diff --git a/.github/workflows/games.yml b/.github/workflows/games.yml index ebee4f6..97fa9b5 100644 --- a/.github/workflows/games.yml +++ b/.github/workflows/games.yml @@ -25,7 +25,7 @@ jobs: strategy: fail-fast: false matrix: - benchmark: [common, minigrid, crafter, textworld, babaisai, minihack] + benchmark: [common, minigrid, crafter, textworld, babaisai, minihack, chess] steps: - uses: actions/checkout@v4 with: {persist-credentials: false} diff --git a/README.md b/README.md index 5e00e1f..ad225e2 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 版本 | +| Chess | 1 | — | 标准开局,执白对固定黑方 | [PettingZoo Chess 工程验证](game_first_exam/tasks/chess/README.md) | 套件由 [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 | 所有套件去重后的任务;汇总时应选择一种模式 | +| `chess` | 1 | PettingZoo Chess Standard 工程验证 | +| `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 | @@ -246,6 +248,7 @@ harbor view jobs | MiniGrid / Baba Is AI | 原生目标是否成功 | reward、步数、原生终局 | | TextWorld | 原生 score / max_score | 原生得分、胜负、步数 | | MiniHack | 完成 100,未完成 0 | 原生 return、end status、动作数;100 是分数,不是 100 步 | +| Chess | 原生胜 100、和 50、负或未完成 0 | 原生结果、白方决策数、双方半回合数 | | Crafter | 单局成就比例;跨局另计算成就成功率的 Crafter score | 22 个成就、原生 return、存活状态;木镐是辅助目标 | 普通 reducer 按任务族汇总,Crafter 使用独立、带版本的成就 reducer。缺失局、重复局、环境故障和有效失败分开处理;模型未完成应计为有效失败,不能随意删掉。单局成就比例不是官方完整评测集的总分。 @@ -326,12 +329,12 @@ docker build -f game_first_exam/tests/envs/common.Dockerfile -t game-tests:commo docker run --rm -v "$PWD:/repo:ro" game-tests:common \ bash game_first_exam/tests/run.sh common -# 将 common 换成 minigrid / crafter / textworld / babaisai / minihack +# 将 common 换成 minigrid / crafter / textworld / babaisai / minihack / chess # Harbor 选择、配置合并、锁定和报告测试: python game_first_exam/tests/test_game_harbor.py ``` -GitHub Actions 执行静态检查、公共测试、5 个原生 adapter 环境及 Harbor 集成测试;不调用真实模型,不部署网站,不发布 PyPI 包或镜像。 +GitHub Actions 执行静态检查、公共测试、6 个原生 adapter 环境及 Harbor 集成测试;不调用真实模型,不部署网站,不发布 PyPI 包或镜像。 - **`harbor` 不识别 `--game-suite`:**确认当前环境执行过 `pip install -e .`,并检查 `which harbor`。也可用 `game-exam run ...`;单独安装 Harbor 不包含本仓库选择逻辑。 - **选不到任务:**先 `--list`;只有 Room 有 MiniHack privileged,只有 Crafter i01 有 realtime。模式不匹配会拒绝启动。 diff --git a/configs/game_benchmarks.toml b/configs/game_benchmarks.toml index 8f77b59..f67f030 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.chess] +schema = "game_first_exam/benchmarks/chess/instance_schema.py" diff --git a/configs/game_suites/chess.toml b/configs/game_suites/chess.toml new file mode 100644 index 0000000..7422376 --- /dev/null +++ b/configs/game_suites/chess.toml @@ -0,0 +1,10 @@ +schema_version = "game-suite/2.1" +version = "0.1.2" +tier = "smoke" +name = "games-chess-native-smoke-v0.1.2" +files_images = ["connection-files", "game-files", "chess-files"] + +[[tasks]] +name = "chess-match-i01-standard" +benchmark = "chess" +family = "standard-start" diff --git a/game_first_exam/benchmarks/chess/SOURCE.json b/game_first_exam/benchmarks/chess/SOURCE.json new file mode 100644 index 0000000..e4682ec --- /dev/null +++ b/game_first_exam/benchmarks/chess/SOURCE.json @@ -0,0 +1,9 @@ +{ + "repository": "https://github.com/Farama-Foundation/PettingZoo", + "commit": "7221e4b15873a8b16555fda038a77a6ae595e88d", + "environment": "classic/chess-v6", + "pettingzoo_wheel_sha256": "075a6ab7c32d32d9a674f1af395010198bf09c172341aa38fa5415461601ac61", + "chess_sdist_sha256": "a8b43e5678fdb3000695bdaa573117ad683761e5ca38e591c4826eba6d25bb39", + "chess_py_sha256": "2b5c6f684951bb1b476213db88fcbebf63ed7acf0c565e288454f3174752726a", + "chess_utils_py_sha256": "e9a7418ab85bbbb2f5ed5cd766b5afcc7ff07a6ca110842f48465f4ec9717cc1" +} diff --git a/game_first_exam/benchmarks/chess/adapter.py b/game_first_exam/benchmarks/chess/adapter.py new file mode 100644 index 0000000..0e78294 --- /dev/null +++ b/game_first_exam/benchmarks/chess/adapter.py @@ -0,0 +1,152 @@ +"""One white client decision and at most one black AEC response.""" +import copy +import hashlib +from importlib.metadata import version +import json +import os +from pathlib import Path + +import numpy as np +from pettingzoo import make +from pettingzoo.classic.chess import chess_utils + +from contracts import Capabilities, Transition +from encoding import state_hash +from metric_rules import ACTION_COUNT, BLACK, POINTS, WHITE +from opponent import choose + + +class Adapter: + def __init__(self, instance, assets=None): + for package, expected in instance['engine_versions'].items(): + if version(package) != expected: + raise ValueError(f'Chess dependency version mismatch: {package}') + self.instance = instance + self.env = make('aec', instance['env_id'], render_mode='rgb_array', screen_height=384) + try: + self.env.reset(seed=instance['seed']) + self.board = self.env.unwrapped.board + self.history = [] + self.decisions = 0 + self.outcome = 'unfinished' + self.result = '*' + self.draw_reason = None + self.rewards = [0, 0] + self.terminated = self.truncated = False + self.trace_digest = hashlib.sha256() + trace = os.environ.get('CHESS_TRACE_PATH') + self.trace_path = Path(trace) if trace else None + if self.trace_path is not None: + self.trace_path.parent.mkdir(parents=True, exist_ok=True) + with self.trace_path.open('xb'): + pass + self.refresh_observation([]) + except Exception: + self.env.close() + raise + + def spec(self): + return { + 'adapter_version': '1.0.0', + 'capabilities': Capabilities(False, 'enum', native_truncation=True).to_dict(), + 'action_schema': {'type': 'string', 'enum': [str(i) for i in range(ACTION_COUNT)], + 'max_length': 4}, + 'goal': 'Win the native game as white.', + } + + def legal_map(self, actor, mask): + return {str(index): chess_utils.action_to_move(self.board, int(index), int(actor == BLACK)).uci() + for index in np.flatnonzero(mask)} + + def refresh_observation(self, moves): + native = self.env.observe(WHITE) + self.white_legal = {} if self.terminated or self.truncated else self.legal_map(WHITE, native['action_mask']) + self.public = { + 'native_observation': native['observation'].tolist(), + 'action_mask': native['action_mask'].tolist(), + 'controlled_agent': WHITE, + 'side_to_move': 'white' if self.board.turn else 'black', + 'board_fen': self.board.fen(), + 'board_ascii': str(self.board), + 'legal_moves': self.white_legal, + 'last_round_moves': moves, + 'move_history_uci': list(self.history), + 'outcome': self.outcome, + } + + def observe(self): + return copy.deepcopy(self.public) + + def native_step(self, actor, action, legal): + if self.env.agent_selection != actor: + raise RuntimeError('unexpected native Chess actor') + before = self.board.fen() + uci = legal.get(action) + self.env.step(int(action)) + self.rewards = [self.env.rewards[player] for player in (WHITE, BLACK)] + self.terminated = all(self.env.terminations.values()) + self.truncated = all(self.env.truncations.values()) + if uci is not None: + self.history.append(uci) + if self.terminated: + if uci is None: + self.outcome = 'illegal_action' + else: + outcome = self.board.outcome(claim_draw=True) + self.result = outcome.result() + self.outcome = {'1-0': 'win', '0-1': 'loss', '1/2-1/2': 'draw'}[self.result] + if self.outcome == 'draw': + self.draw_reason = outcome.termination.name.lower() + row = {'actor': actor, 'action_id': action, 'uci': uci, 'decision': self.decisions, + 'ply': self.board.ply(), 'fen_before': before, 'fen_after': self.board.fen(), + 'rewards': self.rewards, 'terminated': self.terminated, 'truncated': self.truncated, + 'legal_moves': legal} + data = (json.dumps(row, sort_keys=True, separators=(',', ':')) + '\n').encode() + if self.trace_path is not None: + with self.trace_path.open('ab') as stream: + stream.write(data) + self.trace_digest.update(data) + return {'actor': actor, 'action_id': action, 'uci': uci} + + def step(self, action): + if self.terminated or self.truncated: + raise ValueError('episode closed') + self.decisions += 1 + moves = [self.native_step(WHITE, action, self.white_legal)] + reward = self.rewards[0] + if not (self.terminated or self.truncated): + legal = self.legal_map(BLACK, self.env.observe(BLACK)['action_mask']) + response = choose(legal, self.instance['opponent_seed'], self.history) + if response not in legal: + raise RuntimeError('fixed opponent returned an illegal Chess action') + moves.append(self.native_step(BLACK, response, legal)) + reward += self.rewards[0] + self.refresh_observation(moves) + return Transition(float(reward), self.terminated, self.truncated) + + def success(self): + return self.outcome == 'win' + + def metrics(self): + plies = len(self.history) + return {'outcome': self.outcome, 'match_points': POINTS[self.outcome], + 'success': int(self.success()), 'native_result': self.result, + 'native_return': self.rewards[0], 'native_rewards': self.rewards.copy(), + 'draw_reason': self.draw_reason, 'agent_decisions': self.decisions, + 'agent_legal_plies': (plies + 1) // 2, 'opponent_plies': plies // 2, + 'total_board_plies': plies, 'setup_plies': 0, + 'native_illegal_actions': int(self.outcome == 'illegal_action'), + 'final_fen': self.board.fen(), 'trace_sha256': self.trace_digest.hexdigest()} + + def fingerprint(self): + return state_hash({'metrics': self.metrics(), 'actor': self.env.agent_selection, + 'flags': [self.env.terminations, self.env.truncations], + 'board_history': self.env.unwrapped.board_history, + 'seed': self.instance['seed'], 'opponent_seed': self.instance['opponent_seed'], + 'opponent_policy': self.instance['opponent_policy']}) + + def frame(self): + return self.env.render() + + def close(self): + self.env.close() diff --git a/game_first_exam/benchmarks/chess/build-requirements.txt b/game_first_exam/benchmarks/chess/build-requirements.txt new file mode 100644 index 0000000..6f8bf56 --- /dev/null +++ b/game_first_exam/benchmarks/chess/build-requirements.txt @@ -0,0 +1,2 @@ +setuptools==80.9.0 --hash=sha256:062d34222ad13e0cc312a4c02d73f059e86a4acbfbdea8f8f76b28c99f306922 +wheel==0.45.1 --hash=sha256:708e7481cc80179af0e556bbf0cc00b8444c7321e2700b8d8580231d13017248 diff --git a/game_first_exam/benchmarks/chess/chess-requirements.txt b/game_first_exam/benchmarks/chess/chess-requirements.txt new file mode 100644 index 0000000..e5df904 --- /dev/null +++ b/game_first_exam/benchmarks/chess/chess-requirements.txt @@ -0,0 +1 @@ +chess==1.11.2 --hash=sha256:a8b43e5678fdb3000695bdaa573117ad683761e5ca38e591c4826eba6d25bb39 diff --git a/game_first_exam/benchmarks/chess/instance_schema.py b/game_first_exam/benchmarks/chess/instance_schema.py new file mode 100644 index 0000000..570827e --- /dev/null +++ b/game_first_exam/benchmarks/chess/instance_schema.py @@ -0,0 +1,37 @@ +"""Trusted Chess configuration, usable without native dependencies.""" +from config_schema import validate_engine_versions + +BENCHMARK = 'chess' +SCHEMA_VERSION = '1.0.0' +ENV_ID = 'classic/chess-v6' +PROFILE = 'chess-public-board-native-v1' +PROFILES = {PROFILE} +METRICS = {'match_points'} +REDUCERS = {('family_macro', '1.0.0')} +FIELDS = {'engine_versions', 'engine_commit', 'engine_wheel_sha256', 'controlled_agent', + 'initialization_policy', 'opponent_policy', 'opponent_seed', 'tool_policy'} +VERSIONS = {'pettingzoo': '1.27.0', 'chess': '1.11.2', 'gymnasium': '1.0.0', + 'numpy': '1.26.4', 'pygame-ce': '2.5.6'} +COMMIT = '7221e4b15873a8b16555fda038a77a6ae595e88d' +WHEEL = '075a6ab7c32d32d9a674f1af395010198bf09c172341aa38fa5415461601ac61' + + +def validate(value): + validate_engine_versions(value['engine_versions'], VERSIONS) + expected = { + 'env_id': ENV_ID, 'family': 'standard-start', 'controlled_agent': 'player_0', + 'initialization_policy': 'native-start-v1', 'opponent_policy': 'hash-legal-v1', + 'engine_commit': COMMIT, 'engine_wheel_sha256': WHEEL, + 'tool_policy': 'public-tools-no-task-solutions-v1', + 'capabilities': {'images': False, 'action_mode': 'enum', 'timing': 'action-stepped', + 'native_truncation': True}, + 'metric_spec': {'primary': 'match_points', 'reducer': 'family_macro', + 'reducer_version': '1.0.0', 'success_label': 'native_white_win'}, + } + for field, frozen in expected.items(): + if value[field] != frozen: + raise ValueError(f'unsupported Chess {field}') + if type(value['opponent_seed']) is not int or not 0 <= value['opponent_seed'] < 2**31: + raise ValueError('invalid Chess opponent seed') + if value['max_steps'] is None: + raise ValueError('Chess requires a public decision budget') diff --git a/game_first_exam/benchmarks/chess/metric_rules.py b/game_first_exam/benchmarks/chess/metric_rules.py new file mode 100644 index 0000000..dc83bcf --- /dev/null +++ b/game_first_exam/benchmarks/chess/metric_rules.py @@ -0,0 +1,126 @@ +"""Validate the sealed Chess outcome and its half-move record.""" +import hashlib +import json +import os +from pathlib import Path +import re + +import chess + +from config_schema import HASH +from opponent import choose + +WHITE, BLACK = 'player_0', 'player_1' +ACTION_COUNT = 4672 +ACTION_ID = re.compile(r'0|[1-9][0-9]{0,3}') +UCI_MOVE = re.compile(r'[a-h][1-8][a-h][1-8][qrbn]?') +REWARDS = {'win': [1, -1], 'loss': [-1, 1], 'draw': [0, 0], + 'illegal_action': [-1, 0], 'unfinished': [0, 0]} +POINTS = {'win': 100, 'draw': 50, 'loss': 0, 'illegal_action': 0, 'unfinished': 0} +RESULTS = {'win': '1-0', 'loss': '0-1', 'draw': '1/2-1/2', + 'illegal_action': '*', 'unfinished': '*'} +DRAW_REASONS = {'stalemate', 'insufficient_material', 'fifty_moves', 'threefold_repetition', + 'seventyfive_moves', 'fivefold_repetition'} + + +def valid_action_id(value): + return isinstance(value, str) and ACTION_ID.fullmatch(value) is not None and int(value) < ACTION_COUNT + + +def valid_rewards(actual, expected): + return (isinstance(actual, list) and len(actual) == 2 + and all(type(value) in (int, float) for value in actual) and actual == expected) + + +def validate_metrics(final, instance): + m = final['metrics'] + outcome = m['outcome'] + if outcome not in POINTS: + raise ValueError('unknown Chess outcome') + illegal = int(outcome == 'illegal_action') + if (final['terminated'], final['truncated']) != (outcome != 'unfinished', bool(illegal)): + raise ValueError('Chess outcome disagrees with native flags') + if m['native_result'] != RESULTS[outcome] or not valid_rewards(m['native_rewards'], REWARDS[outcome]): + raise ValueError('Chess outcome disagrees with native result or rewards') + if (type(m['native_return']) not in (int, float) + or final['return'] != REWARDS[outcome][0] or m['native_return'] != final['return']): + raise ValueError('Chess return disagrees with native rewards') + if (outcome == 'draw' and m['draw_reason'] not in DRAW_REASONS + or outcome != 'draw' and m['draw_reason'] is not None): + raise ValueError('invalid Chess draw reason') + if type(m['match_points']) is not int or m['match_points'] != POINTS[outcome]: + raise ValueError('inconsistent Chess points') + if type(m['success']) is not int or m['success'] != int(outcome == 'win') or final['success'] != bool(m['success']): + raise ValueError('inconsistent Chess success') + + count_fields = ('agent_decisions', 'agent_legal_plies', 'opponent_plies', 'total_board_plies', + 'native_illegal_actions', 'setup_plies') + if any(type(m[field]) is not int or m[field] < 0 for field in count_fields): + raise ValueError('invalid Chess action counts') + white, black = m['agent_legal_plies'], m['opponent_plies'] + if (m['agent_decisions'] != final['steps'] or m['setup_plies'] != 0 + or m['native_illegal_actions'] != illegal or white + illegal != final['steps'] + or white + black != m['total_board_plies'] or white - black not in (0, 1) + or (outcome in {'loss', 'unfinished', 'illegal_action'} and white != black) + or (outcome == 'win' and white != black + 1)): + raise ValueError('inconsistent Chess action accounting') + if not isinstance(m['final_fen'], str) or len(m['final_fen'].split()) != 6: + raise ValueError('missing Chess final FEN') + if not HASH.fullmatch(m['trace_sha256']): + raise ValueError('invalid Chess trace digest') + trace_path = os.environ.get('CHESS_VERIFY_TRACE') + if trace_path: + validate_trace(Path(trace_path).read_bytes(), final, instance) + + +def validate_trace(data, final, instance): + """Replay the native game's legal moves and verify its outcome.""" + m = final['metrics'] + if hashlib.sha256(data).hexdigest() != m['trace_sha256']: + raise ValueError('Chess trace digest mismatch') + events = [json.loads(line) for line in data.splitlines()] + if len(events) != m['total_board_plies'] + m['native_illegal_actions']: + raise ValueError('Chess trace length mismatch') + history = [] + board = chess.Board() + for index, row in enumerate(events): + actor = WHITE if index % 2 == 0 else BLACK + last = index == len(events) - 1 + illegal = last and m['outcome'] == 'illegal_action' + native_end = last and final['terminated'] + if not isinstance(row, dict): + raise ValueError('Chess trace entry must be an object') + if (row['actor'] != actor or row['decision'] != index // 2 + 1 or row['fen_before'] != board.fen() + or type(row['decision']) is not int or type(row['ply']) is not int + or row['ply'] != index + 1 - int(illegal) + or row['terminated'] is not native_end or row['truncated'] is not illegal + or not valid_rewards(row['rewards'], m['native_rewards'] if last else [0, 0])): + raise ValueError('Chess trace has inconsistent turn or terminal state') + legal, action = row['legal_moves'], row['action_id'] + if (not valid_action_id(action) or not isinstance(legal, dict) or not legal + or any(not valid_action_id(key) or not isinstance(move, str) or not UCI_MOVE.fullmatch(move) + for key, move in legal.items()) + or len(set(legal.values())) != len(legal)): + raise ValueError('Chess trace has an invalid action ID or legal move map') + if (action in legal) == illegal or row['uci'] != legal.get(action): + raise ValueError('Chess trace action disagrees with the reported legal mask') + if set(legal.values()) != {move.uci() for move in board.legal_moves}: + raise ValueError('Chess trace legal map disagrees with replay') + if actor == BLACK and action != choose(legal, instance['opponent_seed'], history): + raise ValueError('Chess trace action disagrees with the frozen opponent') + if not illegal: + board.push_uci(row['uci']) + history.append(row['uci']) + if row['fen_after'] != board.fen(): + raise ValueError('Chess trace board disagrees with replay') + # PettingZoo ends on claimable draws as well as checkmate and stalemate. + outcome = board.outcome(claim_draw=True) + if (outcome is not None) != (native_end and not illegal): + raise ValueError('Chess trace termination disagrees with replay') + if board.fen() != m['final_fen']: + raise ValueError('Chess trace final FEN mismatch') + outcome = board.outcome(claim_draw=True) + if outcome is not None: + draw_reason = outcome.termination.name.lower() if outcome.winner is None else None + if outcome.result() != m['native_result'] or draw_reason != m['draw_reason']: + raise ValueError('Chess trace result disagrees with replay') diff --git a/game_first_exam/benchmarks/chess/opponent.py b/game_first_exam/benchmarks/chess/opponent.py new file mode 100644 index 0000000..1c5647f --- /dev/null +++ b/game_first_exam/benchmarks/chess/opponent.py @@ -0,0 +1,10 @@ +"""Deterministic selection from the native legal action map.""" +import hashlib +import json + + +def choose(legal, seed, history): + ordered = sorted(legal, key=legal.__getitem__) + key = json.dumps([seed, len(history), history], separators=(',', ':')).encode() + index = int.from_bytes(hashlib.sha256(key).digest(), 'big') % len(ordered) + return ordered[index] diff --git a/game_first_exam/benchmarks/chess/requirements.txt b/game_first_exam/benchmarks/chess/requirements.txt new file mode 100644 index 0000000..e8a995f --- /dev/null +++ b/game_first_exam/benchmarks/chess/requirements.txt @@ -0,0 +1,11 @@ +pettingzoo==1.27.0 --hash=sha256:075a6ab7c32d32d9a674f1af395010198bf09c172341aa38fa5415461601ac61 +-r chess-requirements.txt +numpy==1.26.4 --hash=sha256:675d61ffbfa78604709862923189bad94014bef562cc35cf61d3a07bba02a7ed --hash=sha256:08beddf13648eb95f8d867350f6a018a4be2e5ad54c8d8caed89ebca558b2818 +gymnasium==1.0.0 --hash=sha256:b6f40e1e24c5bd419361e1a5b86a9117d2499baecc3a660d44dfff4c465393ad +typing_extensions==4.16.0 --hash=sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8 +pygame-ce==2.5.6 --hash=sha256:6ed8163e389d5dfcf7817458792c4eaeb96a50393d63a9c4d3384eb2b8944123 --hash=sha256:2759a2e83234cb276edb16ea6fa858736bbe64977ba35e0f83844c255ba846e7 +cloudpickle==3.1.1 --hash=sha256:c8c5a44295039331ee9dad40ba100a9c7297b6f988e50e87ccdf3765a668350e +farama-notifications==0.0.4 --hash=sha256:14de931035a41961f7c056361dc7f980762a143d05791ef5794a751a2caf05ae +pillow==10.4.0 --hash=sha256:bf2342ac639c4cf38799a44950bbc2dfcb685f052b9e262f446482afaf4bffca --hash=sha256:86dcb5a1eb778d8b25659d5e4341269e8590ad6b4e8b44d9f4b07f8d136c414a --hash=sha256:1d846aea995ad352d4bdcc847535bd56e0fd88d36829d2c90be880ef1ee4668a +imageio==2.37.0 --hash=sha256:11efa15b87bc7871b61590326b2d635439acc321cf7f8ce996f812543ce10eed +imageio-ffmpeg==0.6.0 --hash=sha256:c7e46fcec401dd990405049d2e2f475e2b397779df2519b544b8aab515195282 --hash=sha256:02fa47c83703c37df6bfe4896aab339013f62bf02c5ebf2dce6da56af04ffc0a diff --git a/game_first_exam/images/chess-files/FILES.json b/game_first_exam/images/chess-files/FILES.json new file mode 100644 index 0000000..d84d64f --- /dev/null +++ b/game_first_exam/images/chess-files/FILES.json @@ -0,0 +1,14 @@ +{ + "image": "ghcr.io/mll-lab-nu/efe:chess-files-0.1.2@sha256:75f183dd662d4388d072ea4f5d266fecace649176074d226f14e13caee106add", + "source": "game_first_exam/benchmarks/chess", + "files": { + "SOURCE.json": "fcf83f0723e7f43fab0894cbf867bb097fcb2f72568826e854fe678767b6c8aa", + "adapter.py": "d31ddfdcfe910fe46ab5712303690b162701d191557e98cfbadd77829a856589", + "build-requirements.txt": "83f111e093bad00e18d8ee645a55359e4a3b9ea26a1b2d8b91776712a0db30fb", + "chess-requirements.txt": "7d46bd5d8cec63418af9a29320b9f922a7972b54c3419c8434182ae27a2e94ac", + "instance_schema.py": "e7dbbfc5323f21916149905afbe6fad03ebefc2c1c431e9332926b08bdca8671", + "metric_rules.py": "aa9217750518596d085ed57500c0fca4d8f55140359ffb908541790b60821ea9", + "opponent.py": "a0db0920375a1892ef13b6f8b1dd30f73ec8a137ca667d91e1b62ee7a6b94db4", + "requirements.txt": "b1a71e2d4448d9bc8a84ea70861eb4607e9ecb9ce073d05903401c0e8bc3769f" + } +} diff --git a/game_first_exam/images/chess-files/README.md b/game_first_exam/images/chess-files/README.md new file mode 100644 index 0000000..00207d7 --- /dev/null +++ b/game_first_exam/images/chess-files/README.md @@ -0,0 +1,3 @@ +# Chess files image + +The deterministic payload provides the Chess adapter, opponent, verifier rules, schema and dependency locks. Prepare the `chess` suite to assemble and load it locally. The pinned digest is derived from this checkout. diff --git a/game_first_exam/images/chess-files/VERSION b/game_first_exam/images/chess-files/VERSION new file mode 100644 index 0000000..d917d3e --- /dev/null +++ b/game_first_exam/images/chess-files/VERSION @@ -0,0 +1 @@ +0.1.2 diff --git a/game_first_exam/tasks/chess/README.md b/game_first_exam/tasks/chess/README.md new file mode 100644 index 0000000..e04418f --- /dev/null +++ b/game_first_exam/tasks/chess/README.md @@ -0,0 +1,13 @@ +# PettingZoo Chess Standard smoke + +The `chess` suite freezes one standard-start match. Its current engineering condition uses White as the sole evaluated player and a deterministic Black policy. The provisional policy permits public tools, including chess engines, subject to the task-specific answer restriction. This condition measures a coding agent operating a chess client with those tools. Tool policy, observation profile, budget and match scoring are pending benchmark review. + +The simulator uses AEC `classic/chess-v6` (PettingZoo 1.27.0), with chess 1.11.2 on Python 3.12. Source hashes and the simulator's Windows x64 and Linux x86-64 dependency locks are kept with the [adapter](../../benchmarks/chess). The engine receives one reset to the standard board. One client decision executes one native call for White and at most one native call for Black. The policy sorts the native legal map by absolute UCI and indexes it with SHA-256 of the frozen opponent seed, history length and UCI history. + +`chess-public-board-native-v1` publishes the unmodified white-view tensor and mask as lists, alongside derived FEN, board text, move map, history and outcome. The native initial history planes are zero. The native mask may remain nonzero at termination while the public legal map is empty. Legal action IDs use the action encoding of the current native player. Public move text always uses absolute UCI. + +A mask-zero ID within the action space ends the episode through the native wrapper, with White reward −1, Black reward 0 and both native flags set. The service rejects unknown strings before they reach the simulator. The engine ends the game when it detects claimable draws, including a draw that could be claimed on the next move. Public exhaustion preserves the unfinished status and actual native flags. + +`match_points` is 100 for White checkmate, 50 for a draw and 0 for loss, illegal move or unfinished games. The independent verifier checks the native rewards, flags, action counts and trace digest. It replays UCI moves with the pinned rules library and checks each legal move set, FEN and the resulting termination. It verifies Black's policy against the recorded action map. The trusted simulator supplies the mapping from PettingZoo action IDs to UCI. Each event includes the actor, legal map, ID and UCI, rewards, flags, decision index, ply and FEN transition. Rejected requests are recorded by the shared service. The shared video captures the initial board and one frame after each public decision. + +PettingZoo is MIT licensed. The `chess` distribution declares GPL-3.0-or-later and pygame-ce declares LGPL-2.1. Review obligations for dependency and image redistribution, bundled FFmpeg binaries and all upstream chessboard assets before publishing. The task does not bundle an external chess engine. diff --git a/game_first_exam/tasks/chess/chess-match-i01-standard/DIGEST b/game_first_exam/tasks/chess/chess-match-i01-standard/DIGEST new file mode 100644 index 0000000..f238e5c --- /dev/null +++ b/game_first_exam/tasks/chess/chess-match-i01-standard/DIGEST @@ -0,0 +1 @@ +sha256:e20971d408b67e43faa9a13207a1abbd40a763a8f8a830c0ec6a72a932cdcab0 diff --git a/game_first_exam/tasks/chess/chess-match-i01-standard/README.md b/game_first_exam/tasks/chess/chess-match-i01-standard/README.md new file mode 100644 index 0000000..d941f82 --- /dev/null +++ b/game_first_exam/tasks/chess/chess-match-i01-standard/README.md @@ -0,0 +1,35 @@ +# chess-match-i01-standard + +| | | +|---|---| +| Benchmark | Chess | +| Mode | standard (`game-standard/2.2`) | +| Twin | — (none: Chess has no privileged mode, PROTOCOL §2) | +| Simulator / robot | `chess` / `game-agent` | +| Family / instance | `standard-start` / seed 2117382936 | +| 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 +White plays from the standard starting position against the frozen hash-based opponent. The public decision limit is 128 and the coding agent's time budget is 600 seconds. See the [benchmark audit](../README.md) for source, observation and grading details. + +## Difficulty +Engineering smoke match against a deterministic legal-move policy. Difficulty remains uncalibrated. + +## Reference solution +The frozen client route reaches a native White checkmate in 26 decisions and 51 board plies. The `solution/` directory is reserved for reference runs. + +## Verification +The isolated verifier replays the UCI trace from the standard position and checks the final result, decision counts, trace digest and black replies against the frozen policy. + +## 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/chess/chess-match-i01-standard/environment/Dockerfile b/game_first_exam/tasks/chess/chess-match-i01-standard/environment/Dockerfile new file mode 100644 index 0000000..d5adc3f --- /dev/null +++ b/game_first_exam/tasks/chess/chess-match-i01-standard/environment/Dockerfile @@ -0,0 +1,11 @@ +FROM docker.io/library/python:3.12.10-slim-bookworm@sha256:fd95fa221297a88e1cf49c55ec1828edd7c5a428187e67b5d1805692d11588db +RUN sed -i 's|http://deb.debian.org/|https://deb.debian.org/|g' /etc/apt/sources.list.d/debian.sources \ + && apt-get -o Acquire::Retries=0 update \ + && apt-get -o Acquire::Retries=0 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/chess/chess-match-i01-standard/environment/docker-compose.yaml b/game_first_exam/tasks/chess/chess-match-i01-standard/environment/docker-compose.yaml new file mode 100644 index 0000000..945cf2a --- /dev/null +++ b/game_first_exam/tasks/chess/chess-match-i01-standard/environment/docker-compose.yaml @@ -0,0 +1,44 @@ +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: + CHESS_TRACE_PATH: /data/chess_plies.jsonl + 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/chess/chess-match-i01-standard/environment/rcb_monitor/limits.json b/game_first_exam/tasks/chess/chess-match-i01-standard/environment/rcb_monitor/limits.json new file mode 100644 index 0000000..71850b0 --- /dev/null +++ b/game_first_exam/tasks/chess/chess-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": "chess-match-i01-standard", + "tick_sec": 5 +} diff --git a/game_first_exam/tasks/chess/chess-match-i01-standard/environment/sim/Dockerfile b/game_first_exam/tasks/chess/chess-match-i01-standard/environment/sim/Dockerfile new file mode 100644 index 0000000..5e7e9f8 --- /dev/null +++ b/game_first_exam/tasks/chess/chess-match-i01-standard/environment/sim/Dockerfile @@ -0,0 +1,11 @@ +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:chess-files-0.1.2@sha256:75f183dd662d4388d072ea4f5d266fecace649176074d226f14e13caee106add /build-requirements.txt /chess-requirements.txt /requirements.txt /locks/ +RUN pip install --require-hashes --retries 0 --timeout 30 -r /locks/build-requirements.txt \ + && pip install --require-hashes --no-build-isolation --retries 0 --timeout 30 -r /locks/requirements.txt \ + && pip check +COPY --from=ghcr.io/mll-lab-nu/efe:game-files-0.6.0@sha256:bfb708928954d5cc194a614ab772a65b1e56f381b49dfeb2227c3d609e5f2ecc /server.py /reducers.py /config_schema.py /contracts.py /encoding.py /recording.py /srv/ +COPY --from=ghcr.io/mll-lab-nu/efe:chess-files-0.1.2@sha256:75f183dd662d4388d072ea4f5d266fecace649176074d226f14e13caee106add /adapter.py /instance_schema.py /metric_rules.py /opponent.py /srv/ +COPY instance.json /srv/instance.json +WORKDIR /srv +CMD ["python3", "/srv/server.py"] diff --git a/game_first_exam/tasks/chess/chess-match-i01-standard/environment/sim/instance.json b/game_first_exam/tasks/chess/chess-match-i01-standard/environment/sim/instance.json new file mode 100644 index 0000000..e14c26b --- /dev/null +++ b/game_first_exam/tasks/chess/chess-match-i01-standard/environment/sim/instance.json @@ -0,0 +1,38 @@ +{ + "schema_version": "game-instance/2.2", + "protocol": "game-standard/2.2", + "adapter_version": "1.0.0", + "benchmark": "chess", + "env_id": "classic/chess-v6", + "family": "standard-start", + "seed": 2117382936, + "max_steps": 128, + "observation_profile": "chess-public-board-native-v1", + "engine_versions": { + "pettingzoo": "1.27.0", + "chess": "1.11.2", + "gymnasium": "1.0.0", + "numpy": "1.26.4", + "pygame-ce": "2.5.6" + }, + "engine_commit": "7221e4b15873a8b16555fda038a77a6ae595e88d", + "engine_wheel_sha256": "075a6ab7c32d32d9a674f1af395010198bf09c172341aa38fa5415461601ac61", + "controlled_agent": "player_0", + "initialization_policy": "native-start-v1", + "opponent_policy": "hash-legal-v1", + "opponent_seed": 2117382936, + "tool_policy": "public-tools-no-task-solutions-v1", + "metric_spec": { + "primary": "match_points", + "reducer": "family_macro", + "reducer_version": "1.0.0", + "success_label": "native_white_win" + }, + "capabilities": { + "images": false, + "action_mode": "enum", + "timing": "action-stepped", + "native_truncation": true + }, + "initial_state_sha256": "b4075f20eb23191657bfaa63c55b729f301bcd4f5db5fd8995214b659589bfe6" +} diff --git a/game_first_exam/tasks/chess/chess-match-i01-standard/instruction.md b/game_first_exam/tasks/chess/chess-match-i01-standard/instruction.md new file mode 100644 index 0000000..eb1fb3c --- /dev/null +++ b/game_first_exam/tasks/chess/chess-match-i01-standard/instruction.md @@ -0,0 +1,40 @@ +# PettingZoo Chess · Standard Match + +You play White from the standard chess starting position against a fixed computer opponent. Use the Python client to win the game. + +## Rules + +- Use a program to read the board and submit moves. Your program may make several decisions in a loop. +- You have at most 128 decisions and cannot reset the game. Stop when `done` is true. +- A native win earns 100 points and a native draw earns 50. A loss, illegal move ending or unfinished game earns 0. The played game supplies the score. + +## Client (`/app/game_client.py`) + +```python +from game_client import GameClient + +game = GameClient() +snapshot = game.observe() # read one snapshot without spending a decision +board = snapshot["observation"] +print(board["board_ascii"], board["legal_moves"]) + +# Choose an action ID from legal_moves and pass it as a string. +# snapshot = game.step(chosen_id, expected_step=snapshot["step"]) +``` + +`board_ascii` shows ranks 8 through 1 and files a through h. `board_fen` is the full public position in FEN format. `legal_moves` maps action ID strings to absolute UCI moves, including promotion suffixes. `move_history_uci` lists all played moves, and `last_round_moves` lists the latest actions with actor, ID and move. + +The enhanced observation includes the original white-view 8×8×111 Boolean tensor (`native_observation`) and 4,672-entry integer `action_mask`, both as JSON lists. Use `legal_moves` to select an action. An ID from `"0"` through `"4671"` outside the current legal set ends the game. An invalid action string outside that ID set is rejected before play advances. + +A step plays your move and, if the game continues, one Black move. The response contains one updated snapshot. `step` counts accepted White decisions and `steps_remaining` counts the remaining decisions. `time_left_s` is the service countdown in seconds from the first observation or accepted action. If a response is lost or the step is stale, call `observe()` before choosing your next action. A terminal snapshot can retain native mask entries. Always check `done` before moving. + +## External material +You may use public tools, including chess engines and rule libraries. Do not obtain a precomputed answer for this specific benchmark instance or access private evaluator files. + +## 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/chess/chess-match-i01-standard/solution/solve.sh b/game_first_exam/tasks/chess/chess-match-i01-standard/solution/solve.sh new file mode 100755 index 0000000..54e2df7 --- /dev/null +++ b/game_first_exam/tasks/chess/chess-match-i01-standard/solution/solve.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -euo pipefail +python3 - <<'PYCODE' +import json +from pathlib import Path + +from game_client import GameClient + +game = GameClient() +state = game.observe() +moves = json.loads(Path("/solution/white_moves.json").read_text()) +for uci in moves: + assert not state["done"], "reference match ended early" + action = next(key for key, move in state["observation"]["legal_moves"].items() if move == uci) + state = game.step(action, expected_step=state["step"]) +assert state["done"] and state["observation"]["outcome"] == "win", "expected a native white win" +print("Native white win after", state["step"], "decisions and", + len(state["observation"]["move_history_uci"]), "plies") +PYCODE diff --git a/game_first_exam/tasks/chess/chess-match-i01-standard/solution/white_moves.json b/game_first_exam/tasks/chess/chess-match-i01-standard/solution/white_moves.json new file mode 100644 index 0000000..46df954 --- /dev/null +++ b/game_first_exam/tasks/chess/chess-match-i01-standard/solution/white_moves.json @@ -0,0 +1,6 @@ +[ + "d2d3", "c1h6", "h6g7", "g7h8", "h8g7", "g7f6", "f6d8", + "d8c7", "c7e5", "e5b8", "b8a7", "a7b8", "b1c3", "c3d5", + "g1f3", "f3d4", "d4b5", "d1d2", "b5d6", "d2g5", + "d6b7", "b7c5", "h2h3", "g5f4", "f4f6", "f6b6" +] diff --git a/game_first_exam/tasks/chess/chess-match-i01-standard/task.toml b/game_first_exam/tasks/chess/chess-match-i01-standard/task.toml new file mode 100644 index 0000000..ccdd22c --- /dev/null +++ b/game_first_exam/tasks/chess/chess-match-i01-standard/task.toml @@ -0,0 +1,59 @@ +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/chess_plies.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/chess-match-i01-standard" +description = "Win from the standard Chess position as White against a deterministic opponent." +keywords = ["game", "chess", "pettingzoo", "standard-mode"] + +[metadata] +task_type = "trajectory" +simulator = "chess" +robot = "game-agent" +family = "standard-start" +dynamics = "static" +protocol = "game-standard/2.2" +oracle = "full" +instance_seed = 2117382936 +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/chess/chess-match-i01-standard/tests/Dockerfile b/game_first_exam/tasks/chess/chess-match-i01-standard/tests/Dockerfile new file mode 100644 index 0000000..c44cff2 --- /dev/null +++ b/game_first_exam/tasks/chess/chess-match-i01-standard/tests/Dockerfile @@ -0,0 +1,12 @@ +FROM docker.io/library/python:3.12.10-slim-bookworm@sha256:fd95fa221297a88e1cf49c55ec1828edd7c5a428187e67b5d1805692d11588db +COPY --from=ghcr.io/mll-lab-nu/efe:chess-files-0.1.2@sha256:75f183dd662d4388d072ea4f5d266fecace649176074d226f14e13caee106add /build-requirements.txt /chess-requirements.txt /locks/ +RUN pip install --require-hashes --retries 0 --timeout 30 -r /locks/build-requirements.txt \ + && pip install --require-hashes --no-build-isolation --retries 0 --timeout 30 -r /locks/chess-requirements.txt \ + && pip check +COPY test.sh instance.json /tests/ +COPY --from=ghcr.io/mll-lab-nu/efe:game-files-0.6.0@sha256:bfb708928954d5cc194a614ab772a65b1e56f381b49dfeb2227c3d609e5f2ecc /grade.py /reducers.py /config_schema.py /tests/ +COPY --from=ghcr.io/mll-lab-nu/efe:chess-files-0.1.2@sha256:75f183dd662d4388d072ea4f5d266fecace649176074d226f14e13caee106add /instance_schema.py /metric_rules.py /opponent.py /tests/ +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/chess/chess-match-i01-standard/tests/instance.json b/game_first_exam/tasks/chess/chess-match-i01-standard/tests/instance.json new file mode 100644 index 0000000..e14c26b --- /dev/null +++ b/game_first_exam/tasks/chess/chess-match-i01-standard/tests/instance.json @@ -0,0 +1,38 @@ +{ + "schema_version": "game-instance/2.2", + "protocol": "game-standard/2.2", + "adapter_version": "1.0.0", + "benchmark": "chess", + "env_id": "classic/chess-v6", + "family": "standard-start", + "seed": 2117382936, + "max_steps": 128, + "observation_profile": "chess-public-board-native-v1", + "engine_versions": { + "pettingzoo": "1.27.0", + "chess": "1.11.2", + "gymnasium": "1.0.0", + "numpy": "1.26.4", + "pygame-ce": "2.5.6" + }, + "engine_commit": "7221e4b15873a8b16555fda038a77a6ae595e88d", + "engine_wheel_sha256": "075a6ab7c32d32d9a674f1af395010198bf09c172341aa38fa5415461601ac61", + "controlled_agent": "player_0", + "initialization_policy": "native-start-v1", + "opponent_policy": "hash-legal-v1", + "opponent_seed": 2117382936, + "tool_policy": "public-tools-no-task-solutions-v1", + "metric_spec": { + "primary": "match_points", + "reducer": "family_macro", + "reducer_version": "1.0.0", + "success_label": "native_white_win" + }, + "capabilities": { + "images": false, + "action_mode": "enum", + "timing": "action-stepped", + "native_truncation": true + }, + "initial_state_sha256": "b4075f20eb23191657bfaa63c55b729f301bcd4f5db5fd8995214b659589bfe6" +} diff --git a/game_first_exam/tasks/chess/chess-match-i01-standard/tests/rcb_limits.json b/game_first_exam/tasks/chess/chess-match-i01-standard/tests/rcb_limits.json new file mode 100644 index 0000000..71850b0 --- /dev/null +++ b/game_first_exam/tasks/chess/chess-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": "chess-match-i01-standard", + "tick_sec": 5 +} diff --git a/game_first_exam/tasks/chess/chess-match-i01-standard/tests/test.sh b/game_first_exam/tasks/chess/chess-match-i01-standard/tests/test.sh new file mode 100755 index 0000000..f645c35 --- /dev/null +++ b/game_first_exam/tasks/chess/chess-match-i01-standard/tests/test.sh @@ -0,0 +1,7 @@ +#!/bin/bash +rm -rf /logs/verifier/* # verdicts from an earlier run never survive (docs/protocol/README.md Appendix H.1) +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) +set -eu +mkdir -p /logs/verifier +CHESS_VERIFY_TRACE=/data/chess_plies.jsonl python3 /tests/grade.py 2>/logs/verifier/grade.log diff --git a/game_first_exam/tests/benchmarks/chess/exported.toml b/game_first_exam/tests/benchmarks/chess/exported.toml new file mode 100644 index 0000000..a81b5fd --- /dev/null +++ b/game_first_exam/tests/benchmarks/chess/exported.toml @@ -0,0 +1,7 @@ +[protocols] +standard = ["game-standard/2.2"] + +[[tasks]] +name = "chess-match-i01-standard" +source_task = "classic/chess-v6" +protocol = "game-standard/2.2" diff --git a/game_first_exam/tests/envs/chess.Dockerfile b/game_first_exam/tests/envs/chess.Dockerfile new file mode 100644 index 0000000..272aaec --- /dev/null +++ b/game_first_exam/tests/envs/chess.Dockerfile @@ -0,0 +1,7 @@ +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 game_first_exam/benchmarks/chess/*requirements.txt /locks/ +RUN pip install --require-hashes --retries 0 --timeout 30 -r /locks/build-requirements.txt \ + && pip install --require-hashes --no-build-isolation --retries 0 --timeout 30 -r /locks/requirements.txt \ + && pip check +WORKDIR /repo diff --git a/game_first_exam/tests/run.sh b/game_first_exam/tests/run.sh index a033e85..109f021 100755 --- a/game_first_exam/tests/run.sh +++ b/game_first_exam/tests/run.sh @@ -13,6 +13,10 @@ case "${1:-common}" in python3 -m unittest discover -s game_first_exam/tests -p 'test_game_connection.py' python3 -m unittest discover -s game_first_exam/tests -p 'test_game_modes.py' ;; + chess) + python3 game_first_exam/tests/test_chess_native.py -v + python3 game_first_exam/tests/test_chess.py -v + ;; minihack) export GAME_TEST_BENCHMARK=minihack python3 game_first_exam/tests/test_game_adapters.py diff --git a/game_first_exam/tests/test_chess.py b/game_first_exam/tests/test_chess.py new file mode 100644 index 0000000..ac27ac8 --- /dev/null +++ b/game_first_exam/tests/test_chess.py @@ -0,0 +1,236 @@ +"""Chess adapter, public service and independent grading checks.""" +import copy +import hashlib +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 / path) for path in ('scripts', 'game_first_exam/runtime', + 'game_first_exam/benchmarks/chess')] + +from adapter import Adapter +from config_schema import validate_instance +from game_schemas import load_schema +from grade import grade +from metric_rules import validate_metrics +from server import Game, InvalidAction + +INSTANCE = ROOT / 'game_first_exam/tasks/chess/chess-match-i01-standard/tests/instance.json' + + +class ChessIntegrationTests(unittest.TestCase): + def setUp(self): + load_schema('chess') + self.instance = json.loads(INSTANCE.read_text()) + temp = tempfile.TemporaryDirectory() + self.addCleanup(temp.cleanup) + self.output = Path(temp.name) + self.trace = self.output / 'chess_plies.jsonl' + + def open_game(self): + with patch.dict(os.environ, {'CHESS_TRACE_PATH': str(self.trace)}): + game = Game.open(Adapter, self.instance, None, self.output) + self.addCleanup(game.close) + self.assertIsNone(game.final) + return game + + def play(self, game, uci): + action = next(key for key, move in game.observe()['observation']['legal_moves'].items() if move == uci) + return game.submit({'action': action, 'expected_step': game.steps, 'request_id': str(game.steps)}) + + def score(self, game, outcome, points): + self.assertEqual(game.final['metrics']['outcome'], outcome) + with patch.dict(os.environ, {'CHESS_VERIFY_TRACE': str(self.trace)}): + result = grade(game.final, self.instance, validate_metrics) + self.assertEqual(result['primary_score'], points) + self.assertEqual(result['success'], float(outcome == 'win')) + + def test_round_retry_determinism_and_public_budget(self): + self.instance['max_steps'] = 1 + game = self.open_game() + initial = game.adapter.fingerprint() + public = game.adapter.observe() + public['legal_moves'].clear() + game.adapter.frame() + self.assertEqual(game.adapter.fingerprint(), initial) + self.assertEqual(len(game.observe()['observation']['legal_moves']), 20) + with self.assertRaises(InvalidAction): + game.submit({'action': '4672', 'expected_step': 0, 'request_id': 'rejected'}) + self.assertEqual(game.steps, 0) + self.assertEqual(self.trace.read_bytes(), b'') + action = next(iter(game.observe()['observation']['legal_moves'])) + request = {'action': action, 'expected_step': 0, 'request_id': 'retry'} + result = game.submit(request) + self.assertEqual(game.submit(request), result) + self.assertEqual(result['observation']['side_to_move'], 'white') + self.assertEqual(game.final['reason'], 'step_limit') + self.score(game, 'unfinished', 0) + other = Adapter(self.instance) + self.addCleanup(other.close) + self.assertEqual(other.fingerprint(), initial) + other.step(action) + self.assertEqual(other.fingerprint(), game.adapter.fingerprint()) + self.assertEqual(other.metrics()['total_board_plies'], 2) + original = self.trace.read_bytes() + self.trace.write_bytes(original + b'\n') + with self.assertRaisesRegex(ValueError, 'digest mismatch'): + self.score(game, 'unfinished', 0) + + def test_native_illegal_and_verifier_mismatch(self): + game = self.open_game() + response = game.submit({'action': '0', 'expected_step': 0, 'request_id': 'illegal'}) + self.assertTrue(response['done']) + self.assertEqual(response['observation']['legal_moves'], {}) + self.assertEqual(game.final['metrics']['total_board_plies'], 0) + self.score(game, 'illegal_action', 0) + final = copy.deepcopy(game.final) + final['metrics']['match_points'] = 50 + with self.assertRaisesRegex(ValueError, 'points'): + grade(final, self.instance, validate_metrics) + + def test_verifier_rejects_malformed_evidence_even_with_matching_digest(self): + game = self.open_game() + self.play(game, 'e2e4') + game.finalize('agent_finished') + events = [json.loads(line) for line in self.trace.read_bytes().splitlines()] + for update in ({'terminated': 0}, {'decision': True}, {'rewards': [False, 0]}, + {'action_id': '04672'}, {'legal_moves': {'1': 'bad'}}): + with self.subTest(update=update): + first = {**events[0], **update} + payload = b''.join((json.dumps(row) + '\n').encode() for row in [first, *events[1:]]) + self.trace.write_bytes(payload) + invalid = copy.deepcopy(game.final) + invalid['metrics']['trace_sha256'] = hashlib.sha256(payload).hexdigest() + with patch.dict(os.environ, {'CHESS_VERIFY_TRACE': str(self.trace)}), self.assertRaises(ValueError): + grade(invalid, self.instance, validate_metrics) + invalid = copy.deepcopy(game.final) + invalid['metrics']['native_return'] = False + with self.assertRaisesRegex(ValueError, 'return'): + grade(invalid, self.instance, validate_metrics) + + def test_verifier_rejects_consistent_digest_and_fen_chain_with_wrong_board(self): + game = self.open_game() + self.play(game, 'e2e4') + game.finalize('agent_finished') + first, second = [json.loads(line) for line in self.trace.read_bytes().splitlines()] + # The old verifier accepted this because it matched both sides of the FEN link. + first['fen_after'] = second['fen_before'] = first['fen_after'].replace(' b ', ' w ') + payload = b''.join((json.dumps(row) + '\n').encode() for row in (first, second)) + self.trace.write_bytes(payload) + final = copy.deepcopy(game.final) + final['metrics']['trace_sha256'] = hashlib.sha256(payload).hexdigest() + with patch.dict(os.environ, {'CHESS_VERIFY_TRACE': str(self.trace)}): + with self.assertRaisesRegex(ValueError, 'board disagrees with replay'): + grade(final, self.instance, validate_metrics) + + def test_verifier_rejects_win_on_unfinished_board(self): + self.instance['max_steps'] = 1 + game = self.open_game() + with self.scripted('e7e5'): + self.play(game, 'e2e4') + first, _ = [json.loads(line) for line in self.trace.read_bytes().splitlines()] + first.update(terminated=True, rewards=[1, -1]) + payload = (json.dumps(first) + '\n').encode() + self.trace.write_bytes(payload) + final = copy.deepcopy(game.final) + final.update(terminated=True, success=True, reason='native_terminated', end_source='native') + final['return'] = 1 + final['metrics'].update(outcome='win', match_points=100, success=1, native_result='1-0', + native_return=1, native_rewards=[1, -1], opponent_plies=0, + total_board_plies=1, final_fen=first['fen_after'], + trace_sha256=hashlib.sha256(payload).hexdigest()) + with patch.dict(os.environ, {'CHESS_VERIFY_TRACE': str(self.trace)}): + with self.assertRaisesRegex(ValueError, 'termination disagrees with replay'): + grade(final, self.instance, validate_metrics) + + def scripted(self, responses, target='adapter.choose'): + """Use real AEC moves while forcing a terminal test fixture for Black.""" + remaining = iter(responses.split()) + + def policy(legal, seed, history): + response = next(remaining) + return next(key for key, move in legal.items() if move == response) + + return patch(target, side_effect=policy) + + def test_native_loss(self): + game = self.open_game() + with self.scripted('e7e5 d8h4') as black: + self.play(game, 'f2f3') + self.assertTrue(self.play(game, 'g2g4')['done']) + self.assertEqual(black.call_count, 2) + with self.scripted('e7e5 d8h4', 'metric_rules.choose'): + self.score(game, 'loss', 0) + self.assertEqual(game.final['metrics']['total_board_plies'], 4) + + def test_native_win_on_last_decision(self): + self.instance['max_steps'] = 4 + game = self.open_game() + with self.scripted('e7e5 b8c6 g8f6') as black: + for uci in ('e2e4', 'f1c4', 'd1h5', 'h5f7'): + result = self.play(game, uci) + self.assertEqual(black.call_count, 3) + self.assertTrue(result['done']) + self.assertTrue(game.final['budget_exhausted']) + self.assertEqual(game.final['reason'], 'native_terminated') + with self.scripted('e7e5 b8c6 g8f6', 'metric_rules.choose'): + self.score(game, 'win', 100) + + def test_native_draw(self): + game = self.open_game() + with self.scripted('g8f6 f6g8 g8f6'): + for uci in ('g1f3', 'f3g1', 'g1f3', 'f3g1'): + result = self.play(game, uci) + self.assertTrue(result['done']) + self.assertEqual(game.final['metrics']['draw_reason'], 'threefold_repetition') + with self.scripted('g8f6 f6g8 g8f6', 'metric_rules.choose'): + self.score(game, 'draw', 50) + + def test_stale_step_does_not_advance_and_timeout_is_unfinished(self): + game = self.open_game() + with patch('server.time.monotonic', return_value=100.0): + response = self.play(game, 'e2e4') + trace = self.trace.read_bytes() + next_action = next(iter(response['observation']['legal_moves'])) + request = {'action': next_action, 'expected_step': 0, 'request_id': 'stale'} + with patch('server.time.monotonic', return_value=101.0): + with self.assertRaisesRegex(ValueError, 'stale expected_step'): + game.submit(request) + self.assertEqual(self.trace.read_bytes(), trace) + self.assertEqual(game.steps, 1) + with patch('server.time.monotonic', return_value=701.0): + self.assertTrue(game.observe()['done']) + self.assertEqual(game.final['reason'], 'time_limit') + self.score(game, 'unfinished', 0) + + def test_zero_decisions_are_unfinished(self): + game = self.open_game() + game.finalize('agent_finished') + self.score(game, 'unfinished', 0) + + def test_illegal_opponent_invalidates_environment(self): + game = self.open_game() + with patch('adapter.choose', return_value='invalid'), self.assertRaisesRegex(RuntimeError, 'environment execution'): + self.play(game, 'e2e4') + result = grade(game.final, self.instance, validate_metrics) + self.assertFalse(result['result_valid']) + self.assertIsNone(result['primary_score']) + + def test_configuration_fails_closed(self): + validate_instance(self.instance) + for field, value in (('opponent_policy', 'unknown'), ('controlled_agent', 'player_1'), + ('observation_profile', 'native'), ('opponent_seed', True), ('x', 1)): + with self.subTest(field=field), self.assertRaises(ValueError): + validate_instance({**self.instance, field: value}) + metrics = {**self.instance['metric_spec'], 'reducer': 'unknown'} + with self.assertRaises(ValueError): + validate_instance({**self.instance, 'metric_spec': metrics}) + + +if __name__ == '__main__': + unittest.main() diff --git a/game_first_exam/tests/test_chess_native.py b/game_first_exam/tests/test_chess_native.py new file mode 100644 index 0000000..b1728d5 --- /dev/null +++ b/game_first_exam/tests/test_chess_native.py @@ -0,0 +1,118 @@ +"""Behavior probes for the pinned PettingZoo Chess AEC environment.""" +import hashlib +from pathlib import Path +import unittest + +import chess +import numpy as np +from pettingzoo import make +from pettingzoo.classic.chess import chess_utils + + +def legal_map(env): + actor = env.agent_selection + board = env.unwrapped.board + mask = env.observe(actor)['action_mask'] + return {chess_utils.action_to_move(board, int(i), int(actor == 'player_1')).uci(): int(i) + for i in np.flatnonzero(mask)} + + +def play(env, moves): + for move in moves.split(): + assert not any(env.terminations.values()) + assert env.step(legal_map(env)[move]) is None + + +class NativeChessTests(unittest.TestCase): + def new_env(self, **kwargs): + env = make('aec', 'classic/chess-v6', **kwargs) + self.addCleanup(env.close) + self.assertIsNone(env.reset(seed=123, options={'fen': 'ignored'})) + return env + + def test_source_and_reset_observation(self): + source = Path(chess_utils.__file__).parent + for name, expected in { + 'chess.py': '2b5c6f684951bb1b476213db88fcbebf63ed7acf0c565e288454f3174752726a', + 'chess_utils.py': 'e9a7418ab85bbbb2f5ed5cd766b5afcc7ff07a6ca110842f48465f4ec9717cc1', + }.items(): + self.assertEqual(hashlib.sha256((source / name).read_bytes()).hexdigest(), expected) + env = self.new_env(render_mode='rgb_array', screen_height=128) + self.assertFalse(env.metadata['is_parallelizable']) + self.assertEqual(env.agent_selection, 'player_0') + self.assertEqual(env.unwrapped.board.fen(), chess.STARTING_FEN) + white = env.observe('player_0') + self.assertEqual(white['observation'].shape, (8, 8, 111)) + self.assertEqual(white['observation'].dtype, np.bool_) + self.assertFalse(white['observation'][..., 7:].any()) + self.assertEqual(white['action_mask'].shape, (4672,)) + self.assertEqual(white['action_mask'].dtype, np.int8) + self.assertEqual(white['action_mask'].sum(), 20) + self.assertFalse(env.observe('player_1')['action_mask'].any()) + white_id = legal_map(env)['e2e4'] + play(env, 'e2e4') + self.assertEqual(env.agent_selection, 'player_1') + self.assertEqual(legal_map(env)['e7e5'], white_id) + white = env.observe('player_0')['observation'] + black = env.observe('player_1')['observation'] + np.testing.assert_array_equal(black[..., 7:13], white[::-1, :, 13:19]) + before = env.unwrapped.board.fen(), env.unwrapped.board_history.copy() + frame = env.render() + self.assertEqual(frame.shape, (128, 128, 3)) + self.assertEqual(frame.dtype, np.uint8) + env.observe('player_1') + self.assertEqual(env.unwrapped.board.fen(), before[0]) + np.testing.assert_array_equal(env.unwrapped.board_history, before[1]) + print(f'Native initial mask=20, e2e4/e7e5 ID={white_id}, rgb_array={frame.shape}') + + def test_special_moves_and_all_legal_ids(self): + for moves, expected in ( + ('e2e4 a7a6 e4e5 d7d5', {'e5d6'}), + ('e2e4 e7e5 g1f3 g8f6 f1c4 f8c5', {'e1g1'}), + ('a2a4 h7h5 a4a5 h5h4 a5a6 h4h3 a6b7 h3g2', + {'b7a8' + suffix for suffix in 'qrbn'}), + ): + env = self.new_env() + for move in moves.split(): + lookup = legal_map(env) + self.assertEqual(set(lookup), {m.uci() for m in env.unwrapped.board.legal_moves}) + env.step(lookup[move]) + self.assertLessEqual(expected, legal_map(env).keys()) + + def test_checkmate_draw_illegal_and_dead_steps(self): + for moves, rewards, truncated in ( + ('f2f3 e7e5 g2g4 d8h4', (-1, 1), False), + ('g1f3 g8f6 f3g1 f6g8 g1f3 g8f6 f3g1', (0, 0), False), + ('', (-1, 0), True), + ): + env = self.new_env() + if moves: + play(env, moves) + else: + with self.assertRaises(AssertionError): + env.step(4672) + self.assertFalse(any(env.terminations.values())) + env.step(0) + self.assertEqual(env.unwrapped.board.ply(), 0) + self.assertTrue(env.observe(env.agent_selection)['action_mask'].any()) + self.assertEqual(tuple(env.rewards.values()), rewards) + self.assertEqual(tuple(env.terminations.values()), (True, True)) + self.assertEqual(tuple(env.truncations.values()), (truncated, truncated)) + print(f'Native ply={env.unwrapped.board.ply()} rewards={env.rewards} truncation={truncated}') + with self.assertRaises(ValueError): + env.step(0) + env.step(None) + env.step(None) + self.assertEqual(env.agents, []) + + def test_reproducible(self): + one, two = self.new_env(), self.new_env() + for env in (one, two): + play(env, 'e2e4 c7c5 g1f3 d7d6') + for key, value in one.observe('player_0').items(): + np.testing.assert_array_equal(value, two.observe('player_0')[key]) + self.assertEqual(one.unwrapped.board.fen(), two.unwrapped.board.fen()) + + +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..ee93a02 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-", "chess-")) 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..a1ce943 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 = [ + ("chess-", "Chess", "chess"), ("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..20c28c8 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 = "^chess-.*-standard$" +main = { cpus = 1, memory_gb = 1, pids = 256, disk_gb = 2 } +sim = { cpus = 1, memory_gb = 1, pids = 128 } +measured = "Initial Chess CPU-only integration caps"