diff --git a/.github/workflows/games.yml b/.github/workflows/games.yml index ebee4f6..68665b3 100644 --- a/.github/workflows/games.yml +++ b/.github/workflows/games.yml @@ -41,7 +41,38 @@ jobs: with: {python-version: '3.12'} - run: python -m pip install -e . - run: harbor run --game-suite minihack-balrog --standard --list + - run: harbor run --game-suite connectfour --standard --list - run: python game_first_exam/tests/test_game_harbor.py + connectfour-smoke: + runs-on: ubuntu-latest + timeout-minutes: 35 + steps: + - uses: actions/checkout@v4 + with: {persist-credentials: false} + - uses: actions/setup-python@v5 + with: {python-version: '3.12'} + - uses: docker/setup-docker-action@v5 + with: + version: v29.5.2 + set-host: true + daemon-config: '{"features":{"containerd-snapshotter":true}}' + - run: python -m pip install -e . -r game_first_exam/benchmarks/connectfour/requirements.txt + - run: python game_first_exam/tests/test_connectfour.py + - name: Win through Harbor + run: | + harbor run --game-suite connectfour --standard \ + -c configs/harbor/oracle.json --plugin game_harbor:GameRecords \ + --jobs-dir "$PWD/jobs" --job-name connectfour-win -y + - name: Loss through Harbor + run: python game_first_exam/tests/benchmarks/connectfour/loss/run_harbor.py + - name: Check both native results and recordings + run: python ci_checks/check-connectfour-result.py jobs/connectfour-win jobs/connectfour-loss + - uses: actions/upload-artifact@v4 + if: always() + with: + name: connectfour-evidence + path: jobs/ + retention-days: 7 fresh-clone-smoke: runs-on: ubuntu-latest timeout-minutes: 30 @@ -78,7 +109,7 @@ jobs: path: jobs/ retention-days: 7 invariants: - needs: [static, adapters, harbor, fresh-clone-smoke] + needs: [static, adapters, harbor, fresh-clone-smoke, connectfour-smoke] if: ${{ always() }} runs-on: ubuntu-latest steps: @@ -87,4 +118,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 + CONNECTFOUR: ${{ needs.connectfour-smoke.result }} + run: test "$STATIC" = success && test "$ADAPTERS" = success && test "$HARBOR" = success && test "$SMOKE" = success && test "$CONNECTFOUR" = success diff --git a/README.md b/README.md index 5e00e1f..477ee7d 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、43 个 standard 任务配置,另外有 1 个 privileged 和 1 个 realtime 配置,共 45 个任务目录**。同一原生任务的不同模式单独计数。 | 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 版本 | +| [PettingZoo Connect Four](game_first_exam/tasks/connectfour/README.md) | 1 | — | 棋盘规划与固定对手对弈 | 冻结红方对局,含胜负录像 | 套件由 [configs/game_suites/](configs/game_suites/) 定义,可以重叠,数量不能直接相加: @@ -46,7 +47,8 @@ Game Exam 基于 [Embodied First Exam](https://github.com/mll-lab-nu/embodied-fi | `babaisai` | 2 | Baba Is AI smoke | | `minihack` | 3 | Room/River standard + Room privileged | | `minihack-balrog` | 8 | 参考 BALROG 选取的原生 MiniHack 任务 | -| `all` | 44 | 所有套件去重后的任务;汇总时应选择一种模式 | +| `connectfour` | 1 | PettingZoo Connect Four 固定对局 | +| `all` | 45 | 所有套件去重后的任务;汇总时应选择一种模式 | `minihack-balrog` 包含 MazeWalk 9×9、MazeWalk 15×15、Corridor R3、CorridorBattle Dark、Quest Easy、Quest Medium、Boxoban Medium、Boxoban Hard。**使用相同原生环境名称不意味着与 BALROG 的 LLM 输入、prompt、agent、seed 和预算完全相同**,成绩不能直接当作 BALROG 排行榜成绩。 @@ -153,7 +155,7 @@ harbor run --game-suite minihack --standard --family room \ | 模式 | 执行方式 | 当前覆盖 | |---|---|---| -| `standard` | agent 通过客户端操作可信模拟器,按动作推进;对 live episode 评分 | 5 个游戏、42 个配置 | +| `standard` | agent 通过客户端操作可信模拟器,按动作推进;对 live episode 评分 | 6 个游戏、43 个配置 | | `privileged` | agent 可本地探索和规划;最终动作序列由独立 verifier 重新执行 | MiniHack Room | | `realtime` | 首次有效动作计划启动固定 tick;程序与模型思考期间游戏继续推进 | Crafter survival i01 | diff --git a/ci_checks/check-connectfour-result.py b/ci_checks/check-connectfour-result.py new file mode 100644 index 0000000..f7ac173 --- /dev/null +++ b/ci_checks/check-connectfour-result.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python3 +"""Check the winning and losing Harbor trials independently.""" + +import json +import sys +from pathlib import Path + + +def check(job: Path, outcome: str, score: int): + trials = list(job.glob("*/result.json")) + if len(trials) != 1: + raise ValueError(f"{job}: expected one completed trial, found {len(trials)}") + + trial = trials[0].parent + result = json.loads(trials[0].read_text()) + reward = json.loads((trial / "verifier/reward.json").read_text()) + final = json.loads((trial / "artifacts/data/final.json").read_text()) + recording = json.loads((trial / "artifacts/data/recording.json").read_text()) + + if result.get("exception_info") is not None or result["task_name"].split("/")[-1] != "connectfour-match-i01-standard": + raise ValueError(f"{job}: wrong task or Harbor exception") + if reward["result_valid"] != 1 or reward["primary_score"] != score or reward["success"] != score: + raise ValueError(f"{job}: unexpected verifier grade") + if any(reward.get(key) != 0 for key in ("infra_error", "sim_error", "environment_error")): + raise ValueError(f"{job}: environment or simulator error") + if (final["metrics"]["outcome"] != outcome or final["success"] != bool(score) + or final["metrics"]["agent_decisions"] != 12 or final["steps"] != 12): + raise ValueError(f"{job}: native match did not reach its expected outcome") + if recording.get("render_error") is not None or not (trial / "artifacts/data/replay.mp4").stat().st_size: + raise ValueError(f"{job}: replay missing or rendering failed") + print(f"{job}: {outcome}, score {score}, 12 decisions, replay recorded") + + +if __name__ == "__main__": + check(Path(sys.argv[1]), "win", 1) + check(Path(sys.argv[2]), "loss", 0) diff --git a/configs/game_benchmarks.toml b/configs/game_benchmarks.toml index 8f77b59..5a6c791 100644 --- a/configs/game_benchmarks.toml +++ b/configs/game_benchmarks.toml @@ -14,3 +14,6 @@ schema = "game_first_exam/benchmarks/babaisai/instance_schema.py" [benchmarks.minihack] schema = "game_first_exam/benchmarks/minihack/instance_schema.py" + +[benchmarks.connectfour] +schema = "game_first_exam/benchmarks/connectfour/instance_schema.py" diff --git a/configs/game_suites/connectfour.toml b/configs/game_suites/connectfour.toml new file mode 100644 index 0000000..378d312 --- /dev/null +++ b/configs/game_suites/connectfour.toml @@ -0,0 +1,10 @@ +schema_version = "game-suite/2.1" +version = "1.0.0" +tier = "smoke" +name = "games-connectfour-minimal-v1.0.0" +files_images = ["connection-files", "game-files", "connectfour-files"] + +[[tasks]] +name = "connectfour-match-i01-standard" +benchmark = "connectfour" +family = "fixed-opponent" diff --git a/docs/demos/connectfour/red-loss.mp4 b/docs/demos/connectfour/red-loss.mp4 new file mode 100644 index 0000000..6369b92 Binary files /dev/null and b/docs/demos/connectfour/red-loss.mp4 differ diff --git a/docs/demos/connectfour/red-win.mp4 b/docs/demos/connectfour/red-win.mp4 new file mode 100644 index 0000000..7a80d60 Binary files /dev/null and b/docs/demos/connectfour/red-win.mp4 differ diff --git a/game_first_exam/benchmarks/connectfour/SOURCE.json b/game_first_exam/benchmarks/connectfour/SOURCE.json new file mode 100644 index 0000000..d122e40 --- /dev/null +++ b/game_first_exam/benchmarks/connectfour/SOURCE.json @@ -0,0 +1,6 @@ +{ + "repository": "https://github.com/Farama-Foundation/PettingZoo", + "environment": "classic/connect_four-v3", + "package": "pettingzoo==1.26.1", + "opponent": "block-win-hash-v1, implemented in opponent.py" +} diff --git a/game_first_exam/benchmarks/connectfour/adapter.py b/game_first_exam/benchmarks/connectfour/adapter.py new file mode 100644 index 0000000..e9dece8 --- /dev/null +++ b/game_first_exam/benchmarks/connectfour/adapter.py @@ -0,0 +1,108 @@ +"""One column decision for Red, followed by one fixed Yellow response.""" + +import copy +from importlib.metadata import version + +import numpy as np +from pettingzoo.classic import connect_four_v3 + +from contracts import Capabilities, Transition +from encoding import png, state_hash +from opponent import choose + + +RED, YELLOW = "player_0", "player_1" + + +class Adapter: + def __init__(self, instance, assets=None): + if version("pettingzoo") != instance["engine_version"]: + raise ValueError("The pinned Connect Four version is not installed") + self.instance = instance + self.env = connect_four_v3.env(render_mode="rgb_array") + try: + self.env.reset(seed=instance["seed"]) + self.turns = [] + self.decisions = 0 + self.outcome = "playing" + self.native_rewards = (0, 0) + self.capture() + except BaseException: + self.env.close() + raise + + def spec(self): + return {"adapter_version": "1.0.0", + "capabilities": Capabilities(True, "enum", native_truncation=True).to_dict(), + "action_schema": {"type": "string", "enum": [str(i) for i in range(7)]}, + "goal": "Win a native Connect Four match as Red."} + + def board(self): + return list(self.env.unwrapped.board) + + def legal(self, actor): + return [int(column) for column in np.flatnonzero(self.env.observe(actor)["action_mask"])] + + def capture(self): + frame = self.env.render() + # The native 891-pixel board needs one padded pixel for H.264 recording. + if frame.shape[1] % 2: + frame = np.pad(frame, ((0, 0), (0, 1), (0, 0)), mode="edge") + self.rgb = np.ascontiguousarray(frame) + + def observe(self): + return {"image_png_base64": png(self.rgb), + "board": [self.board()[row:row + 7] for row in range(0, 42, 7)], + "legal_columns": [] if self.outcome != "playing" else self.legal(RED), + "last_moves": copy.deepcopy(self.turns[-2:]), + "outcome": self.outcome} + + def play(self, actor, column): + if self.env.agent_selection != actor: + raise RuntimeError("Unexpected Connect Four turn") + legal = self.legal(actor) + before = self.board() + self.env.step(column) + after = self.board() + self.native_rewards = tuple(self.env.rewards[agent] for agent in (RED, YELLOW)) + if all(self.env.terminations.values()): + self.outcome = ("illegal" if column not in legal else + "win" if self.native_rewards[0] == 1 else + "loss" if self.native_rewards[0] == -1 else "draw") + self.turns.append({"actor": actor, "column": column, "board_before": before, + "board_after": after, "rewards": list(self.native_rewards)}) + + def step(self, action): + if self.outcome != "playing": + raise ValueError("Match already ended") + self.decisions += 1 + self.play(RED, int(action)) + reward = self.native_rewards[0] + if self.outcome == "playing": + response = choose(self.board(), self.legal(YELLOW), self.instance["opponent_seed"]) + self.play(YELLOW, response) + reward += self.native_rewards[0] + self.capture() + return Transition(float(reward), self.outcome != "playing", + self.outcome == "illegal") + + def success(self): + return self.outcome == "win" + + def metrics(self): + return {"outcome": self.outcome, "success": int(self.success()), + "native_rewards": list(self.native_rewards), "agent_decisions": self.decisions, + "total_plies": len(self.turns), "final_board": self.board(), + "moves": copy.deepcopy(self.turns)} + + def fingerprint(self): + return state_hash({"board": self.board(), "turn": self.env.agent_selection, + "outcome": self.outcome, "seed": self.instance["seed"], + "opponent_seed": self.instance["opponent_seed"], + "policy": self.instance["opponent_policy"]}) + + def frame(self): + return self.rgb + + def close(self): + self.env.close() diff --git a/game_first_exam/benchmarks/connectfour/instance_schema.py b/game_first_exam/benchmarks/connectfour/instance_schema.py new file mode 100644 index 0000000..b681a97 --- /dev/null +++ b/game_first_exam/benchmarks/connectfour/instance_schema.py @@ -0,0 +1,25 @@ +"""Frozen Connect Four settings shared by the host and isolated verifier.""" + +BENCHMARK = "connectfour" +SCHEMA_VERSION = "1.0.0" +FIELDS = {"engine_version", "opponent_policy", "opponent_seed", "controlled_agent"} +PROFILES = {"native-rgb-board-v1"} +METRICS = {"success"} +REDUCERS = {("family_macro", "1.0.0")} + + +def validate(value): + expected = { + "env_id": "connect_four_v3", "family": "fixed-opponent", + "engine_version": "1.26.1", "controlled_agent": "player_0", + "opponent_policy": "block-win-hash-v1", "opponent_seed": 2117382936, + "capabilities": {"images": True, "action_mode": "enum", "timing": "action-stepped", + "native_truncation": True}, + "metric_spec": {"primary": "success", "reducer": "family_macro", + "reducer_version": "1.0.0", "success_label": "native_red_win"}, + } + for key, frozen in expected.items(): + if value[key] != frozen: + raise ValueError(f"Unsupported Connect Four {key}") + if value["max_steps"] != 21: + raise ValueError("Connect Four has at most 21 Red turns") diff --git a/game_first_exam/benchmarks/connectfour/metric_rules.py b/game_first_exam/benchmarks/connectfour/metric_rules.py new file mode 100644 index 0000000..f73917b --- /dev/null +++ b/game_first_exam/benchmarks/connectfour/metric_rules.py @@ -0,0 +1,52 @@ +"""Independently replay public Connect Four moves and check the native verdict.""" + +from opponent import choose, winning_move + + +def validate_metrics(final, instance): + metrics = final["metrics"] + board = [0] * 42 + moves = metrics["moves"] + if not isinstance(moves, list) or len(moves) > 42: + raise ValueError("Invalid Connect Four move count") + + outcome = "playing" + for index, move in enumerate(moves): + actor = "player_0" if index % 2 == 0 else "player_1" + player = 1 if index % 2 == 0 else 2 + column = move["column"] + legal = [c for c in range(7) if board[c] == 0] + if (outcome != "playing" or move["actor"] != actor or type(column) is not int + or not 0 <= column < 7 or move["board_before"] != board): + raise ValueError("Connect Four move order or board is inconsistent") + if actor == "player_1" and column != choose(board, legal, instance["opponent_seed"]): + raise ValueError("Connect Four opponent did not follow its frozen policy") + + if column not in legal: + outcome = "illegal" + rewards = [-1, 0] + else: + won = winning_move(board, column, player) + row = next(r for r in range(5, -1, -1) if board[r * 7 + column] == 0) + board[row * 7 + column] = player + if won: + outcome = "win" if player == 1 else "loss" + elif all(board[:7]): + outcome = "draw" + rewards = ([1, -1] if outcome == "win" else + [-1, 1] if outcome == "loss" else [0, 0]) + if move["board_after"] != board or move["rewards"] != rewards: + raise ValueError("Connect Four board or native reward disagrees with replay") + + decisions = (len(moves) + 1) // 2 + if (type(metrics["agent_decisions"]) is not int or metrics["agent_decisions"] != decisions + or decisions != final["steps"] or metrics["total_plies"] != len(moves) + or metrics["final_board"] != board or metrics["outcome"] != outcome + or metrics["native_rewards"] != (rewards if moves else [0, 0])): + raise ValueError("Connect Four final metrics disagree with move replay") + success = outcome == "win" + if (metrics["success"] != int(success) or final["success"] != success + or final["terminated"] != (outcome != "playing") + or final["truncated"] != (outcome == "illegal") + or final["return"] != (rewards if moves else [0, 0])[0]): + raise ValueError("Connect Four terminal result disagrees with replay") diff --git a/game_first_exam/benchmarks/connectfour/opponent.py b/game_first_exam/benchmarks/connectfour/opponent.py new file mode 100644 index 0000000..8ddc954 --- /dev/null +++ b/game_first_exam/benchmarks/connectfour/opponent.py @@ -0,0 +1,45 @@ +"""A deterministic opponent that takes wins, blocks threats, then plays a seeded move.""" + +import hashlib +import json + + +ROWS, COLUMNS = 6, 7 + + +def winning_move(board, column, player): + """Check a proposed drop on the native, row-major PettingZoo board.""" + row = next((r for r in range(ROWS - 1, -1, -1) if board[r * COLUMNS + column] == 0), None) + if row is None: + return False + + def occupied(r, c): + return (r, c) == (row, column) or ( + 0 <= r < ROWS and 0 <= c < COLUMNS and board[r * COLUMNS + c] == player + ) + + for dr, dc in ((0, 1), (1, 0), (1, 1), (1, -1)): + count = 1 + for sign in (-1, 1): + r, c = row + sign * dr, column + sign * dc + while occupied(r, c): + count += 1 + r += sign * dr + c += sign * dc + if count >= 4: + return True + return False + + +def choose(board, legal, seed): + """Return a legal column; same board and seed always yield the same answer.""" + legal = sorted(int(column) for column in legal) + if not legal: + raise ValueError("Cannot choose from a full board") + for player in (2, 1): + for column in legal: + if winning_move(board, column, player): + return column + encoded = json.dumps([seed, board], separators=(",", ":")).encode() + index = int.from_bytes(hashlib.sha256(encoded).digest(), "big") % len(legal) + return legal[index] diff --git a/game_first_exam/benchmarks/connectfour/requirements.txt b/game_first_exam/benchmarks/connectfour/requirements.txt new file mode 100644 index 0000000..c325aba --- /dev/null +++ b/game_first_exam/benchmarks/connectfour/requirements.txt @@ -0,0 +1,10 @@ +pettingzoo==1.26.1 +gymnasium==1.3.0 +numpy==2.5.1 +pygame-ce==2.5.8 +imageio==2.37.4 +imageio-ffmpeg==0.6.0 +pillow==11.3.0 +cloudpickle==3.1.2 +farama-notifications==0.0.6 +typing-extensions==4.16.0 diff --git a/game_first_exam/images/connectfour-files/FILES.json b/game_first_exam/images/connectfour-files/FILES.json new file mode 100644 index 0000000..c60dadc --- /dev/null +++ b/game_first_exam/images/connectfour-files/FILES.json @@ -0,0 +1,11 @@ +{ + "image": "ghcr.io/mll-lab-nu/efe:connectfour-files-0.1.0@sha256:6c81b2a06c9246b4471a343f9657a4d48485fa02c827672cfbefd43cd473b850", + "source": "game_first_exam/benchmarks/connectfour", + "files": { + "adapter.py": "3d2beadbbe11f922b84b0f2c5252741a06d5bfaa9999b8bec18ca7d862bd8e18", + "instance_schema.py": "74efb24967206186c10e2396bda091b79a8a0a73ac040d6b0d20f14d67e62cdf", + "metric_rules.py": "6f21179d6f23f0b62220beec4248591098ac35b614080e209114fa538aa1e8af", + "opponent.py": "73b1e85a3297c40643e0ac4b59557351bfab2e23d163b1e3f0bfab8be8082f7d", + "requirements.txt": "73b46aec000241c5a2168a0309476eef7d01b721927c3dcc6ba8a405fa5d3fa0" + } +} diff --git a/game_first_exam/images/connectfour-files/README.md b/game_first_exam/images/connectfour-files/README.md new file mode 100644 index 0000000..aab482f --- /dev/null +++ b/game_first_exam/images/connectfour-files/README.md @@ -0,0 +1,3 @@ +# connectfour-files + +Files-only image. Build locally with `python scripts/files_image.py build connectfour-files`. This local integration does not publish the image. diff --git a/game_first_exam/images/connectfour-files/VERSION b/game_first_exam/images/connectfour-files/VERSION new file mode 100644 index 0000000..6e8bf73 --- /dev/null +++ b/game_first_exam/images/connectfour-files/VERSION @@ -0,0 +1 @@ +0.1.0 diff --git a/game_first_exam/tasks/connectfour/README.md b/game_first_exam/tasks/connectfour/README.md new file mode 100644 index 0000000..ecda316 --- /dev/null +++ b/game_first_exam/tasks/connectfour/README.md @@ -0,0 +1,19 @@ +# Connect Four + +A frozen PettingZoo Connect Four match against a deterministic defensive opponent. + +Red plays first. The native renderer draws the second player's pieces dark gray. +The opponent takes an immediate win, blocks an immediate Red win, then chooses a +deterministic legal column. This is one introductory fixed match, not an established +difficulty ladder. The agent sees the live board and may choose up to 21 columns. + +Two scored native previews of the same frozen opening: + +- [Red wins, score 1](../../../docs/demos/connectfour/red-win.mp4) +- [Red loses, score 0](../../../docs/demos/connectfour/red-loss.mp4) + +The previews use reference and control routes, not a model's policy. Generate them +with `python game_first_exam/tests/benchmarks/connectfour/record_demos.py`. + +On a host with Docker Desktop and Harbor, run both full container trials with +`bash game_first_exam/tests/benchmarks/connectfour/verify_harbor.command`. diff --git a/game_first_exam/tasks/connectfour/connectfour-match-i01-standard/DIGEST b/game_first_exam/tasks/connectfour/connectfour-match-i01-standard/DIGEST new file mode 100644 index 0000000..bd146c1 --- /dev/null +++ b/game_first_exam/tasks/connectfour/connectfour-match-i01-standard/DIGEST @@ -0,0 +1 @@ +sha256:0c58e2848a57573e86def6f79e589f901544281a8811e81f11d02ad582977a76 diff --git a/game_first_exam/tasks/connectfour/connectfour-match-i01-standard/README.md b/game_first_exam/tasks/connectfour/connectfour-match-i01-standard/README.md new file mode 100644 index 0000000..d9b28ad --- /dev/null +++ b/game_first_exam/tasks/connectfour/connectfour-match-i01-standard/README.md @@ -0,0 +1,35 @@ +# connectfour-match-i01-standard + +| | | +|---|---| +| Benchmark | Connect Four | +| Mode | standard (`game-standard/2.2`) | +| Twin | — (none: Connect Four has no privileged mode, PROTOCOL §2) | +| Simulator / robot | `connectfour` / `game-agent` | +| Family / instance | `fixed-opponent` / seed 42 | +| Oracle | `full` | +| Agent time budget | 600 s; tokens: protocol default (docs/protocol/running.md "Official runs") | +| Base image | `docker.io/library/python:3.12.10-slim-bookworm@sha256:fd95fa221297a88e1cf49c55ec1828edd7c5a428187e67b5d1805692d11588db` | + +## Task +Play Red from an empty native 7×6 PettingZoo board. Each move is one column; the fixed Yellow opponent replies if the match is still live. Win before the 21-decision budget runs out. + +## Difficulty +The opponent takes an immediate winning move and blocks a one-move threat; otherwise it picks a deterministic legal column. This is one frozen introductory match, not a calibrated difficulty scale. + +## Reference solution +The 12-decision reference wins in 23 total plies. A separate 12-decision control loses in 24 plies. Neither policy needs internal simulator access. + +## Verification +The isolated verifier reconstructs every placement from the trusted native move log and checks both the opponent policy and native outcome. A Red win is success (1); a draw, loss, illegal move, or exhausted decision budget is 0. + +## Resources +Caps per container (PROTOCOL §6). + +| Container | CPUs | Memory | Processes | GPU memory | Disk | +|---|---|---|---|---|---| +| `main` (the agent's) | 1 | 1 GiB | 256 | no GPU | 2 GiB | +| `sim` | 1 | 1 GiB | 128 | no GPU | — | +| verifier (as `main`) | 1 | 1 GiB | no cap | no GPU | 2 GiB | + +- GPU: not needed. diff --git a/game_first_exam/tasks/connectfour/connectfour-match-i01-standard/environment/Dockerfile b/game_first_exam/tasks/connectfour/connectfour-match-i01-standard/environment/Dockerfile new file mode 100644 index 0000000..10dcc84 --- /dev/null +++ b/game_first_exam/tasks/connectfour/connectfour-match-i01-standard/environment/Dockerfile @@ -0,0 +1,9 @@ +FROM docker.io/library/python:3.12.10-slim-bookworm@sha256:fd95fa221297a88e1cf49c55ec1828edd7c5a428187e67b5d1805692d11588db +RUN apt-get update && apt-get install -y --no-install-recommends bash curl git nodejs npm ca-certificates \ + && rm -rf /var/lib/apt/lists/* +RUN npm install -g @openai/codex@0.167.1 && npm cache clean --force +COPY --from=ghcr.io/mll-lab-nu/efe:game-files-0.6.0@sha256:bfb708928954d5cc194a614ab772a65b1e56f381b49dfeb2227c3d609e5f2ecc /game_client.py /app/game_client.py +COPY --from=ghcr.io/mll-lab-nu/efe:connection-files-0.1.0@sha256:6d1002dea6ca507b4148d3196e233838e645b33bcfa9a27ae4a43027ae519999 /service_connection.py /app/service_connection.py +ENV PYTHONUNBUFFERED=1 PYTHONPATH=/app +RUN mkdir -p /app/output +WORKDIR /app diff --git a/game_first_exam/tasks/connectfour/connectfour-match-i01-standard/environment/docker-compose.yaml b/game_first_exam/tasks/connectfour/connectfour-match-i01-standard/environment/docker-compose.yaml new file mode 100644 index 0000000..7fa17b4 --- /dev/null +++ b/game_first_exam/tasks/connectfour/connectfour-match-i01-standard/environment/docker-compose.yaml @@ -0,0 +1,43 @@ +services: + main: + pids_limit: 256 # rcb-monitor + volumes: # rcb-monitor + - rcb_limits:/run/rcb-limits:ro # rcb-monitor + depends_on: [sim] + sim: + cpus: 1 # rcb-monitor + mem_limit: 1024m # rcb-monitor + pids_limit: 128 # rcb-monitor + volumes: # rcb-monitor + - rcb_observe:/run/rcb-observe:ro # rcb-monitor + build: + context: sim + dockerfile: Dockerfile + working_dir: /srv + command: python3 /srv/server.py + environment: + RCB_WALL_CLOCK_S: "600" + # >>> rcb_monitor (resource monitor, PROTOCOL §6; generated by images/monitor/rcb_monitor/inject.py) + rcb_monitor: + image: ghcr.io/mll-lab-nu/efe:monitor-0.5.0@sha256:ecc5f24f1516ca11711d7c2d3ac07c89f79cd9220812c1244498ec71e352402a + pid: host + cgroup: host + network_mode: none + cap_add: [SYS_PTRACE] + cpus: 0.5 + mem_limit: 256m + pids_limit: 64 + restart: on-failure + working_dir: /var/rcb-monitor + volumes: + - ./rcb_monitor/limits.json:/opt/rcb_monitor/limits.json:ro + - rcb_limits:/run/rcb-limits + - rcb_observe:/run/rcb-observe + environment: + RCB_LIMITS_ENFORCE: ${RCB_LIMITS_ENFORCE:-0} + RCB_LIMITS_TOLERANCE: ${RCB_LIMITS_TOLERANCE:-0.05} + command: ["python3", "/opt/rcb_monitor/monitor.py", "run"] + # <<< rcb_monitor +volumes: # rcb-monitor + rcb_limits: # rcb-monitor + rcb_observe: # rcb-monitor diff --git a/game_first_exam/tasks/connectfour/connectfour-match-i01-standard/environment/rcb_monitor/limits.json b/game_first_exam/tasks/connectfour/connectfour-match-i01-standard/environment/rcb_monitor/limits.json new file mode 100644 index 0000000..eaea4d1 --- /dev/null +++ b/game_first_exam/tasks/connectfour/connectfour-match-i01-standard/environment/rcb_monitor/limits.json @@ -0,0 +1,26 @@ +{ + "agent_timeout_sec": 600, + "caps": { + "main": { + "cpus": 1.0, + "disk_gb": 2.0, + "memory_gb": 1.0, + "pids": 256 + }, + "sim": { + "cpus": 1.0, + "memory_gb": 1.0, + "pids": 128 + } + }, + "disk_gb": 2.0, + "disk_tick_sec": 60, + "format": "rcb-limits/2", + "gpu": false, + "mode": "standard", + "scope_services": [ + "main" + ], + "task": "connectfour-match-i01-standard", + "tick_sec": 5 +} diff --git a/game_first_exam/tasks/connectfour/connectfour-match-i01-standard/environment/sim/Dockerfile b/game_first_exam/tasks/connectfour/connectfour-match-i01-standard/environment/sim/Dockerfile new file mode 100644 index 0000000..70e15b8 --- /dev/null +++ b/game_first_exam/tasks/connectfour/connectfour-match-i01-standard/environment/sim/Dockerfile @@ -0,0 +1,16 @@ +FROM docker.io/library/python:3.12.10-slim-bookworm@sha256:fd95fa221297a88e1cf49c55ec1828edd7c5a428187e67b5d1805692d11588db +ENV PYTHONUNBUFFERED=1 PYGAME_HIDE_SUPPORT_PROMPT=1 SDL_VIDEODRIVER=dummy SDL_AUDIODRIVER=dummy +COPY --from=ghcr.io/mll-lab-nu/efe:connectfour-files-0.1.0@sha256:6c81b2a06c9246b4471a343f9657a4d48485fa02c827672cfbefd43cd473b850 /requirements.txt /srv/requirements.txt +RUN pip install --no-cache-dir -r /srv/requirements.txt +COPY --from=ghcr.io/mll-lab-nu/efe:game-files-0.6.0@sha256:bfb708928954d5cc194a614ab772a65b1e56f381b49dfeb2227c3d609e5f2ecc /server.py /srv/server.py +COPY --from=ghcr.io/mll-lab-nu/efe:game-files-0.6.0@sha256:bfb708928954d5cc194a614ab772a65b1e56f381b49dfeb2227c3d609e5f2ecc /reducers.py /srv/reducers.py +COPY --from=ghcr.io/mll-lab-nu/efe:game-files-0.6.0@sha256:bfb708928954d5cc194a614ab772a65b1e56f381b49dfeb2227c3d609e5f2ecc /config_schema.py /srv/config_schema.py +COPY --from=ghcr.io/mll-lab-nu/efe:game-files-0.6.0@sha256:bfb708928954d5cc194a614ab772a65b1e56f381b49dfeb2227c3d609e5f2ecc /contracts.py /srv/contracts.py +COPY --from=ghcr.io/mll-lab-nu/efe:game-files-0.6.0@sha256:bfb708928954d5cc194a614ab772a65b1e56f381b49dfeb2227c3d609e5f2ecc /encoding.py /srv/encoding.py +COPY --from=ghcr.io/mll-lab-nu/efe:game-files-0.6.0@sha256:bfb708928954d5cc194a614ab772a65b1e56f381b49dfeb2227c3d609e5f2ecc /recording.py /srv/recording.py +COPY --from=ghcr.io/mll-lab-nu/efe:connectfour-files-0.1.0@sha256:6c81b2a06c9246b4471a343f9657a4d48485fa02c827672cfbefd43cd473b850 /adapter.py /srv/adapter.py +COPY --from=ghcr.io/mll-lab-nu/efe:connectfour-files-0.1.0@sha256:6c81b2a06c9246b4471a343f9657a4d48485fa02c827672cfbefd43cd473b850 /instance_schema.py /srv/instance_schema.py +COPY --from=ghcr.io/mll-lab-nu/efe:connectfour-files-0.1.0@sha256:6c81b2a06c9246b4471a343f9657a4d48485fa02c827672cfbefd43cd473b850 /opponent.py /srv/opponent.py +COPY instance.json /srv/instance.json +WORKDIR /srv +CMD ["python3", "/srv/server.py"] diff --git a/game_first_exam/tasks/connectfour/connectfour-match-i01-standard/environment/sim/instance.json b/game_first_exam/tasks/connectfour/connectfour-match-i01-standard/environment/sim/instance.json new file mode 100644 index 0000000..70ef0ea --- /dev/null +++ b/game_first_exam/tasks/connectfour/connectfour-match-i01-standard/environment/sim/instance.json @@ -0,0 +1,28 @@ +{ + "schema_version": "game-instance/2.2", + "protocol": "game-standard/2.2", + "adapter_version": "1.0.0", + "capabilities": { + "images": true, + "action_mode": "enum", + "timing": "action-stepped", + "native_truncation": true + }, + "benchmark": "connectfour", + "env_id": "connect_four_v3", + "family": "fixed-opponent", + "seed": 42, + "max_steps": 21, + "observation_profile": "native-rgb-board-v1", + "metric_spec": { + "primary": "success", + "reducer": "family_macro", + "reducer_version": "1.0.0", + "success_label": "native_red_win" + }, + "initial_state_sha256": "4ec0ec6910bf45819c9a0eb90537d736d278ed8529bffc20c9d0d1136b02f128", + "engine_version": "1.26.1", + "controlled_agent": "player_0", + "opponent_policy": "block-win-hash-v1", + "opponent_seed": 2117382936 +} diff --git a/game_first_exam/tasks/connectfour/connectfour-match-i01-standard/instruction.md b/game_first_exam/tasks/connectfour/connectfour-match-i01-standard/instruction.md new file mode 100644 index 0000000..ac55116 --- /dev/null +++ b/game_first_exam/tasks/connectfour/connectfour-match-i01-standard/instruction.md @@ -0,0 +1,30 @@ +# Connect Four · Red versus Yellow + +Play a full game of Connect Four as Red. Drop your tokens into the 7-column board; connect four horizontally, vertically, or diagonally before the fixed Yellow opponent does. The native screenshot draws Yellow's pieces dark gray. The opponent wins immediately when it can, blocks an immediate Red win when it can, and otherwise makes a deterministic legal move. + +You may make up to 21 Red decisions. A native Red win scores 1; a loss, draw, illegal column, or unfinished match scores 0. A full column is an illegal move and ends the game. You cannot reset the game. + +Use the live service through `/app/game_client.py`: + +```python +from game_client import GameClient + +game = GameClient() +state = game.observe() +print(state["observation"]["board"]) +print(state["observation"]["legal_columns"]) +# state = game.step("3", expected_step=state["step"]) +``` + +Actions are the column numbers `"0"` through `"6"` as strings. Each accepted step plays one Red move and, if no one has won, one Yellow move. The observation includes an RGB screenshot (`image_png_base64`), a 6×7 board (0 empty, 1 Red, 2 Yellow), legal columns, recent moves and the outcome. The response also has `step`, `done`, `steps_remaining` and `time_left_s`. Check `done` before moving, and use the current `expected_step` with each action. On a lost response, call `observe()` before submitting another move. Your files do not determine the score. + +## External material +The network is open. You may install packages (pip, apt), and you may search for, download and use public tools and pretrained controllers. Do not look up a ready-made solution to this exact task. Say in your notes what you used. + +## Resources +Your container: **1 CPUs**, **1 GiB of memory**, **256 processes and threads** and **2 GiB** of disk (new files under `/app`, `/tmp` and `/root`). Your container has no GPU. The simulator runs in its own container and does not count against these. CPU only slows you down; a process that goes over any other cap can be killed. Usage and caps: `/run/rcb-limits/usage.json`. + +## Time limit +You have 600 seconds to complete this task. Do not cheat by using online solutions or hints specific to this task. + +This is wall-clock time from the start of your session; the time you wait for the simulator service counts. When it is up you are stopped without warning and the episode is graded as it stands at that moment. The service's `time_left_s` counts the same limit from your first request to the service, so it never runs out before your time does: your real time left is `time_left_s` minus the time you spent before that request. Plan by it. Your session started when you received this task. `/run/rcb-limits/usage.json`, rewritten every few seconds, gives the time left on this limit (`time_left_s`) and its end (`deadline_utc`), counted from a little before your session started, so it never gives you more time than you have: read it (or run `date`) before you decide that time is short, never guess. Waiting counts too: a tool call that sends input to a process that keeps running (an interactive interpreter, a simulator loop, a server) can wait for the whole wait or yield time you give it even when the answer is printed at once, so give such calls a short wait and poll again if the output is not complete, or run one-shot scripts that exit when they are done. Installing packages is not cheating (`## External material` above). diff --git a/game_first_exam/tasks/connectfour/connectfour-match-i01-standard/solution/route.json b/game_first_exam/tasks/connectfour/connectfour-match-i01-standard/solution/route.json new file mode 100644 index 0000000..f7665bd --- /dev/null +++ b/game_first_exam/tasks/connectfour/connectfour-match-i01-standard/solution/route.json @@ -0,0 +1 @@ +[1, 5, 5, 0, 2, 4, 5, 3, 0, 6, 3, 2] diff --git a/game_first_exam/tasks/connectfour/connectfour-match-i01-standard/solution/solve.py b/game_first_exam/tasks/connectfour/connectfour-match-i01-standard/solution/solve.py new file mode 100644 index 0000000..2ef48da --- /dev/null +++ b/game_first_exam/tasks/connectfour/connectfour-match-i01-standard/solution/solve.py @@ -0,0 +1,18 @@ +"""Replay a verified public Red route through the normal game client.""" + +import json +from pathlib import Path + +from game_client import GameClient + + +game = GameClient() +state = game.observe() +for column in json.loads(Path("/solution/route.json").read_text()): + if state["done"]: + break + if column not in state["observation"]["legal_columns"]: + raise RuntimeError(f"Reference column {column} is full") + state = game.step(str(column), expected_step=state["step"]) + +print("Native match:", state["observation"]["outcome"], "after", state["step"], "decisions") diff --git a/game_first_exam/tasks/connectfour/connectfour-match-i01-standard/solution/solve.sh b/game_first_exam/tasks/connectfour/connectfour-match-i01-standard/solution/solve.sh new file mode 100755 index 0000000..a856bf7 --- /dev/null +++ b/game_first_exam/tasks/connectfour/connectfour-match-i01-standard/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -euo pipefail +exec python3 /solution/solve.py diff --git a/game_first_exam/tasks/connectfour/connectfour-match-i01-standard/task.toml b/game_first_exam/tasks/connectfour/connectfour-match-i01-standard/task.toml new file mode 100644 index 0000000..a4098b6 --- /dev/null +++ b/game_first_exam/tasks/connectfour/connectfour-match-i01-standard/task.toml @@ -0,0 +1,58 @@ +schema_version = "1.3" +artifacts = [{ source = "/var/rcb-monitor/", service = "rcb_monitor" }, { source = "/data/final.json", service = "sim" }, + { source = "/data/episode.jsonl", service = "sim" }, + { source = "/data/recording.json", service = "sim" }, + { source = "/data/replay.mp4", service = "sim" }, + { source = "/data/replay.last.png", service = "sim" }, + "/app/output/", +] + +[task] +name = "embodied-first-exam/connectfour-match-i01-standard" +description = "Win a PettingZoo Connect Four match as Red against a frozen defensive opponent." +keywords = ["game", "connectfour", "board", "strategy", "standard-mode"] + +[metadata] +task_type = "trajectory" +simulator = "connectfour" +robot = "game-agent" +family = "fixed-opponent" +dynamics = "static" +protocol = "game-standard/2.2" +oracle = "full" +instance_seed = 42 +expert_time_estimate_hours = 0.5 + +[verifier] +timeout_sec = 120.0 +environment_mode = "separate" +network_mode = "no-network" + +# Resources (PROTOCOL §6): seal the monitor's record first. +[[verifier.collect]] +service = "rcb_monitor" +command = "python3 /opt/rcb_monitor/monitor.py seal --wait 90" +timeout_sec = 120 + +[[verifier.collect]] +service = "main" +command = "kill -9 -1 2>/dev/null; exit 0" +timeout_sec = 30 + +[[verifier.collect]] +service = "sim" +command = "kill -USR1 $(cat /data/server.pid); i=0; while [ ! -f /data/collection.ready ] && [ $i -lt 30 ]; do sleep 1; i=$((i+1)); done; test -f /data/collection.ready && test -f /data/final.json" +timeout_sec = 40 + +[agent] +timeout_sec = 600.0 +network_mode = "public" + +[environment] +build_timeout_sec = 1200.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 + +[verifier.env] +RCB_LIMITS_ENFORCE = "${RCB_LIMITS_ENFORCE:-0}" diff --git a/game_first_exam/tasks/connectfour/connectfour-match-i01-standard/tests/Dockerfile b/game_first_exam/tasks/connectfour/connectfour-match-i01-standard/tests/Dockerfile new file mode 100644 index 0000000..ac7a38a --- /dev/null +++ b/game_first_exam/tasks/connectfour/connectfour-match-i01-standard/tests/Dockerfile @@ -0,0 +1,12 @@ +FROM docker.io/library/python:3.12.10-slim-bookworm@sha256:fd95fa221297a88e1cf49c55ec1828edd7c5a428187e67b5d1805692d11588db +COPY test.sh instance.json /tests/ +COPY --from=ghcr.io/mll-lab-nu/efe:game-files-0.6.0@sha256:bfb708928954d5cc194a614ab772a65b1e56f381b49dfeb2227c3d609e5f2ecc /grade.py /tests/grade.py +COPY --from=ghcr.io/mll-lab-nu/efe:game-files-0.6.0@sha256:bfb708928954d5cc194a614ab772a65b1e56f381b49dfeb2227c3d609e5f2ecc /reducers.py /tests/reducers.py +COPY --from=ghcr.io/mll-lab-nu/efe:game-files-0.6.0@sha256:bfb708928954d5cc194a614ab772a65b1e56f381b49dfeb2227c3d609e5f2ecc /config_schema.py /tests/config_schema.py +COPY --from=ghcr.io/mll-lab-nu/efe:connectfour-files-0.1.0@sha256:6c81b2a06c9246b4471a343f9657a4d48485fa02c827672cfbefd43cd473b850 /instance_schema.py /tests/instance_schema.py +COPY --from=ghcr.io/mll-lab-nu/efe:connectfour-files-0.1.0@sha256:6c81b2a06c9246b4471a343f9657a4d48485fa02c827672cfbefd43cd473b850 /metric_rules.py /tests/metric_rules.py +COPY --from=ghcr.io/mll-lab-nu/efe:connectfour-files-0.1.0@sha256:6c81b2a06c9246b4471a343f9657a4d48485fa02c827672cfbefd43cd473b850 /opponent.py /tests/opponent.py +RUN chmod +x /tests/test.sh +# resources (PROTOCOL §6) # rcb-monitor +COPY --from=ghcr.io/mll-lab-nu/efe:monitor-0.5.0@sha256:ecc5f24f1516ca11711d7c2d3ac07c89f79cd9220812c1244498ec71e352402a /opt/rcb_monitor/rcb_limits.py /tests/rcb_limits.py +COPY rcb_limits.json /tests/rcb_limits.json diff --git a/game_first_exam/tasks/connectfour/connectfour-match-i01-standard/tests/instance.json b/game_first_exam/tasks/connectfour/connectfour-match-i01-standard/tests/instance.json new file mode 100644 index 0000000..70ef0ea --- /dev/null +++ b/game_first_exam/tasks/connectfour/connectfour-match-i01-standard/tests/instance.json @@ -0,0 +1,28 @@ +{ + "schema_version": "game-instance/2.2", + "protocol": "game-standard/2.2", + "adapter_version": "1.0.0", + "capabilities": { + "images": true, + "action_mode": "enum", + "timing": "action-stepped", + "native_truncation": true + }, + "benchmark": "connectfour", + "env_id": "connect_four_v3", + "family": "fixed-opponent", + "seed": 42, + "max_steps": 21, + "observation_profile": "native-rgb-board-v1", + "metric_spec": { + "primary": "success", + "reducer": "family_macro", + "reducer_version": "1.0.0", + "success_label": "native_red_win" + }, + "initial_state_sha256": "4ec0ec6910bf45819c9a0eb90537d736d278ed8529bffc20c9d0d1136b02f128", + "engine_version": "1.26.1", + "controlled_agent": "player_0", + "opponent_policy": "block-win-hash-v1", + "opponent_seed": 2117382936 +} diff --git a/game_first_exam/tasks/connectfour/connectfour-match-i01-standard/tests/rcb_limits.json b/game_first_exam/tasks/connectfour/connectfour-match-i01-standard/tests/rcb_limits.json new file mode 100644 index 0000000..eaea4d1 --- /dev/null +++ b/game_first_exam/tasks/connectfour/connectfour-match-i01-standard/tests/rcb_limits.json @@ -0,0 +1,26 @@ +{ + "agent_timeout_sec": 600, + "caps": { + "main": { + "cpus": 1.0, + "disk_gb": 2.0, + "memory_gb": 1.0, + "pids": 256 + }, + "sim": { + "cpus": 1.0, + "memory_gb": 1.0, + "pids": 128 + } + }, + "disk_gb": 2.0, + "disk_tick_sec": 60, + "format": "rcb-limits/2", + "gpu": false, + "mode": "standard", + "scope_services": [ + "main" + ], + "task": "connectfour-match-i01-standard", + "tick_sec": 5 +} diff --git a/game_first_exam/tasks/connectfour/connectfour-match-i01-standard/tests/test.sh b/game_first_exam/tasks/connectfour/connectfour-match-i01-standard/tests/test.sh new file mode 100755 index 0000000..0cf878a --- /dev/null +++ b/game_first_exam/tasks/connectfour/connectfour-match-i01-standard/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +rm -rf /logs/verifier/* +trap 'p=$(command -v python3 || command -v python); "$p" /tests/rcb_limits.py verify' EXIT # resources, after the grader (PROTOCOL §6) +p=$(command -v python3 || command -v python); "$p" /tests/rcb_limits.py sanitize /app/output || true # untrusted agent files (PROTOCOL H.1) +mkdir -p /logs/verifier +python3 /tests/grade.py 2>/logs/verifier/grade.log diff --git a/game_first_exam/tests/benchmarks/connectfour/exported.toml b/game_first_exam/tests/benchmarks/connectfour/exported.toml new file mode 100644 index 0000000..7f1c97d --- /dev/null +++ b/game_first_exam/tests/benchmarks/connectfour/exported.toml @@ -0,0 +1,7 @@ +[protocols] +standard = ["game-standard/2.2"] + +[[tasks]] +name = "connectfour-match-i01-standard" +source_task = "PettingZoo-classic-connect_four_v3" +protocol = "game-standard/2.2" diff --git a/game_first_exam/tests/benchmarks/connectfour/loss/route.json b/game_first_exam/tests/benchmarks/connectfour/loss/route.json new file mode 100644 index 0000000..40012a9 --- /dev/null +++ b/game_first_exam/tests/benchmarks/connectfour/loss/route.json @@ -0,0 +1 @@ +[6, 3, 6, 3, 0, 2, 4, 3, 4, 2, 4, 2] diff --git a/game_first_exam/tests/benchmarks/connectfour/loss/run_harbor.py b/game_first_exam/tests/benchmarks/connectfour/loss/run_harbor.py new file mode 100644 index 0000000..a768c4e --- /dev/null +++ b/game_first_exam/tests/benchmarks/connectfour/loss/run_harbor.py @@ -0,0 +1,37 @@ +"""Run a losing policy against the same frozen native PettingZoo opponent.""" + +import json +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def main(): + root = Path.cwd() + if not (root / "scripts/prepare_games.py").is_file(): + raise SystemExit("Run from the Game Exam repository root") + staging = root / "jobs/prepared" + staging.mkdir(parents=True, exist_ok=True) + run = Path(tempfile.mkdtemp(prefix="connectfour-loss-", dir=staging)) + config = run / "control.json" + subprocess.run([sys.executable, "scripts/prepare_games.py", "--suite", "connectfour", + "--output", str(config)], check=True) + tasks = json.loads(config.read_text())["tasks"] + if len(tasks) != 1: + raise RuntimeError("Expected one Connect Four task") + task = Path(tasks[0]["path"]).resolve() + if not task.is_relative_to(run) or task.name != "connectfour-match-i01-standard": + raise RuntimeError("The prepared task is not a frozen Connect Four match") + shutil.copyfile(Path(__file__).with_name("route.json"), task / "solution/route.json") + sys.path.insert(0, str(root / "scripts")) + import task_conventions + task_conventions.normalize(task) + subprocess.run([sys.executable, "scripts/stamp_mtimes.py", "--full", str(task)], check=True) + subprocess.run(["harbor", "run", "-c", str(config), "-a", "oracle", + "--jobs-dir", str(root / "jobs"), "--job-name", "connectfour-loss", "-y"], check=True) + + +if __name__ == "__main__": + main() diff --git a/game_first_exam/tests/benchmarks/connectfour/record_demos.py b/game_first_exam/tests/benchmarks/connectfour/record_demos.py new file mode 100644 index 0000000..bd0ab28 --- /dev/null +++ b/game_first_exam/tests/benchmarks/connectfour/record_demos.py @@ -0,0 +1,83 @@ +"""Record readable win/loss previews from the frozen, scored native match.""" + +import json +import os +from pathlib import Path +import sys +import tempfile + +import imageio.v2 as imageio +import numpy as np +from PIL import Image, ImageDraw, ImageFont + + +ROOT = Path(__file__).resolve().parents[4] +sys.path[:0] = [str(ROOT / folder) for folder in ( + "scripts", "game_first_exam/runtime", "game_first_exam/benchmarks/connectfour" +)] + +from adapter import Adapter +from game_schemas import load_schema +from grade import grade +from metric_rules import validate_metrics +from server import Game + + +TASK = ROOT / "game_first_exam/tasks/connectfour/connectfour-match-i01-standard" +OUTPUT = ROOT / "docs/demos/connectfour" +INSTANCE = json.loads((TASK / "tests/instance.json").read_text()) + + +def card(frame, title, subtitle): + image = Image.new("RGB", (896, 864), (13, 18, 31)) + image.paste(Image.fromarray(frame), (2, 90)) + draw = ImageDraw.Draw(image) + font = ImageFont.load_default(size=27) + draw.text((16, 9), title, font=font, fill=(255, 255, 255)) + draw.text((16, 49), subtitle, font=ImageFont.load_default(size=21), fill=(180, 210, 250)) + return np.asarray(image) + + +def record(name, route_path, outcome, score): + route = json.loads(route_path.read_text()) + with tempfile.TemporaryDirectory() as tmp: + game = Game.open(Adapter, INSTANCE, None, tmp) + frames = [(game.adapter.frame().copy(), "Empty board")] + try: + if game.adapter.fingerprint() != INSTANCE["initial_state_sha256"]: + raise ValueError("Frozen native opening changed") + for index, column in enumerate(route, 1): + if game.final is not None: + break + game.submit({"action": str(column), "expected_step": game.steps, + "request_id": f"demo-{index}"}) + frames.append((game.adapter.frame().copy(), f"Red move {index}: column {column}")) + if game.final["metrics"]["outcome"] != outcome: + raise ValueError("Unexpected native outcome") + if grade(game.final, INSTANCE, validate_metrics)["primary_score"] != score: + raise ValueError("The isolated verifier disagrees") + if not (Path(tmp) / "replay.mp4").stat().st_size: + raise ValueError("The native recorder failed") + finally: + game.close() + + OUTPUT.mkdir(parents=True, exist_ok=True) + path = OUTPUT / name + with imageio.get_writer(path, fps=6, codec="libx264", macro_block_size=16) as writer: + for frame, label in frames: + picture = card(frame, "CONNECT FOUR | Red vs Yellow", label) + for _ in range(4): + writer.append_data(picture) + picture = card(frames[-1][0], "CONNECT FOUR | Red vs Yellow", + f"{outcome.upper()} | Red score: {score} | {len(route)} decisions") + for _ in range(18): + writer.append_data(picture) + print(f"{path.name}: native {outcome}, score {score}, {len(route)} decisions, {path.stat().st_size} bytes") + + +if __name__ == "__main__": + os.environ["SDL_VIDEODRIVER"] = "dummy" + os.environ["SDL_AUDIODRIVER"] = "dummy" + load_schema("connectfour") + record("red-win.mp4", TASK / "solution/route.json", "win", 1) + record("red-loss.mp4", Path(__file__).with_name("loss") / "route.json", "loss", 0) diff --git a/game_first_exam/tests/benchmarks/connectfour/verify_harbor.command b/game_first_exam/tests/benchmarks/connectfour/verify_harbor.command new file mode 100644 index 0000000..205971c --- /dev/null +++ b/game_first_exam/tests/benchmarks/connectfour/verify_harbor.command @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Run both reference outcomes on a host with Docker Desktop and Harbor installed. +set -euo pipefail +root="$(cd "$(dirname "$0")/../../../.." && pwd)" +cd "$root" + +# Reuse the adjacent development virtualenv when invoked from this checkout. +if [ -x ../Game_exam-main/.venv/bin/harbor ]; then + export PATH="$(cd ../Game_exam-main/.venv/bin && pwd):$PATH" +fi +export PATH="/Applications/Docker.app/Contents/Resources/bin:$HOME/.docker/bin:$PATH" +export DOCKER_HOST="unix://$HOME/.docker/run/docker.sock" + +docker info --format 'Docker server: {{.ServerVersion}}' +harbor run --game-suite connectfour --standard \ + -c configs/harbor/oracle.json --plugin game_harbor:GameRecords \ + --jobs-dir "$PWD/jobs" --job-name connectfour-win -y +python game_first_exam/tests/benchmarks/connectfour/loss/run_harbor.py +python ci_checks/check-connectfour-result.py jobs/connectfour-win jobs/connectfour-loss diff --git a/game_first_exam/tests/test_connectfour.py b/game_first_exam/tests/test_connectfour.py new file mode 100644 index 0000000..9dbdd1e --- /dev/null +++ b/game_first_exam/tests/test_connectfour.py @@ -0,0 +1,80 @@ +"""Native matches, deterministic opponent, and independent replay verification.""" + +import copy +import json +import os +from pathlib import Path +import sys +import tempfile +import unittest +from unittest.mock import patch + + +ROOT = Path(__file__).resolve().parents[2] +sys.path[:0] = [str(ROOT / folder) for folder in ( + "scripts", "game_first_exam/runtime", "game_first_exam/benchmarks/connectfour" +)] + +from adapter import Adapter +from game_schemas import load_schema +from grade import grade +from metric_rules import validate_metrics +from server import Game + + +TASK = ROOT / "game_first_exam/tasks/connectfour/connectfour-match-i01-standard" +INSTANCE = json.loads((TASK / "tests/instance.json").read_text()) +WIN = json.loads((TASK / "solution/route.json").read_text()) +LOSS = json.loads((ROOT / "game_first_exam/tests/benchmarks/connectfour/loss/route.json").read_text()) + + +class ConnectFourTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + load_schema("connectfour") + + def play(self, route, expected): + with tempfile.TemporaryDirectory() as output, patch.dict(os.environ, { + "SDL_VIDEODRIVER": "dummy", "SDL_AUDIODRIVER": "dummy" + }): + game = Game.open(Adapter, INSTANCE, None, output) + try: + self.assertIsNone(game.final) + opening = game.adapter.fingerprint() + self.assertEqual(opening, INSTANCE["initial_state_sha256"]) + observation = game.observe() + self.assertEqual(observation["observation"]["legal_columns"], list(range(7))) + self.assertEqual(game.adapter.fingerprint(), opening) + for column in route: + if game.final is not None: + break + observation = game.submit({"action": str(column), "expected_step": game.steps, + "request_id": str(game.steps)}) + self.assertEqual(game.final["metrics"]["outcome"], expected) + self.assertEqual(game.final["metrics"]["agent_decisions"], len(route)) + reward = grade(game.final, INSTANCE, validate_metrics) + self.assertEqual(reward["primary_score"], int(expected == "win")) + self.assertEqual(reward["environment_error"], 0) + self.assertTrue((Path(output) / "replay.mp4").stat().st_size > 0) + return game.final + finally: + game.close() + + def test_reference_wins_and_control_loses_on_identical_opening(self): + self.play(WIN, "win") + self.play(LOSS, "loss") + + def test_verifier_rejects_tampered_native_moves(self): + final = self.play(WIN, "win") + fake = copy.deepcopy(final) + fake["metrics"]["moves"][1]["column"] = 6 + with self.assertRaisesRegex(ValueError, "opponent"): + grade(fake, INSTANCE, validate_metrics) + fake = copy.deepcopy(final) + fake["metrics"]["outcome"] = "loss" + with self.assertRaisesRegex(ValueError, "final metrics"): + grade(fake, INSTANCE, validate_metrics) + + +if __name__ == "__main__": + unittest.main() diff --git a/game_first_exam/tests/test_game_harbor.py b/game_first_exam/tests/test_game_harbor.py index e6e71f6..c598769 100644 --- a/game_first_exam/tests/test_game_harbor.py +++ b/game_first_exam/tests/test_game_harbor.py @@ -32,13 +32,13 @@ class GameSelection(unittest.TestCase): def test_game_only_default_and_all_selection_never_launches(self): for flags, expected in ((["--list", "--standard"], 30), - (["--all", "--standard", "--list"], 42)): + (["--all", "--standard", "--list"], 43)): with self.subTest(flags=flags), contextlib.redirect_stdout(io.StringIO()) as output, \ patch("efe.harbor") as launch, patch("efe.prepull") as pull: self.assertEqual(efe.run(flags), 0) names = output.getvalue().splitlines() self.assertEqual(len(names), expected) - self.assertTrue(all(name.startswith(("minigrid-", "crafter-", "textworld-", "babaisai-", "minihack-")) + self.assertTrue(all(name.startswith(("minigrid-", "crafter-", "textworld-", "babaisai-", "minihack-", "connectfour-")) for name in names)) launch.assert_not_called() pull.assert_not_called() diff --git a/scripts/task_conventions.py b/scripts/task_conventions.py index 36b7e5c..09ae331 100644 --- a/scripts/task_conventions.py +++ b/scripts/task_conventions.py @@ -72,6 +72,7 @@ # benchmark's game_first_exam/benchmarks//; BENCHMARKS and BENCHMARK_DIRS below are views of this table, and # ci_checks/ci_scope.py --check holds its UNITS / FILES_IMAGE to it. A new benchmark adds one row here. BENCHMARK_TABLE = [ + ("connectfour-", "Connect Four", "connectfour"), ("minihack-", "MiniHack", "minihack"), ("babaisai-", "Baba Is AI", "babaisai"), ("crafter-", "Crafter", "crafter"), diff --git a/scripts/task_resources.toml b/scripts/task_resources.toml index f5e2106..df7506a 100644 --- a/scripts/task_resources.toml +++ b/scripts/task_resources.toml @@ -21,3 +21,9 @@ match = "^minihack-.*-standard$" main = { cpus = 1, memory_gb = 1, pids = 256, disk_gb = 2 } sim = { cpus = 1, memory_gb = 1, pids = 128 } measured = "Initial CPU-only integration caps; measure during validation" + +[[cap]] +match = "^connectfour-.*-standard$" +main = { cpus = 1, memory_gb = 1, pids = 256, disk_gb = 2 } +sim = { cpus = 1, memory_gb = 1, pids = 128 } +measured = "Initial Connect Four CPU-only integration caps"