diff --git a/.github/workflows/factorio.yml b/.github/workflows/factorio.yml new file mode 100644 index 0000000..4993544 --- /dev/null +++ b/.github/workflows/factorio.yml @@ -0,0 +1,49 @@ +name: Factorio +on: + push: + branches: [factorio-benchmark] + workflow_call: + workflow_dispatch: +permissions: + contents: read +concurrency: + group: factorio-${{ github.ref }} + cancel-in-progress: true +jobs: + linux-regression: + if: github.ref == 'refs/heads/factorio-benchmark' && github.event_name == 'push' + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@v4 + with: {persist-credentials: false} + - uses: actions/setup-python@v5 + with: {python-version: '3.12'} + - run: python -m pip install -e . + - run: python ci_checks/check-games.py + - run: python game_first_exam/tests/test_game_harbor.py + - run: docker build -f game_first_exam/tests/envs/common.Dockerfile -t game-tests:common . + - run: docker run --rm -v "$PWD:/repo:ro" game-tests:common bash game_first_exam/tests/run.sh common + factorio: + runs-on: ubuntu-latest + timeout-minutes: 45 + steps: + - uses: actions/checkout@v4 + with: {persist-credentials: false} + - uses: actions/setup-python@v5 + with: {python-version: '3.12'} + - run: python -m pip install -e . + - run: harbor run --game-suite factorio -a oracle -k 2 -n 2 --ek keep_containers=true --job-name fle-probe -y + - name: Verify live trial isolation from Docker metadata and native REPL readbacks + run: python ci_checks/check-factorio-isolation.py jobs/fle-probe + - name: Exercise the native scorer with a nonzero fixture + run: | + docker run --rm --network none --entrypoint /opt/fle-venv/bin/python \ + -v "$PWD/game_first_exam:/checks:ro" \ + game-exam-fle:6439e18b7870770454cf91eb36b3d1e6412724f4 /checks/tests/test_factorio.py + - name: Show Harbor diagnostics on failure + if: failure() + run: | + if test -d jobs/fle-probe; then + find jobs/fle-probe -type f \( -name 'exception.txt' -o -name 'trial.log' -o -name 'test-stdout.txt' -o -name 'oracle.txt' \) -exec tail -n 80 {} \; + fi diff --git a/.github/workflows/games.yml b/.github/workflows/games.yml index ebee4f6..56625e1 100644 --- a/.github/workflows/games.yml +++ b/.github/workflows/games.yml @@ -77,8 +77,10 @@ jobs: name: fresh-clone-room-evidence path: jobs/ retention-days: 7 + factorio: + uses: ./.github/workflows/factorio.yml invariants: - needs: [static, adapters, harbor, fresh-clone-smoke] + needs: [static, adapters, harbor, fresh-clone-smoke, factorio] if: ${{ always() }} runs-on: ubuntu-latest steps: @@ -87,4 +89,5 @@ jobs: ADAPTERS: ${{ needs.adapters.result }} HARBOR: ${{ needs.harbor.result }} SMOKE: ${{ needs.fresh-clone-smoke.result }} - run: test "$STATIC" = success && test "$ADAPTERS" = success && test "$HARBOR" = success && test "$SMOKE" = success + FLE: ${{ needs.factorio.result }} + run: test "$STATIC" = success && test "$ADAPTERS" = success && test "$HARBOR" = success && test "$SMOKE" = success && test "$FLE" = success diff --git a/README.md b/README.md index 5e00e1f..691db5b 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ Game Exam 基于 [Embodied First Exam](https://github.com/mll-lab-nu/embodied-fi ## 已接入的游戏 -当前共有 **5 个 benchmark、42 个 standard 任务配置,另外有 1 个 privileged 和 1 个 realtime 配置,共 44 个任务目录**。同一原生任务的不同模式单独计数。 +当前接入 **6 个 benchmark**。其中 5 个提供冻结任务,共 42 个 standard、1 个 privileged 和 1 个 realtime 配置。Factorio Learning Environment 另提供 Lab-play 自动铁板生产任务。 | Benchmark | standard | 其他模式 | 主要内容 | 说明 | |---|---:|---|---|---| @@ -33,6 +33,7 @@ Game Exam 基于 [Embodied First Exam](https://github.com/mll-lab-nu/embodied-fi | TextWorld | 9 | — | 文字探索、寻宝、烹饪 | 冻结 `.z8` 游戏,通过原生引擎执行 | | Baba Is AI | 2 | — | 移动文字、改变规则、解谜 | 基础关卡与复合关卡的最小 smoke 验证 | | MiniHack | 10 | 1 privileged | Room、River、导航、战斗、Quest、Boxoban | 原生 MiniHack/NLE 环境;Room 另有 privileged 版本 | +| Factorio Learning Environment | — | Lab-play 文本交互 | 通过 Python REPL 搭建自动铁板生产线 | [运行与评分说明](game_first_exam/benchmarks/factorio/README.md) | 套件由 [configs/game_suites/](configs/game_suites/) 定义,可以重叠,数量不能直接相加: diff --git a/ci_checks/check-factorio-isolation.py b/ci_checks/check-factorio-isolation.py new file mode 100644 index 0000000..bd9e9bc --- /dev/null +++ b/ci_checks/check-factorio-isolation.py @@ -0,0 +1,90 @@ +"""Inspect two retained Harbor trials on an isolated Linux CI runner.""" +import json +import re +import subprocess +import sys +from pathlib import Path + + +def containers(project): + ids = subprocess.check_output( + ["docker", "ps", "-aq", "--filter", f"label=com.docker.compose.project={project}"], text=True + ).split() + assert ids, f"No containers for Compose project {project}" + rows = json.loads(subprocess.check_output(["docker", "inspect", *ids])) + services = {row["Config"]["Labels"]["com.docker.compose.service"]: row for row in rows} + assert len(services) == len(rows), f"Duplicate service in {project}" + return services + + +def volume(row, path, writable): + mount, = [m for m in row["Mounts"] if m["Destination"] == path] + assert mount["Type"] == "volume" and mount["RW"] is writable, path + return mount["Name"] + + +def check(job): + ids = set() + volumes = set() + starts, ends = [], [] + trials = sorted(job.glob("*/result.json")) + assert len(trials) == 2, f"Expected two completed trials, got {len(trials)}" + for path in trials: + result = json.loads(path.read_text()) + assert result["exception_info"] is None and result["verifier_environment_mode"] == "separate" + project = result["trial_name"].lower() + runtime = containers(project + "__env") + assert set(runtime) == {"main", "engine", "recorder"} + verifier = containers(project + "__verifier__trial") + # Harbor may run its own egress-control service alongside a verifier. + # The grading process itself must still have a private, offline namespace. + assert "main" in verifier and set(verifier) <= {"main", "harbor-docker-egress-control-sidecar"}, set(verifier) + agent, engine, recorder, grader = runtime["main"], runtime["engine"], runtime["recorder"], verifier["main"] + for row in (*runtime.values(), *verifier.values()): + config = row["HostConfig"] + assert not config["Privileged"] and config["PidMode"] != "host" and config["IpcMode"] != "host" + for mount in row["Mounts"]: + assert mount["Destination"] != "/var/run/docker.sock" + if mount["Type"] == "bind": + source = Path(mount["Source"]).resolve() + assert source.name != "docker.sock" and not Path.cwd().is_relative_to(source) + if source.is_relative_to(Path.cwd()): + assert source.is_relative_to(path.parent.resolve()), f"Mount outside trial: {source}" + for row in (engine, recorder, grader): + assert row["HostConfig"]["NetworkMode"] == "none" + assert not row["HostConfig"]["PortBindings"] + for row in (engine, recorder): + assert all(m["Type"] != "bind" for m in row["Mounts"]) + channel = volume(recorder, "/channel", True) + bridge = volume(engine, "/tmp", True) + assert volume(agent, "/channel", False) == channel + assert volume(recorder, "/native", False) == bridge + for row, hidden in ((agent, {bridge}), (engine, {channel})): + assert hidden.isdisjoint(m.get("Name") for m in row["Mounts"]) + for row in verifier.values(): + assert {channel, bridge}.isdisjoint(m.get("Name") for m in row["Mounts"]) + assert bridge != channel and volumes.isdisjoint({bridge, channel}), "Cross-trial shared volume" + volumes.update((bridge, channel)) + assert engine["State"]["Status"] == "exited" + starts.append(engine["State"]["StartedAt"]) + ends.append(engine["State"]["FinishedAt"]) + + trial = path.parent + marker = (trial / "artifacts/logs/artifacts/fle-probe-id").read_text().strip() + assert re.fullmatch(r"[0-9a-f]{32}", marker) and marker not in ids + ids.add(marker) + episode = json.loads((trial / "artifacts/evidence/episode.json").read_text()) + assert episode["sealed"] and episode["fault"] is None + first, second = episode["steps"] + assert first["code"].splitlines()[0] == f"trial_marker = '{marker}'" + assert second["code"].strip() == "print(trial_marker)" + assert [first["number"], second["number"]] == [1, 2] + assert all(not s["error_occurred"] and s["reward"] == 0 for s in (first, second)) + rewards = json.loads((trial / "verifier/reward.json").read_text()) + assert rewards["iron_plate_goal_reached"] == 0 and "fle_inspect_score" in rewards + assert max(starts) < min(ends), "Game engine lifetimes did not overlap" + print("Two overlapping engines, four distinct volumes, two matching REPL readbacks and two isolated verifiers.") + + +if __name__ == "__main__": + check(Path(sys.argv[1])) diff --git a/game_first_exam/benchmarks/factorio/README.md b/game_first_exam/benchmarks/factorio/README.md new file mode 100644 index 0000000..ec80e56 --- /dev/null +++ b/game_first_exam/benchmarks/factorio/README.md @@ -0,0 +1,26 @@ +# Factorio Learning Environment + +套件 `factorio` 提供 FLE v0.4.3 的 `iron_plate_throughput`。目标是在 60 个游戏秒内自动生产至少 16 块铁板。首次运行需要 Linux 容器、Docker Compose v2 和访问镜像仓库及 GitHub 的构建网络。构建使用固定提交中的官方 Dockerfile 和 Factorio 2.0.73。FLE 的 Python 依赖安装在镜像内。[上游任务定义](https://github.com/JackHopkins/factorio-learning-environment/blob/6439e18b7870770454cf91eb36b3d1e6412724f4/fle/eval/tasks/task_definitions/lab_play/throughput_tasks.py) + +```bash +harbor run --game-suite factorio --list +harbor run --game-suite factorio -a oracle --job-name fle-probe -y +harbor run --game-suite factorio -c configs/harbor/codex-deepseek.json --job-name fle-iron -y +``` + +`oracle` 用两次原生动作检查环境,无须模型密钥。它在查询库存时写入本局的随机标记,再从 REPL 读回该标记。两步的铁板产量都应为零。正式运行使用所选 Harbor coding agent。它读取官方 API 说明、结构化观测和执行反馈,向原生 REPL 提交 Python 源码。策略和对话历史由 Harbor agent 管理,因此该模式与作者的 Inspect solver 分开报告。 + +## 隔离 + +每个 Harbor trial(包括重试)使用独立的 Compose 项目、Factorio 进程、REPL 和命名卷。游戏与记录服务均关闭网络。游戏的 RCON 只在引擎容器内可用,记录服务通过私有 Unix socket 调用上游 bridge。agent 以只读方式挂载公开控制 socket 所在目录。套件只声明 trial 专属卷。项目源码目录和宿主 Docker socket 均不在容器挂载清单内。模型凭据与 trial 日志由 Harbor 管理。 + +记录服务串行执行动作,并用步号和源码摘要识别重试。上游执行结果存放在记录服务自己的文件系统。Harbor 在 agent 结束后通过记录容器内部的独立 Unix socket 封存轨迹,再收集 `artifacts/evidence/episode.json` 供断网 verifier 评分。原生 REPL 和游戏 bridge 共享引擎容器,评分依赖上游 bridge 如实返回游戏状态。 + +Linux CI 同时启动两个 Harbor trial,并通过 Docker 运行时记录确认两个引擎的运行时间重叠。检查覆盖容器网络模式、卷标识与读写权限、独立评分容器,以及两局各自的 REPL 标记、封存记录和成绩。agent 的公开 socket 只提供查询和游戏动作。正式模型的联网权限取决于 Harbor agent 配置。 + +## 成绩 + +- `iron_plate_goal_reached` 来自原生 Gym 的 `terminated`,即上游 `ThroughputTask.verify` 的吞吐量判定。逐步的 `reward` 由 Gym 返回。 +- `fle_inspect_score` 来自原版 `comprehensive_factorio_scorer`。verifier 将原生每步的 `production_score` 装入 Inspect 的轨迹对象,再调用上游评分器。该指标依据最终生产分数计算,可能与铁板达标值不同。[上游评分实现](https://github.com/JackHopkins/factorio-learning-environment/blob/6439e18b7870770454cf91eb36b3d1e6412724f4/fle/eval/inspect/integration/scorers.py) + +单局最多提交 64 步,沿用原生任务预算。游戏初始化、执行或评分故障会使验证失败。固定的上游源码提交、协议和任务 ID 记录在 `iron_plate_throughput/task.toml` 中。镜像依赖层固定 `a2a-sdk==0.3.22` 和 `inspect-ai==0.3.139`,以保留 v0.4.3 评分器使用的类型接口。其他传递依赖由官方 Dockerfile 在构建时解析。 diff --git a/game_first_exam/benchmarks/factorio/iron_plate_throughput/environment/Dockerfile b/game_first_exam/benchmarks/factorio/iron_plate_throughput/environment/Dockerfile new file mode 100644 index 0000000..fd2ccd2 --- /dev/null +++ b/game_first_exam/benchmarks/factorio/iron_plate_throughput/environment/Dockerfile @@ -0,0 +1,12 @@ +FROM docker.io/library/python:3.12.10-slim-bookworm@sha256:fd95fa221297a88e1cf49c55ec1828edd7c5a428187e67b5d1805692d11588db AS client +WORKDIR /app +COPY fle_client.py /opt/fle_client.py + +FROM client AS recorder +COPY adapter.py /opt/adapter.py +RUN mkdir -p /channel /evidence && chown 65534:65534 /channel /evidence +USER 65534:65534 +CMD ["python", "/opt/adapter.py"] + +FROM client AS main +RUN mkdir -p /channel && chown 65534:65534 /channel diff --git a/game_first_exam/benchmarks/factorio/iron_plate_throughput/environment/adapter.py b/game_first_exam/benchmarks/factorio/iron_plate_throughput/environment/adapter.py new file mode 100644 index 0000000..75c0d6d --- /dev/null +++ b/game_first_exam/benchmarks/factorio/iron_plate_throughput/environment/adapter.py @@ -0,0 +1,162 @@ +"""Mediate one native FLE episode. The REPL runs only in the engine container.""" +import hashlib +import json +import math +import os +import selectors +import sys +from http.server import BaseHTTPRequestHandler +from pathlib import Path + +from fle_client import request + +TASK = "iron_plate_throughput" +LIMIT = 64 # Checked against the upstream task in the verifier. +COLLECT_SOCKET = "/tmp/fle-collect.sock" # Recorder-private filesystem. + + +def native(command, payload=None): + try: + return request("/native/fle_bridge.sock", command, payload) + except (ValueError, OSError) as error: + raise RuntimeError(f"FLE bridge {command} failed: {error}") from error + + +class Episode: + def __init__(self, call, evidence): + self.call = call + self.evidence = evidence + self.steps = [] + self.last_reply = None + self.sealed = False + self.fault = None + call("reset", {}) + self.prompt = call("system-prompt")["system_prompt"] + self.initial = call("observe") + self.save() + + def save(self): + data = {"task": TASK, "sealed": self.sealed, "fault": self.fault, "steps": self.steps} + tmp = self.evidence.with_suffix(".tmp") + tmp.write_text(json.dumps(data, allow_nan=False), encoding="utf-8") + tmp.replace(self.evidence) + + def status(self): + done = (self.sealed or self.fault is not None or len(self.steps) == LIMIT + or bool(self.steps and (self.steps[-1]["terminated"] or self.steps[-1]["truncated"]))) + return {"steps": len(self.steps), "next_step": None if done else len(self.steps) + 1, + "done": done, "fault": self.fault} + + def execute(self, number, code): + if type(number) is not int or not isinstance(code, str): + raise ValueError("Expected an integer step number and Python source text") + digest = hashlib.sha256(code.encode()).hexdigest() + if self.steps and number == len(self.steps) and digest == self.steps[-1]["code_sha256"]: + return {**self.last_reply, **self.status()} + if number != self.status()["next_step"]: + raise ValueError("Episode closed or unexpected step number. Check status.") + result = self.call("execute", {"agent_idx": 0, "code": code}) + step = {"number": number, "code_sha256": digest, "code": code} + for key in ("reward", "production_score", "automated_production_score"): + value = result[key] + if type(value) not in (float, int) or not math.isfinite(value): + raise RuntimeError(f"Invalid native {key}") + step[key] = value + for key in ("terminated", "truncated", "error_occurred"): + if type(result[key]) is not bool: + raise RuntimeError(f"Invalid native {key}") + step[key] = result[key] + self.steps.append(step) + self.save() + # Rollback snapshots are private to the upstream bridge. + self.last_reply = {k: v for k, v in result.items() if k != "game_state_raw"} + self.last_reply.update(self.status()) + return self.last_reply + + def dispatch(self, method, path, payload): + if (method, path) == ("GET", "/status"): + return self.status() + if self.fault: + raise RuntimeError(self.fault) + if (method, path) == ("GET", "/prompt"): + return {"system_prompt": self.prompt} + if (method, path) == ("GET", "/observe"): + return self.call("observe") if self.steps else self.initial + if (method, path) == ("POST", "/step"): + return self.execute(payload.get("number"), payload.get("code")) + raise ValueError("Unknown operation") + + def seal(self): + if self.fault: + raise RuntimeError(self.fault) + self.sealed = True + self.save() + return self.status() + + +class Handler(BaseHTTPRequestHandler): + def log_message(self, fmt, *args): + pass + + def dispatch(self, episode, payload): + return episode.dispatch(self.command, self.path, payload) + + def handle_request(self): + episode = self.server.episode + try: + length = int(self.headers.get("Content-Length", 0)) + if not 0 <= length <= 1024 * 1024: + raise ValueError("Request exceeds the 1 MiB transport limit") + payload = json.loads(self.rfile.read(length)) if length else {} + if not isinstance(payload, dict): + raise ValueError("Expected a JSON object") + result = self.dispatch(episode, payload) + status = 200 + except ValueError as error: + status, result = 400, {"error": str(error)} + except Exception as error: + # The engine could already have applied an action. Never retry that step. + if episode.fault is None: + episode.fault = f"Native environment failure ({type(error).__name__}): {error}" + episode.save() + status, result = 503, {"error": episode.fault} + body = json.dumps(result).encode() + self.send_response(status) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + do_GET = do_POST = handle_request + timeout = 15 + + +class CollectHandler(Handler): + def dispatch(self, episode, payload): + if (self.command, self.path) != ("POST", "/seal"): + raise ValueError("Unknown collection operation") + return episode.seal() + + +def serve(): + from socketserver import UnixStreamServer + + sock = Path("/channel/game.sock") + with (UnixStreamServer(str(sock), Handler) as public, + UnixStreamServer(COLLECT_SOCKET, CollectHandler) as private, + selectors.DefaultSelector() as ready): + os.chmod(sock, 0o666) + os.chmod(COLLECT_SOCKET, 0o600) + public.episode = private.episode = Episode(native, Path("/evidence/episode.json")) + for server in (public, private): + ready.register(server, selectors.EVENT_READ) + # Both listeners use the same thread. A collection waits for an in-flight step. + while True: + for key, _ in ready.select(): + key.fileobj.handle_request() + + +if __name__ == "__main__": + if sys.argv[1:] == ["seal"]: + print(json.dumps(request(COLLECT_SOCKET, "seal", {}))) + else: + serve() diff --git a/game_first_exam/benchmarks/factorio/iron_plate_throughput/environment/docker-compose.yaml b/game_first_exam/benchmarks/factorio/iron_plate_throughput/environment/docker-compose.yaml new file mode 100644 index 0000000..f08122a --- /dev/null +++ b/game_first_exam/benchmarks/factorio/iron_plate_throughput/environment/docker-compose.yaml @@ -0,0 +1,40 @@ +services: + main: + depends_on: + recorder: {condition: service_healthy} + volumes: ["channel:/channel:ro"] + engine: + image: game-exam-fle:6439e18b7870770454cf91eb36b3d1e6412724f4 + pull_policy: never + network_mode: none + init: true + cpus: 1.5 + mem_limit: 2048m + security_opt: ["no-new-privileges:true"] + environment: + FLE_ENV_ID: iron_plate_throughput + FLE_SCENARIO: default_lab_scenario + FLE_NUM_AGENTS: "1" + volumes: ["bridge:/tmp"] + healthcheck: + test: ["CMD", "/opt/fle-venv/bin/python3", "/opt/fle/bridge_client.py", "health"] + interval: 3s + timeout: 5s + retries: 80 + recorder: + build: {context: ., target: recorder} + network_mode: none + init: true + cap_drop: [ALL] + security_opt: ["no-new-privileges:true"] + volumes: ["bridge:/native:ro", "channel:/channel"] + depends_on: + engine: {condition: service_healthy} + healthcheck: + test: ["CMD", "python", "/opt/fle_client.py", "status"] + interval: 3s + timeout: 5s + retries: 80 +volumes: + channel: {} + bridge: {} diff --git a/game_first_exam/benchmarks/factorio/iron_plate_throughput/environment/fle_client.py b/game_first_exam/benchmarks/factorio/iron_plate_throughput/environment/fle_client.py new file mode 100644 index 0000000..ee3a869 --- /dev/null +++ b/game_first_exam/benchmarks/factorio/iron_plate_throughput/environment/fle_client.py @@ -0,0 +1,49 @@ +"""Public command-line client. No game code is evaluated here.""" +import argparse +import http.client +import json +import socket +import sys +from pathlib import Path + + +class Connection(http.client.HTTPConnection): + def __init__(self, path): + super().__init__("localhost", timeout=360) + self.path = path + + def connect(self): + self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + self.sock.settimeout(self.timeout) + self.sock.connect(self.path) + + +def request(path, command, payload=None): + conn = Connection(path) + try: + body = None if payload is None else json.dumps(payload).encode() + conn.request("GET" if body is None else "POST", "/" + command, body, + {"Content-Type": "application/json"}) + response = conn.getresponse() + result = json.load(response) + if response.status != 200: + raise ValueError(result.get("error", f"HTTP {response.status}")) + return result + finally: + conn.close() + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + commands = parser.add_subparsers(dest="command", required=True) + for command in ("status", "prompt", "observe"): + commands.add_parser(command) + step = commands.add_parser("step") + step.add_argument("number", type=int) + step.add_argument("file", help="Python source file, or - for stdin") + args = parser.parse_args() + payload = None + if args.command == "step": + code = sys.stdin.read() if args.file == "-" else Path(args.file).read_text(encoding="utf-8") + payload = {"number": args.number, "code": code} + print(json.dumps(request("/channel/game.sock", args.command, payload), ensure_ascii=False)) diff --git a/game_first_exam/benchmarks/factorio/iron_plate_throughput/instruction.md b/game_first_exam/benchmarks/factorio/iron_plate_throughput/instruction.md new file mode 100644 index 0000000..c8ac0cc --- /dev/null +++ b/game_first_exam/benchmarks/factorio/iron_plate_throughput/instruction.md @@ -0,0 +1,9 @@ +# Build an automatic iron plate factory + +Use the Factorio Learning Environment to produce at least 16 iron plates automatically per 60 in-game seconds. You have one factory and up to 64 REPL actions. + +Run `python /opt/fle_client.py prompt` for the game's Python API, and `python /opt/fle_client.py observe` for the current state. Each observation is JSON and includes inventory, nearby entities and game information. + +Write a program using the FLE API and submit it with `python /opt/fle_client.py step 1 program.py`. Each submission runs in the same game's Python namespace. Read the native output, reward and termination flags. Use the returned `next_step` for your next submission. If a response is lost, repeat the same step number and identical source. You can look up progress with `python /opt/fle_client.py status`. + +FLE checks automatic iron plate production after each action. The trial also reports the upstream Inspect production score. Stop when the factory reaches the target or the budget runs out. diff --git a/game_first_exam/benchmarks/factorio/iron_plate_throughput/solution/solve.sh b/game_first_exam/benchmarks/factorio/iron_plate_throughput/solution/solve.sh new file mode 100755 index 0000000..1e23c5a --- /dev/null +++ b/game_first_exam/benchmarks/factorio/iron_plate_throughput/solution/solve.sh @@ -0,0 +1,17 @@ +#!/bin/sh +# Offline probe using the native inventory API and a per-trial REPL variable. +set -eu +test ! -e /evidence +test ! -e /native/fle_bridge.sock +test ! -e /tmp/fle-collect.sock +test ! -e /var/run/docker.sock +python /opt/fle_client.py prompt >/dev/null +python /opt/fle_client.py observe >/dev/null +marker=$(python -c 'import uuid; print(uuid.uuid4().hex)') +printf "trial_marker = '%s'\nprint(inspect_inventory())\n" "$marker" > /tmp/check_inventory.py +python /opt/fle_client.py step 1 /tmp/check_inventory.py > /tmp/step.json +python -c 'import json; r=json.load(open("/tmp/step.json")); assert r["next_step"] == 2 and not r["error_occurred"] and r["reward"] == 0' +echo 'print(trial_marker)' | python /opt/fle_client.py step 2 - > /tmp/readback.json +python -c 'import json,sys; r=json.load(open("/tmp/readback.json")); assert not r["error_occurred"] and sys.argv[1] in r["result"]' "$marker" +mkdir -p /logs/artifacts +printf '%s\n' "$marker" > /logs/artifacts/fle-probe-id diff --git a/game_first_exam/benchmarks/factorio/iron_plate_throughput/task.toml b/game_first_exam/benchmarks/factorio/iron_plate_throughput/task.toml new file mode 100644 index 0000000..2975717 --- /dev/null +++ b/game_first_exam/benchmarks/factorio/iron_plate_throughput/task.toml @@ -0,0 +1,25 @@ +schema_version = "1.3" +artifacts = [{ source = "/evidence", service = "recorder" }] + +[task] +name = "game-exam/iron_plate_throughput" +description = "Factorio Learning Environment Lab-play iron plate throughput" + +[metadata] +source = "https://github.com/JackHopkins/factorio-learning-environment.git" +source_commit = "6439e18b7870770454cf91eb36b3d1e6412724f4" +upstream_release = "v0.4.3" +env_id = "iron_plate_throughput" +protocol = "fle/lab-play-text" + +[agent] +timeout_sec = 14400 + +[verifier] +environment_mode = "separate" +network_mode = "no-network" +timeout_sec = 600 + +[[verifier.collect]] +service = "recorder" +command = "python /opt/adapter.py seal" diff --git a/game_first_exam/benchmarks/factorio/iron_plate_throughput/tests/Dockerfile b/game_first_exam/benchmarks/factorio/iron_plate_throughput/tests/Dockerfile new file mode 100644 index 0000000..b301393 --- /dev/null +++ b/game_first_exam/benchmarks/factorio/iron_plate_throughput/tests/Dockerfile @@ -0,0 +1,5 @@ +FROM game-exam-fle:6439e18b7870770454cf91eb36b3d1e6412724f4 +ENTRYPOINT [] +WORKDIR /tests +COPY grade.py test.sh /tests/ +RUN chmod +x /tests/test.sh diff --git a/game_first_exam/benchmarks/factorio/iron_plate_throughput/tests/docker-compose.yaml b/game_first_exam/benchmarks/factorio/iron_plate_throughput/tests/docker-compose.yaml new file mode 100644 index 0000000..f9e01ab --- /dev/null +++ b/game_first_exam/benchmarks/factorio/iron_plate_throughput/tests/docker-compose.yaml @@ -0,0 +1,3 @@ +services: + main: + network_mode: none diff --git a/game_first_exam/benchmarks/factorio/iron_plate_throughput/tests/grade.py b/game_first_exam/benchmarks/factorio/iron_plate_throughput/tests/grade.py new file mode 100644 index 0000000..06045f5 --- /dev/null +++ b/game_first_exam/benchmarks/factorio/iron_plate_throughput/tests/grade.py @@ -0,0 +1,62 @@ +"""Feed the sealed numeric trajectory to FLE's original Inspect scorer.""" +import hashlib +import json +import math +from pathlib import Path + + +def validate(episode, task): + if episode["task"] != task.task_key or episode["sealed"] is not True or episode["fault"] is not None: + raise ValueError("Unsealed, mismatched or failed FLE episode") + steps = episode["steps"] + if task.trajectory_length != 64 or not isinstance(steps, list) or len(steps) > task.trajectory_length: + raise ValueError("Invalid trajectory budget") + for n, step in enumerate(steps, start=1): + if step["number"] != n or hashlib.sha256(step["code"].encode()).hexdigest() != step["code_sha256"]: + raise ValueError("Invalid step trace") + for key in ("reward", "production_score", "automated_production_score"): + if type(step[key]) not in (int, float) or not math.isfinite(step[key]): + raise ValueError(f"Invalid {key}") + if any(type(step[k]) is not bool for k in ("terminated", "truncated", "error_occurred")): + raise ValueError("Invalid native step flags") + if n < len(steps) and (step["terminated"] or step["truncated"]): + raise ValueError("Actions after native termination") + return steps + + +def grade(episode, output): + from fle.eval.inspect.eval_set import create_throughput_task + from fle.eval.inspect.integration.solver import TrajectoryData + from fle.eval.tasks.task_definitions.lab_play.throughput_tasks import iron_plate_throughput as task + from inspect_ai import eval as evaluate + from inspect_ai.solver import solver + from inspect_ai.util import store_as + + steps = validate(episode, task) + + @solver + def recorded_trajectory(): + async def solve(state, generate): + trajectory = store_as(TrajectoryData) + trajectory.scores = [step["production_score"] for step in steps] + trajectory.total_steps = len(steps) + trajectory.final_score = trajectory.scores[-1] if steps else 0.0 + trajectory.production_score = trajectory.final_score + return state + return solve + + evaluation = create_throughput_task(task.task_key, target=task.quota, solver=recorded_trajectory()) + log, = evaluate(evaluation, model="mockllm/model", log_dir=str(output / "inspect"), + log_realtime=False, display="none") + if log.status != "success" or not log.samples or log.samples[0].error: + raise RuntimeError("FLE Inspect grading failed (see the verifier Inspect log)") + score, = log.samples[0].scores.values() + if not score.metadata or score.metadata.get("has_error") is not False: + raise ValueError("Upstream scorer did not return a valid trajectory score") + rewards = {"fle_inspect_score": float(score.value), + "iron_plate_goal_reached": int(bool(steps and steps[-1]["terminated"]))} + (output / "reward.json").write_text(json.dumps(rewards, allow_nan=False)) + + +if __name__ == "__main__": + grade(json.loads(Path("/evidence/episode.json").read_text()), Path("/logs/verifier")) diff --git a/game_first_exam/benchmarks/factorio/iron_plate_throughput/tests/test.sh b/game_first_exam/benchmarks/factorio/iron_plate_throughput/tests/test.sh new file mode 100755 index 0000000..da6a2cb --- /dev/null +++ b/game_first_exam/benchmarks/factorio/iron_plate_throughput/tests/test.sh @@ -0,0 +1,7 @@ +#!/bin/sh +set -eu +test ! -e /channel/game.sock +test ! -e /native/fle_bridge.sock +test ! -e /tmp/fle-collect.sock +test ! -e /var/run/docker.sock +exec /opt/fle-venv/bin/python /tests/grade.py diff --git a/game_first_exam/benchmarks/factorio/runtime/Dockerfile b/game_first_exam/benchmarks/factorio/runtime/Dockerfile new file mode 100644 index 0000000..93c3e87 --- /dev/null +++ b/game_first_exam/benchmarks/factorio/runtime/Dockerfile @@ -0,0 +1,5 @@ +ARG UPSTREAM_IMAGE +FROM ${UPSTREAM_IMAGE} +# v0.4.3 imports a2a.types.TextPart, which was removed in a2a-sdk 1.x. +RUN /opt/fle-venv/bin/pip install --no-cache-dir "a2a-sdk==0.3.22" "inspect-ai==0.3.139" \ + && /opt/fle-venv/bin/python -c "from fle.eval.inspect.integration.scorers import comprehensive_factorio_scorer; from fle.eval.tasks import TaskFactory; t = TaskFactory.create_task('iron_plate_throughput'); assert (t.trajectory_length, t.quota, t.throughput_entity) == (64, 16, 'iron-plate')" diff --git a/game_first_exam/tests/test_factorio.py b/game_first_exam/tests/test_factorio.py new file mode 100644 index 0000000..612c113 --- /dev/null +++ b/game_first_exam/tests/test_factorio.py @@ -0,0 +1,104 @@ +"""FLE adapter boundaries and a known trajectory scored by the pinned authors' code.""" +import json +from http.client import HTTPConnection +from http.server import HTTPServer +from pathlib import Path +import sys +import tempfile +from threading import Thread +import unittest +from unittest.mock import Mock + +TASK = Path(__file__).resolve().parents[1] / "benchmarks/factorio/iron_plate_throughput" +sys.path[:0] = [str(TASK / "environment"), str(TASK / "tests")] +from adapter import Episode, Handler +from grade import grade, validate + + +class FactorioTests(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = Path(tmp.name) + self.output = self.root / "episode.json" + self.reply = {"reward": 2, "production_score": 8, "automated_production_score": 4, + "terminated": False, "truncated": False, "error_occurred": False, + "game_state_raw": "private upstream snapshot", "result": "observed"} + self.bridge = Mock(side_effect=lambda cmd, payload=None: + {"reset": {}, "observe": {"entities": []}, "system-prompt": {"system_prompt": "api"}, + "execute": self.reply}[cmd]) + self.session = Episode(self.bridge, self.output) + + def test_retry_is_one_native_action(self): + result = self.session.execute(1, "print(1)") + self.assertEqual(result, self.session.execute(1, "print(1)")) + self.assertNotIn("game_state_raw", result) + with self.assertRaises(ValueError): + self.session.execute(1, "print(2)") + self.assertEqual([call.args for call in self.bridge.call_args_list if call.args[0] == "execute"], + [("execute", {"agent_idx": 0, "code": "print(1)"})]) + for route in ("/reset", "/game-state", "/execute", "/seal"): + with self.assertRaises(ValueError): + self.session.dispatch("POST", route, {}) + self.assertFalse(self.session.sealed) + + def test_native_end_and_budget(self): + for i in range(1, 65): + self.session.execute(i, "print(1)") + with self.assertRaises(ValueError): + self.session.execute(65, "print(1)") + self.assertFalse(self.session.steps[-1]["terminated"]) + + def test_native_termination_ends_episode_before_budget(self): + self.reply.update(terminated=True, reward=16) + self.assertIsNone(self.session.execute(1, "sleep(60)")["next_step"]) + with self.assertRaises(ValueError): + self.session.execute(2, "sleep(60)") + + def test_failed_native_step_cannot_be_retried_or_graded(self): + self.bridge.side_effect = RuntimeError("native connection lost") + with HTTPServer(("127.0.0.1", 0), Handler) as server: + server.episode = self.session + thread = Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + for command, payload in (("step", {"number": 1, "code": "sleep(1)"}), + ("step", {"number": 1, "code": "sleep(1)"}), ("seal", {})): + conn = HTTPConnection(*server.server_address, timeout=5) + try: + conn.request("POST", "/" + command, json.dumps(payload)) + response = conn.getresponse() + self.assertEqual(response.status, 503) + self.assertIn("native connection lost", json.load(response)["error"]) + finally: + conn.close() + finally: + server.shutdown() + thread.join() + self.assertEqual(sum(call.args[0] == "execute" for call in self.bridge.call_args_list), 1) + saved = json.loads(self.output.read_text()) + self.assertIsNotNone(saved["fault"]) + self.assertFalse(saved["sealed"]) + with self.assertRaises(RuntimeError): + self.session.seal() + + def test_native_scorer_and_target_are_distinct(self): + from fle.eval.tasks.task_definitions.lab_play.throughput_tasks import iron_plate_throughput + + self.session.execute(1, "print(1)") + with self.assertRaises(ValueError): + validate(json.loads(self.output.read_text()), iron_plate_throughput) + self.session.seal() + with self.assertRaises(ValueError): + self.session.execute(2, "print(2)") + episode = json.loads(self.output.read_text()) + grade(episode, self.root) + self.assertEqual(json.loads((self.root / "reward.json").read_text()), + {"fle_inspect_score": 0.5, "iron_plate_goal_reached": 0}) + episode["fault"] = "bridge disconnected" + with self.assertRaises(ValueError): + validate(episode, iron_plate_throughput) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/efe.py b/scripts/efe.py index 16d55c7..d531fad 100755 --- a/scripts/efe.py +++ b/scripts/efe.py @@ -335,6 +335,12 @@ def run(argv: list[str], app=None) -> int: games = _Scripts("prepare_games") if game_suite is None: game_suite = "all" if which == "all" else "core" + if game_suite == "factorio": + if modes or benches or paths or set(families) - {"lab-play"}: + print("Factorio uses the native Lab-play task. Select with --family lab-play or -i.", file=sys.stderr) + return 2 + return _Scripts("factorio").launch(find_root(), inc, exc, n_tasks, listing, rest, + lambda args: harbor(args, app)) if game_suite is not None: try: suite, plans = games.load_suite(game_suite) diff --git a/scripts/factorio.py b/scripts/factorio.py new file mode 100644 index 0000000..21d1e2c --- /dev/null +++ b/scripts/factorio.py @@ -0,0 +1,34 @@ +"""Run the pinned native FLE task with a Harbor agent.""" +import fnmatch +import subprocess +import sys +import tomllib + + +def launch(root, include, exclude, limit, listing, args, harbor): + task = root / "game_first_exam/benchmarks/factorio/iron_plate_throughput" + name = task.name + if (limit == 0 or (include and not any(fnmatch.fnmatchcase(name, p) for p in include)) + or any(fnmatch.fnmatchcase(name, p) for p in exclude)): + print("No matching Factorio task", file=sys.stderr) + return 2 + if listing: + print(name) + return 0 + spec = tomllib.loads((task / "task.toml").read_text(encoding="utf-8"))["metadata"] + revision = spec["source_commit"] + image = f"game-exam-fle:{revision}" + upstream_image = f"game-exam-fle-upstream:{revision}" + # Build the authors' Dockerfile against the exact matching remote tree. + # Only the local image store is shared between trials. + try: + subprocess.run(["docker", "build", "-t", upstream_image, "-f", "fle/eval/inspect/sandbox/Dockerfile", + f'{spec["source"]}#{revision}'], check=True) + subprocess.run(["docker", "build", "--build-arg", f"UPSTREAM_IMAGE={upstream_image}", + "-t", image, str(task.parent / "runtime")], check=True) + except FileNotFoundError: + print("Factorio requires Docker with Linux containers and Compose v2.", file=sys.stderr) + return 2 + except subprocess.CalledProcessError as exc: + return exc.returncode + return harbor(["run", "-p", str(task), *args])