Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions .github/workflows/factorio.yml
Original file line number Diff line number Diff line change
@@ -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
7 changes: 5 additions & 2 deletions .github/workflows/games.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 | 其他模式 | 主要内容 | 说明 |
|---|---:|---|---|---|
Expand All @@ -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/) 定义,可以重叠,数量不能直接相加:

Expand Down
90 changes: 90 additions & 0 deletions ci_checks/check-factorio-isolation.py
Original file line number Diff line number Diff line change
@@ -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]))
26 changes: 26 additions & 0 deletions game_first_exam/benchmarks/factorio/README.md
Original file line number Diff line number Diff line change
@@ -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 在构建时解析。
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -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()
Loading