From 4d7175d02b657bd6c8defa902db8c226f12d45fd Mon Sep 17 00:00:00 2001 From: Li Yajie <263344417+lyzk907-dev@users.noreply.github.com> Date: Fri, 20 Nov 2026 20:03:05 +0800 Subject: [PATCH] Add Tetris Gymnasium adapter and validation tests --- .github/workflows/games.yml | 2 +- game_first_exam/benchmarks/tetris/README.md | 49 ++++ game_first_exam/benchmarks/tetris/SOURCE.json | 9 + game_first_exam/benchmarks/tetris/adapter.py | 146 ++++++++++ .../benchmarks/tetris/instance_schema.py | 40 +++ .../benchmarks/tetris/metric_rules.py | 25 ++ .../benchmarks/tetris/requirements.txt | 10 + .../images/tetris-files/FILES.json | 11 + game_first_exam/images/tetris-files/README.md | 3 + game_first_exam/images/tetris-files/VERSION | 1 + game_first_exam/tests/envs/locks/tetris.txt | 10 + game_first_exam/tests/envs/tetris.Dockerfile | 7 + game_first_exam/tests/run.sh | 4 + game_first_exam/tests/test_tetris_contract.py | 268 ++++++++++++++++++ game_first_exam/tests/test_tetris_native.py | 125 ++++++++ 15 files changed, 709 insertions(+), 1 deletion(-) create mode 100644 game_first_exam/benchmarks/tetris/README.md create mode 100644 game_first_exam/benchmarks/tetris/SOURCE.json create mode 100644 game_first_exam/benchmarks/tetris/adapter.py create mode 100644 game_first_exam/benchmarks/tetris/instance_schema.py create mode 100644 game_first_exam/benchmarks/tetris/metric_rules.py create mode 100644 game_first_exam/benchmarks/tetris/requirements.txt create mode 100644 game_first_exam/images/tetris-files/FILES.json create mode 100644 game_first_exam/images/tetris-files/README.md create mode 100644 game_first_exam/images/tetris-files/VERSION create mode 100644 game_first_exam/tests/envs/locks/tetris.txt create mode 100644 game_first_exam/tests/envs/tetris.Dockerfile create mode 100644 game_first_exam/tests/test_tetris_contract.py create mode 100644 game_first_exam/tests/test_tetris_native.py diff --git a/.github/workflows/games.yml b/.github/workflows/games.yml index ebee4f6..3a423fc 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, tetris] steps: - uses: actions/checkout@v4 with: {persist-credentials: false} diff --git a/game_first_exam/benchmarks/tetris/README.md b/game_first_exam/benchmarks/tetris/README.md new file mode 100644 index 0000000..201f741 --- /dev/null +++ b/game_first_exam/benchmarks/tetris/README.md @@ -0,0 +1,49 @@ +# Tetris Gymnasium native integration + +This change adds the native Tetris Gymnasium adapter, trusted schema, metric validation, files-only image and native/contract tests. Frozen Harbor tasks and a game suite are intentionally deferred. + +## Reference and compatibility + +The repository baseline is LAMDA-NeSy/Game_exam commit `7998e10f62811de00a0145ab90480a254a3fc827`. The integration uses the MIT-licensed [Max-We/Tetris-Gymnasium](https://github.com/Max-We/Tetris-Gymnasium) project and does not use an NES/Atari emulator or a ROM. + +Version 0.2.1 is pinned because the single-reset profile used here has the same `step` dynamics, actions and rewards as 0.3.1 without making the unrelated JAX functional API a simulator dependency. Version 0.3.1 also changes repeated-reset handling and RGB observation-space metadata; this adapter does not claim those paths are identical. `SOURCE.json` records the upstream tag commit and official PyPI wheel digest. + +| Area | Implementation | +|---|---| +| Execution | Harbor native agent, existing GameClient, shared runtime/server.py | +| Native backend | `gym.make("tetris_gymnasium/Tetris")`, one reset and one native step per accepted request | +| Board profile | Native 10×20 board, gravity enabled, four-piece queue, one-piece holder | +| Observation | Upstream `RgbObservation`: padded board, active piece, queue and holder; PNG transport | +| Actions | All eight native actions exposed as descriptive enum strings | +| Seeding | Native `reset(seed=...)`; seed 0 is rejected because upstream 0.2.1 treats it as unseeded | +| Reward | Native placement survival reward plus native quadratic line-clear score | +| Metrics | Total cleared lines, native return, rewarded placements and line-clear score | +| Completion | Native game-over terminates; future tasks must provide a public action cap | + +## Isolation and audit + +Only `image_png_base64` is returned in adapter observations. The image is produced by the upstream RGB wrapper and contains information normally visible in Tetris: the board, active piece, next-piece queue and held piece. Exact arrays, active coordinates, random bag contents and RNG state stay inside the simulator and are used only by `fingerprint()` for audit integrity. + +The adapter is designed for the existing standard-mode main/sim/verifier boundary. A future frozen task must keep its instance in sim/verifier, expose only the public client to main, and use a separate no-network verifier. No frozen Tetris task, target instance, solution or reference trajectory is included in this change. + +## Native semantics + +Tetris Gymnasium has no native time-limit truncation. The episode terminates when a new tetromino cannot spawn. A future frozen instance must set the shared public `max_steps` cap; reaching that cap remains a budget end rather than a native termination. + +The primary metric profile is total native lines cleared. `target_lines` supplies a binary compatibility success label without changing native dynamics or ending the episode early. The adapter preserves each native reward increment and checks the pinned placement reward formula before recording it. + +## Validation commands + +```bash +python game_first_exam/tests/test_tetris_contract.py +python game_first_exam/tests/test_tetris_native.py +``` + +The native test requires the pinned Tetris Gymnasium environment and compares direct native calls with the adapter across seeds, all actions, observations, rewards, termination and read-only methods. Contract tests use a deterministic engine double to exercise the shared service and grader without publishing a task. + +## Sources + +- https://github.com/Max-We/Tetris-Gymnasium/tree/0.2.1 +- https://max-we.github.io/Tetris-Gymnasium/environments/tetris/ +- https://max-we.github.io/Tetris-Gymnasium/utilities/wrappers/ +- https://pypi.org/project/tetris-gymnasium/0.2.1/ diff --git a/game_first_exam/benchmarks/tetris/SOURCE.json b/game_first_exam/benchmarks/tetris/SOURCE.json new file mode 100644 index 0000000..f1f09f4 --- /dev/null +++ b/game_first_exam/benchmarks/tetris/SOURCE.json @@ -0,0 +1,9 @@ +{ + "repository": "https://github.com/Max-We/Tetris-Gymnasium", + "commit": "b09ac36b55a532f030a3b71f90e2c94fb14f26b5", + "release": "0.2.1", + "distribution": "tetris_gymnasium-0.2.1-py3-none-any.whl", + "sha256": "e7a154c58cdc14abd02b3f97dbf2e3806c362d12bbfc6e18c078b7bad55c0dc6", + "license": "MIT", + "interface": "Gymnasium reset/step with the upstream RgbObservation wrapper" +} diff --git a/game_first_exam/benchmarks/tetris/adapter.py b/game_first_exam/benchmarks/tetris/adapter.py new file mode 100644 index 0000000..1162042 --- /dev/null +++ b/game_first_exam/benchmarks/tetris/adapter.py @@ -0,0 +1,146 @@ +"""Tetris Gymnasium backend using its native RGB observation wrapper.""" +import importlib.metadata +import numbers + +import gymnasium as gym +from tetris_gymnasium.envs import Tetris as _Tetris # noqa: F401 - registers the environment +from tetris_gymnasium.wrappers.observation import RgbObservation + +from contracts import Capabilities, Transition +from encoding import png, state_hash + + +ACTIONS = { + 'MOVE_LEFT': 0, + 'MOVE_RIGHT': 1, + 'MOVE_DOWN': 2, + 'ROTATE_CLOCKWISE': 3, + 'ROTATE_COUNTERCLOCKWISE': 4, + 'HARD_DROP': 5, + 'SWAP': 6, + 'NO_OP': 7, +} + + +def make_native_env(instance): + native = gym.make( + instance['env_id'], render_mode='rgb_array', + width=instance['board_width'], height=instance['board_height'], + gravity=instance['gravity'], + ) + return RgbObservation(native) + + +class Adapter: + def __init__(self, instance, assets=None): + self.instance = instance + for name, version in instance['engine_versions'].items(): + if importlib.metadata.version(name) != version: + raise ValueError('Tetris dependency version mismatch: ' + name) + self.env = make_native_env(instance) + try: + native = self.env.unwrapped + if (native.width != instance['board_width'] + or native.height != instance['board_height'] + or native.gravity_enabled is not instance['gravity'] + or native.queue.size != instance['native_queue_size'] + or native.holder.size != instance['native_holder_size']): + raise ValueError('native Tetris profile mismatch') + image, _ = self.env.reset(seed=instance['seed']) + expected_shape = (native.height_padded, + native.width_padded + native.queue.size * native.padding, 3) + if image.shape != expected_shape or str(image.dtype) != 'uint8': + raise ValueError('native Tetris RGB observation changed') + self.image = image.copy() + except Exception: + self.env.close() + raise + self.total_return = 0.0 + self.lines_cleared = 0 + self.rewarded_placements = 0 + self.line_clear_score = 0 + self.ended = False + + def spec(self): + return { + 'adapter_version': '1.0.0', + 'capabilities': Capabilities(images=True, action_mode='enum').to_dict(), + 'action_schema': {'type': 'string', 'enum': list(ACTIONS)}, + 'action_indices': dict(ACTIONS), + 'observation': ('Native RGB observation containing the padded board, active piece, ' + 'four-piece preview queue and one-piece holder; PNG transport only.'), + 'goal': 'Clear lines and keep the native Tetris episode alive.', + } + + def observe(self): + return {'image_png_base64': png(self.image)} + + def step(self, action): + if self.ended: + raise ValueError('episode closed') + if action not in ACTIONS: + raise ValueError('unknown Tetris action') + image, reward, terminated, truncated, info = self.env.step(ACTIONS[action]) + reward = float(reward) + lines = info.get('lines_cleared') + if isinstance(lines, bool) or not isinstance(lines, numbers.Integral): + raise ValueError('invalid native line-clear count') + lines = int(lines) + if not 0 <= lines <= 4: + raise ValueError('invalid native line-clear count') + if terminated: + if reward != 0: + raise ValueError('native game-over reward changed') + elif reward: + expected = 1 + (lines ** 2) * self.instance['board_width'] + if reward != expected: + raise ValueError('native placement reward changed') + self.rewarded_placements += 1 + self.line_clear_score += (lines ** 2) * self.instance['board_width'] + self.image = image.copy() + self.total_return += reward + self.lines_cleared += lines + self.ended = bool(terminated or truncated) + return Transition(reward, bool(terminated), bool(truncated)) + + def success(self): + return self.lines_cleared >= self.instance['target_lines'] + + def metrics(self): + return { + 'success': int(self.success()), + 'lines_cleared': self.lines_cleared, + 'native_return': self.total_return, + 'rewarded_placements': self.rewarded_placements, + 'line_clear_score': self.line_clear_score, + } + + def fingerprint(self): + native = self.env.unwrapped + randomizer = native.randomizer + holder = [{'id': piece.id, 'matrix': piece.matrix} + for piece in native.holder.queue] + return state_hash({ + 'board': native.board, + 'active': {'id': native.active_tetromino.id, + 'matrix': native.active_tetromino.matrix}, + 'position': [native.x, native.y], + 'queue': list(native.queue.queue), + 'holder': holder, + 'bag': randomizer.bag, + 'bag_index': randomizer.index, + 'rng': randomizer.rng.bit_generator.state, + 'has_swapped': native.has_swapped, + 'game_over': native.game_over, + 'return': self.total_return, + 'lines_cleared': self.lines_cleared, + 'rewarded_placements': self.rewarded_placements, + 'line_clear_score': self.line_clear_score, + 'image': self.image, + }) + + def frame(self): + return self.image.copy() + + def close(self): + self.env.close() diff --git a/game_first_exam/benchmarks/tetris/instance_schema.py b/game_first_exam/benchmarks/tetris/instance_schema.py new file mode 100644 index 0000000..be574f6 --- /dev/null +++ b/game_first_exam/benchmarks/tetris/instance_schema.py @@ -0,0 +1,40 @@ +"""Trusted stdlib-only schema for the native Tetris Gymnasium profile.""" +from config_schema import validate_engine_versions + +SCHEMA_VERSION = '1.0.0' +BENCHMARK = 'tetris' +FIELDS = {'engine_versions', 'board_width', 'board_height', 'gravity', + 'native_queue_size', 'native_holder_size', 'target_lines'} +METRICS = {'success', 'lines_cleared', 'native_return', 'rewarded_placements', 'line_clear_score'} +PROFILES = {'native-rgb-board-queue-holder-v1'} +REDUCERS = {('family_macro', '1.0.0')} +ENGINE_VERSIONS = { + 'tetris-gymnasium': '0.2.1', + 'gymnasium': '1.4.0', + 'numpy': '1.26.4', + 'opencv-python': '4.10.0.84', +} + + +def validate(value): + validate_engine_versions(value['engine_versions'], ENGINE_VERSIONS) + if value['env_id'] != 'tetris_gymnasium/Tetris' or value['family'] != 'tetris-classic': + raise ValueError('unsupported Tetris environment/family') + if value['seed'] < 1: + # Upstream 0.2.1 treats seed=0 as an unseeded reset. + raise ValueError('Tetris seed must be positive') + if (value['board_width'], value['board_height'], value['gravity']) != (10, 20, True): + raise ValueError('unsupported Tetris board or gravity profile') + if (value['native_queue_size'], value['native_holder_size']) != (4, 1): + raise ValueError('unsupported native queue/holder profile') + if type(value['target_lines']) is not int or not 1 <= value['target_lines'] <= 1000: + raise ValueError('target_lines must be an integer in [1, 1000]') + if value['max_steps'] is None: + raise ValueError('Tetris requires a public action cap') + if value['capabilities'] != {'images': True, 'action_mode': 'enum', + 'timing': 'action-stepped', 'native_truncation': False}: + raise ValueError('unsupported Tetris capabilities') + if value['metric_spec'] != {'primary': 'lines_cleared', 'reducer': 'family_macro', + 'reducer_version': '1.0.0', + 'success_label': 'target_lines_reached'}: + raise ValueError('unsupported Tetris scoring profile') diff --git a/game_first_exam/benchmarks/tetris/metric_rules.py b/game_first_exam/benchmarks/tetris/metric_rules.py new file mode 100644 index 0000000..4d9137e --- /dev/null +++ b/game_first_exam/benchmarks/tetris/metric_rules.py @@ -0,0 +1,25 @@ +"""Validate native Tetris line and reward accounting.""" + + +def validate_metrics(final, instance): + metrics = final['metrics'] + expected = {'success', 'lines_cleared', 'native_return', + 'rewarded_placements', 'line_clear_score'} + if set(metrics) != expected: + raise ValueError('wrong Tetris metric fields') + for key in ('success', 'lines_cleared', 'rewarded_placements', 'line_clear_score'): + if type(metrics[key]) is not int or metrics[key] < 0: + raise ValueError('invalid Tetris integer metric: ' + key) + if metrics['success'] not in (0, 1): + raise ValueError('invalid Tetris success metric') + if metrics['native_return'] != final['return']: + raise ValueError('inconsistent native Tetris return') + if metrics['native_return'] != metrics['rewarded_placements'] + metrics['line_clear_score']: + raise ValueError('inconsistent native Tetris reward accounting') + success = metrics['lines_cleared'] >= instance['target_lines'] + if metrics['success'] != int(success) or final['success'] != (success and not final['sim_error']): + raise ValueError('inconsistent Tetris target success') + if final['steps'] == 0 and any(metrics[key] for key in expected): + raise ValueError('Tetris metrics without an action') + if final['truncated']: + raise ValueError('Tetris declared no native truncation') diff --git a/game_first_exam/benchmarks/tetris/requirements.txt b/game_first_exam/benchmarks/tetris/requirements.txt new file mode 100644 index 0000000..04441a0 --- /dev/null +++ b/game_first_exam/benchmarks/tetris/requirements.txt @@ -0,0 +1,10 @@ +cloudpickle==3.1.2 +Farama-Notifications==0.0.6 +gymnasium==1.4.0 +ImageIO==2.38.1 +imageio-ffmpeg==0.8.1 +numpy==1.26.4 +opencv-python==4.10.0.84 +pillow==13.0.0 +tetris-gymnasium==0.2.1 +typing_extensions==4.16.0 diff --git a/game_first_exam/images/tetris-files/FILES.json b/game_first_exam/images/tetris-files/FILES.json new file mode 100644 index 0000000..365b854 --- /dev/null +++ b/game_first_exam/images/tetris-files/FILES.json @@ -0,0 +1,11 @@ +{ + "image": "ghcr.io/mll-lab-nu/efe:tetris-files-0.1.0@sha256:77fd0a3da6746150941ed2072e84555df5ed1c31de7f69afabf36b07218b97ab", + "source": "game_first_exam/benchmarks/tetris", + "files": { + "adapter.py": "69f08c46195cd9e4db7b79ef141043b16956ee55439dc911c241d9ab80537320", + "instance_schema.py": "a46eacce97d460192e39b180ce8d99e5314dd12966f5aa9dca4f2117cc2c3045", + "metric_rules.py": "293c46e15b53ef8eb37ac7b7ea5585f25f6041ac08a46c08ee62544dae29e666", + "requirements.txt": "f7382c7e150ec033919edc7e3f0774f384cc156b764bbda6917a8a768623bb6c", + "SOURCE.json": "2d1d227563329fae4018a96d586398c6c98704e2e8674b8a3458f4a82919bcff" + } +} diff --git a/game_first_exam/images/tetris-files/README.md b/game_first_exam/images/tetris-files/README.md new file mode 100644 index 0000000..ebd943e --- /dev/null +++ b/game_first_exam/images/tetris-files/README.md @@ -0,0 +1,3 @@ +# Tetris files-only image + +Built locally by scripts/files_image.py from the pinned Tetris Gymnasium adapter sources. diff --git a/game_first_exam/images/tetris-files/VERSION b/game_first_exam/images/tetris-files/VERSION new file mode 100644 index 0000000..6e8bf73 --- /dev/null +++ b/game_first_exam/images/tetris-files/VERSION @@ -0,0 +1 @@ +0.1.0 diff --git a/game_first_exam/tests/envs/locks/tetris.txt b/game_first_exam/tests/envs/locks/tetris.txt new file mode 100644 index 0000000..04441a0 --- /dev/null +++ b/game_first_exam/tests/envs/locks/tetris.txt @@ -0,0 +1,10 @@ +cloudpickle==3.1.2 +Farama-Notifications==0.0.6 +gymnasium==1.4.0 +ImageIO==2.38.1 +imageio-ffmpeg==0.8.1 +numpy==1.26.4 +opencv-python==4.10.0.84 +pillow==13.0.0 +tetris-gymnasium==0.2.1 +typing_extensions==4.16.0 diff --git a/game_first_exam/tests/envs/tetris.Dockerfile b/game_first_exam/tests/envs/tetris.Dockerfile new file mode 100644 index 0000000..8b4855a --- /dev/null +++ b/game_first_exam/tests/envs/tetris.Dockerfile @@ -0,0 +1,7 @@ +FROM docker.io/library/python:3.12.10-slim-bookworm@sha256:fd95fa221297a88e1cf49c55ec1828edd7c5a428187e67b5d1805692d11588db +ENV PYTHONUNBUFFERED=1 +RUN apt-get update && apt-get install -y --no-install-recommends libglib2.0-0 libgl1 ca-certificates && rm -rf /var/lib/apt/lists/* +COPY game_first_exam/tests/envs/locks/tetris.txt /requirements.txt +RUN pip install --no-cache-dir --no-deps -r /requirements.txt +RUN pip check +WORKDIR /repo diff --git a/game_first_exam/tests/run.sh b/game_first_exam/tests/run.sh index a033e85..b0bde08 100755 --- a/game_first_exam/tests/run.sh +++ b/game_first_exam/tests/run.sh @@ -19,6 +19,10 @@ case "${1:-common}" in python3 game_first_exam/tests/test_minihack.py python3 game_first_exam/tests/test_game_modes_native.py ;; + tetris) + python3 game_first_exam/tests/test_tetris_native.py + python3 game_first_exam/tests/test_tetris_contract.py + ;; minigrid|crafter|textworld|babaisai) export GAME_TEST_BENCHMARK="$1" python3 game_first_exam/tests/test_game_adapters.py diff --git a/game_first_exam/tests/test_tetris_contract.py b/game_first_exam/tests/test_tetris_contract.py new file mode 100644 index 0000000..38c77df --- /dev/null +++ b/game_first_exam/tests/test_tetris_contract.py @@ -0,0 +1,268 @@ +"""Tetris adapter/service regressions with a deterministic engine double.""" +import base64 +import copy +import importlib.util +import io +import sys +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +import numpy as np +from PIL import Image + +ROOT = Path(__file__).resolve().parents[2] +sys.path[:0] = [str(ROOT / 'game_first_exam/runtime')] +from config_schema import register_instance_schema, validate_instance +from grade import grade +from server import Game + + +def load(name, filename): + spec = importlib.util.spec_from_file_location( + name, ROOT / 'game_first_exam/benchmarks/tetris' / filename) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +backend = load('tetris_adapter_test', 'adapter.py') +schema = register_instance_schema(load('tetris_schema_test', 'instance_schema.py')) +rules = load('tetris_rules_test', 'metric_rules.py') + + +class Piece: + def __init__(self, piece_id): + self.id = piece_id + self.matrix = np.full((2, 2), piece_id, dtype=np.uint8) + + +class Queue: + size = 4 + + def __init__(self): + self.queue = [1, 2, 3, 4] + + +class Holder: + size = 1 + + def __init__(self): + self.queue = [] + + +class Randomizer: + def __init__(self): + self.bag = np.arange(7, dtype=np.int8) + self.index = 4 + self.rng = np.random.default_rng(1) + + +class Engine: + """Small native-shaped engine: line clear on step two, game over on step three.""" + width = 10 + height = 20 + gravity_enabled = True + padding = 4 + width_padded = 18 + height_padded = 24 + + def __init__(self): + self.unwrapped = self + self.queue = Queue() + self.holder = Holder() + self.randomizer = Randomizer() + self.active_tetromino = Piece(2) + self.board = np.zeros((24, 18), dtype=np.uint8) + self.x, self.y = 8, 0 + self.has_swapped = False + self.game_over = False + self.actions = [] + self.reset_count = 0 + self.closed = False + self.image = np.zeros((24, 34, 3), dtype=np.uint8) + + def reset(self, seed=None): + self.reset_count += 1 + self.randomizer.rng = np.random.default_rng(seed) + self.image.fill(seed % 255) + return self.image.copy(), {'lines_cleared': 0} + + def step(self, action): + self.actions.append(action) + self.x += 1 + self.board[0, len(self.actions)] = action + 2 + lines = 1 if len(self.actions) == 2 else 0 + terminated = len(self.actions) == 3 + reward = 0 if terminated else (11 if lines else 0) + self.game_over = terminated + self.image.fill(200 if terminated else len(self.actions)) + return self.image.copy(), reward, terminated, False, {'lines_cleared': lines} + + def close(self): + self.closed = True + + +def instance(): + return { + 'schema_version': 'game-instance/2.2', 'protocol': 'game-standard/2.2', + 'adapter_version': '1.0.0', 'benchmark': 'tetris', + 'env_id': 'tetris_gymnasium/Tetris', 'family': 'tetris-classic', + 'seed': 42, 'max_steps': 1000, 'initial_state_sha256': '0' * 64, + 'observation_profile': 'native-rgb-board-queue-holder-v1', + 'capabilities': {'images': True, 'action_mode': 'enum', + 'timing': 'action-stepped', 'native_truncation': False}, + 'engine_versions': dict(schema.ENGINE_VERSIONS), + 'board_width': 10, 'board_height': 20, 'gravity': True, + 'native_queue_size': 4, 'native_holder_size': 1, 'target_lines': 1, + 'metric_spec': {'primary': 'lines_cleared', 'reducer': 'family_macro', + 'reducer_version': '1.0.0', + 'success_label': 'target_lines_reached'}, + } + + +class TetrisContractTests(unittest.TestCase): + def setUp(self): + self.factory = patch.object(backend, 'make_native_env', side_effect=lambda _: Engine()) + self.factory.start() + self.addCleanup(self.factory.stop) + self.versions = patch.object(backend.importlib.metadata, 'version', + side_effect=schema.ENGINE_VERSIONS.__getitem__) + self.versions.start() + self.addCleanup(self.versions.stop) + + def adapter(self): + adapter = backend.Adapter(instance()) + self.addCleanup(adapter.close) + return adapter + + def test_runtime_and_test_dependency_locks_match(self): + runtime = ROOT / 'game_first_exam/benchmarks/tetris/requirements.txt' + lock = ROOT / 'game_first_exam/tests/envs/locks/tetris.txt' + self.assertEqual(runtime.read_text(), lock.read_text()) + + def test_native_profile_and_all_eight_actions(self): + adapter = self.adapter() + self.assertEqual(adapter.env.reset_count, 1) + self.assertEqual(adapter.frame().shape, (24, 34, 3)) + for name, index in backend.ACTIONS.items(): + with self.subTest(action=name): + other = self.adapter() + other.step(name) + self.assertEqual(other.env.actions, [index]) + + def test_public_observation_is_only_cached_rgb(self): + adapter = self.adapter() + before = adapter.fingerprint() + for _ in range(3): + observation = adapter.observe() + self.assertEqual(set(observation), {'image_png_base64'}) + decoded = np.asarray(Image.open(io.BytesIO( + base64.b64decode(observation['image_png_base64'])))) + np.testing.assert_array_equal(decoded, adapter.frame()) + adapter.spec() + adapter.metrics() + self.assertEqual(adapter.fingerprint(), before) + changed = adapter.frame() + changed.fill(255) + self.assertEqual(adapter.fingerprint(), before) + + def test_public_service_excludes_privileged_native_state(self): + adapter = self.adapter() + config = instance() + config['initial_state_sha256'] = adapter.fingerprint() + with tempfile.TemporaryDirectory() as directory: + game = Game(adapter, config, directory) + try: + public = [game.spec(), game.observe(), game.submit({ + 'action': 'NO_OP', 'expected_step': 0, 'request_id': 'isolation-audit'})] + forbidden = {'seed', 'target_lines', 'engine_versions', 'board', 'rng', 'bag', + 'fingerprint', 'metrics', 'native_return', 'lines_cleared', + 'initial_state_sha256'} + + def keys(value): + if isinstance(value, dict): + nested = set().union(*(keys(item) for item in value.values()), set()) + return set(value) | nested + if isinstance(value, list): + return set().union(*(keys(item) for item in value), set()) + return set() + + self.assertFalse(forbidden & set().union(*(keys(item) for item in public))) + self.assertEqual(set(public[1]['observation']), {'image_png_base64'}) + self.assertEqual(set(public[2]['observation']), {'image_png_base64'}) + finally: + game.close() + + def test_line_reward_target_and_native_game_over(self): + adapter = self.adapter() + self.assertEqual(adapter.step('MOVE_LEFT').reward, 0) + transition = adapter.step('HARD_DROP') + self.assertEqual(transition.reward, 11) + self.assertTrue(adapter.success()) + self.assertEqual(adapter.metrics(), { + 'success': 1, 'lines_cleared': 1, 'native_return': 11.0, + 'rewarded_placements': 1, 'line_clear_score': 10, + }) + transition = adapter.step('NO_OP') + self.assertTrue(transition.terminated) + self.assertFalse(transition.truncated) + with self.assertRaisesRegex(ValueError, 'episode closed'): + adapter.step('NO_OP') + + def test_invalid_action_does_not_advance(self): + adapter = self.adapter() + with self.assertRaisesRegex(ValueError, 'unknown Tetris action'): + adapter.step('RESET') + self.assertEqual(adapter.env.actions, []) + + def test_shared_service_deduplicates_seals_and_grades(self): + adapter = self.adapter() + config = instance() + config['initial_state_sha256'] = adapter.fingerprint() + with tempfile.TemporaryDirectory() as directory: + game = Game(adapter, config, directory) + try: + first = {'action': 'MOVE_LEFT', 'expected_step': 0, 'request_id': 'one'} + response = game.submit(first) + self.assertEqual(game.submit(first), response) + game.submit({'action': 'HARD_DROP', 'expected_step': 1, 'request_id': 'two'}) + game.submit({'action': 'NO_OP', 'expected_step': 2, 'request_id': 'three'}) + self.assertTrue(game.observe()['done']) + self.assertEqual(len(adapter.env.actions), 3) + result = grade(game.final, config, rules.validate_metrics) + self.assertEqual((result['primary_score'], result['success']), (1, 1)) + corrupted = copy.deepcopy(game.final) + corrupted['metrics']['lines_cleared'] = 0 + with self.assertRaises(ValueError): + grade(corrupted, config, rules.validate_metrics) + finally: + game.close() + + def test_schema_rejects_profile_drift(self): + validate_instance(instance()) + for key, value in [('seed', 0), ('board_width', 12), ('gravity', False), + ('native_queue_size', 5), ('max_steps', None), + ('target_lines', 0), ('unknown', True)]: + config = instance() + config[key] = value + with self.subTest(key=key), self.assertRaises((ValueError, TypeError)): + validate_instance(config) + + def test_zero_action_finish_is_valid_failure(self): + adapter = self.adapter() + config = instance() + config['initial_state_sha256'] = adapter.fingerprint() + with tempfile.TemporaryDirectory() as directory: + game = Game(adapter, config, directory) + try: + game.finalize('agent_finished') + result = grade(game.final, config, rules.validate_metrics) + self.assertEqual((result['primary_score'], result['success']), (0, 0)) + finally: + game.close() + + +if __name__ == '__main__': + unittest.main() diff --git a/game_first_exam/tests/test_tetris_native.py b/game_first_exam/tests/test_tetris_native.py new file mode 100644 index 0000000..5f004b0 --- /dev/null +++ b/game_first_exam/tests/test_tetris_native.py @@ -0,0 +1,125 @@ +"""Compare the adapter against real Tetris Gymnasium native calls.""" +import importlib.util +import sys +import unittest +from pathlib import Path + +import gymnasium as gym +import numpy as np +from tetris_gymnasium.envs import Tetris as _Tetris # noqa: F401 - registration +from tetris_gymnasium.wrappers.observation import RgbObservation + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / 'game_first_exam/runtime')) +spec = importlib.util.spec_from_file_location( + 'tetris_native_backend', ROOT / 'game_first_exam/benchmarks/tetris/adapter.py') +backend = importlib.util.module_from_spec(spec) +spec.loader.exec_module(backend) + + +def config(seed=42): + return { + 'engine_versions': {'tetris-gymnasium': '0.2.1', 'gymnasium': '1.4.0', + 'numpy': '1.26.4', 'opencv-python': '4.10.0.84'}, + 'env_id': 'tetris_gymnasium/Tetris', 'seed': seed, + 'board_width': 10, 'board_height': 20, 'gravity': True, + 'native_queue_size': 4, 'native_holder_size': 1, 'target_lines': 1, + } + + +def native_env(cfg): + env = gym.make(cfg['env_id'], render_mode='rgb_array', width=cfg['board_width'], + height=cfg['board_height'], gravity=cfg['gravity']) + return RgbObservation(env) + + +def native_state(env): + native = env.unwrapped + return { + 'board': native.board.copy(), 'active': native.active_tetromino.matrix.copy(), + 'active_id': native.active_tetromino.id, 'x': native.x, 'y': native.y, + 'queue': list(native.queue.queue), + 'holder': [piece.id for piece in native.holder.queue], + 'bag': native.randomizer.bag.copy(), 'bag_index': native.randomizer.index, + 'rng': native.randomizer.rng.bit_generator.state, + 'has_swapped': native.has_swapped, 'game_over': native.game_over, + } + + +class TetrisNativeTests(unittest.TestCase): + def assert_state_equal(self, left, right): + for key in ('board', 'active', 'bag'): + np.testing.assert_array_equal(left.pop(key), right.pop(key)) + self.assertEqual(left, right) + + def test_all_actions_match_native_indices(self): + cfg = config() + for name, index in backend.ACTIONS.items(): + with self.subTest(action=name): + adapter = backend.Adapter(cfg) + raw = native_env(cfg) + try: + observation, _ = raw.reset(seed=cfg['seed']) + np.testing.assert_array_equal(adapter.frame(), observation) + observation, reward, terminated, truncated, info = raw.step(index) + transition = adapter.step(name) + self.assertEqual((transition.reward, transition.terminated, + transition.truncated), + (float(reward), bool(terminated), bool(truncated))) + np.testing.assert_array_equal(adapter.frame(), observation) + self.assert_state_equal(native_state(adapter.env), native_state(raw)) + self.assertEqual(adapter.metrics()['lines_cleared'], info['lines_cleared']) + finally: + adapter.close() + raw.close() + + def test_seeded_trajectory_observation_reward_and_end_match(self): + sequence = ['MOVE_LEFT', 'ROTATE_CLOCKWISE', 'MOVE_RIGHT', 'HARD_DROP', + 'SWAP', 'MOVE_DOWN', 'ROTATE_COUNTERCLOCKWISE', 'HARD_DROP'] + for seed in (1, 42, 123): + with self.subTest(seed=seed): + cfg = config(seed) + adapter = backend.Adapter(cfg) + raw = native_env(cfg) + total_lines = 0 + try: + observation, _ = raw.reset(seed=seed) + np.testing.assert_array_equal(adapter.frame(), observation) + initial = adapter.fingerprint() + adapter.spec(); adapter.observe(); adapter.metrics(); adapter.frame() + self.assertEqual(adapter.fingerprint(), initial) + for step in range(300): + name = sequence[step % len(sequence)] + observation, reward, terminated, truncated, info = raw.step( + backend.ACTIONS[name]) + transition = adapter.step(name) + total_lines += info['lines_cleared'] + self.assertEqual((transition.reward, transition.terminated, + transition.truncated), + (float(reward), bool(terminated), bool(truncated))) + np.testing.assert_array_equal(adapter.frame(), observation) + self.assert_state_equal(native_state(adapter.env), native_state(raw)) + self.assertEqual(adapter.metrics()['lines_cleared'], total_lines) + if terminated or truncated: + self.assertTrue(terminated) + self.assertFalse(truncated) + break + else: + self.fail('native Tetris episode did not end within 300 actions') + finally: + adapter.close() + raw.close() + + def test_positive_seeds_are_reproducible(self): + first = backend.Adapter(config(42)) + second = backend.Adapter(config(42)) + other = backend.Adapter(config(43)) + try: + self.assertEqual(first.fingerprint(), second.fingerprint()) + self.assertNotEqual(first.fingerprint(), other.fingerprint()) + finally: + first.close(); second.close(); other.close() + + +if __name__ == '__main__': + unittest.main()