diff --git a/game_first_exam/benchmarks/game2048/README.md b/game_first_exam/benchmarks/game2048/README.md new file mode 100644 index 0000000..3efa54f --- /dev/null +++ b/game_first_exam/benchmarks/game2048/README.md @@ -0,0 +1,35 @@ +# Gymnasium 2048 native integration + +This directory adds a thin adapter, trusted schema, metric validation and source provenance for the MIT-licensed +[`gymnasium-2048`](https://github.com/Quentin18/gymnasium-2048) environment. Frozen Harbor tasks, a game suite and +benchmark registration are intentionally deferred. + +## Frozen native profile + +| Area | Implementation | +|---|---| +| Upstream | `gymnasium-2048==0.1.2`, tag `v0.1.2`, commit recorded in `SOURCE.json` | +| Environment | `gymnasium_2048/TwentyFortyEight-v0`, native 4x4 board and 16 one-hot exponent channels | +| Observation | Native 400x460 RGB rendering of the board and cumulative score, transported as PNG | +| Actions | All four native actions: up, right, down and left | +| Randomness | Native `reset(seed=...)`; legal moves spawn a 2 tile with probability 0.9 or a 4 tile with probability 0.1 | +| Reward | Native merge score increment; cumulative native reward is the standard 2048 score | +| End | Native termination only when no legal move remains; future tasks must also set a public action cap | +| Metrics | Native score, maximum tile, valid/invalid moves and a non-terminating 2048-tile success label | + +## Isolation + +Only `image_png_base64` is returned to the agent. The upstream one-hot observation and `info` object are deliberately +not forwarded because `info["board"]` contains the exact internal board. The board exponent array, RNG state, native +score, move legality and counters remain in the simulator and contribute to `fingerprint()` for audit integrity. +Rendering is cached after reset and every accepted action, so `observe()`, `spec()`, `metrics()` and `frame()` are +read-only and cannot advance RNG. + +No task, solution, reference trajectory or container stack is included. A later task PR must separately verify the +main/simulator/verifier mounts, agent network policy and a no-network verifier before the benchmark is registered. + +## Validation + +`test_game2048_contract.py` exercises the shared service, schema, metric validator and public isolation with a +deterministic native-shaped engine double. `test_game2048_native.py` compares the adapter to direct calls into the +pinned upstream environment across seeds, every action, trajectories, rewards, RGB frames and internal state. diff --git a/game_first_exam/benchmarks/game2048/SOURCE.json b/game_first_exam/benchmarks/game2048/SOURCE.json new file mode 100644 index 0000000..8e4585c --- /dev/null +++ b/game_first_exam/benchmarks/game2048/SOURCE.json @@ -0,0 +1,10 @@ +{ + "project": "gymnasium-2048", + "repository": "https://github.com/Quentin18/gymnasium-2048", + "tag": "v0.1.2", + "commit": "b686d2a82a347066ffa8a82f6f4f57ac44deb5dc", + "license": "MIT", + "pypi": "https://pypi.org/project/gymnasium-2048/0.1.2/", + "wheel": "gymnasium_2048-0.1.2-py3-none-any.whl", + "wheel_sha256": "d906d6757a06553c80709e4a4aa06d47ee6ad053e9506f6ce5c6c63d3e3d8688" +} diff --git a/game_first_exam/benchmarks/game2048/adapter.py b/game_first_exam/benchmarks/game2048/adapter.py new file mode 100644 index 0000000..551126e --- /dev/null +++ b/game_first_exam/benchmarks/game2048/adapter.py @@ -0,0 +1,151 @@ +"""Gymnasium 2048 backend with native RGB rendering and scoring.""" +import importlib.metadata +import numbers + +import gymnasium as gym +import gymnasium_2048 # noqa: F401 - registers the environment +import numpy as np + +from contracts import Capabilities, Transition +from encoding import png, state_hash + + +ACTIONS = {'UP': 0, 'RIGHT': 1, 'DOWN': 2, 'LEFT': 3} +INFO_FIELDS = {'board', 'step_score', 'total_score', 'max', 'is_legal', 'illegal_count'} + + +def make_native_env(instance): + return gym.make( + instance['env_id'], render_mode='rgb_array', + size=instance['board_size'], max_pow=instance['native_max_power'], + ) + + +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('2048 dependency version mismatch: ' + name) + self.env = make_native_env(instance) + try: + native = self.env.unwrapped + if (native.action_space.n != 4 + or native.observation_space.shape != ( + instance['board_size'], instance['board_size'], + instance['native_max_power'])): + raise ValueError('native 2048 spaces changed') + observation, info = self.env.reset(seed=instance['seed']) + self._validate_native(observation, info, initial=True) + self.image = self._render() + except Exception: + self.env.close() + raise + self.steps = 0 + self.total_return = 0.0 + self.ended = False + + def _validate_native(self, observation, info, initial=False): + native = self.env.unwrapped + size = self.instance['board_size'] + if (not isinstance(observation, np.ndarray) + or observation.shape != (size, size, self.instance['native_max_power']) + or observation.dtype != np.uint8 + or not np.all(observation.sum(axis=2) == 1) + or not np.array_equal(np.argmax(observation, axis=2), native.board)): + raise ValueError('native 2048 observation changed') + if set(info) != INFO_FIELDS or not np.array_equal(info['board'], native.board): + raise ValueError('native 2048 info changed') + scalar_fields = ('step_score', 'total_score', 'max', 'illegal_count') + if any(isinstance(info[key], bool) or not isinstance(info[key], numbers.Integral) + for key in scalar_fields) or not isinstance(info['is_legal'], bool): + raise ValueError('native 2048 info types changed') + if (int(info['total_score']) != int(native.total_score) + or int(info['step_score']) != int(native.step_score) + or int(info['max']) != int(native.board.max()) + or int(info['illegal_count']) != int(native.illegal_count) + or info['is_legal'] is not native.is_legal): + raise ValueError('native 2048 info disagrees with engine state') + if initial and ((native.board != 0).sum() != 2 + or native.total_score != 0 or native.illegal_count != 0): + raise ValueError('native 2048 initial state changed') + + def _render(self): + image = self.env.render() + if (not isinstance(image, np.ndarray) + or list(image.shape) != self.instance['native_render_shape'] + or image.dtype != np.uint8): + raise ValueError('native 2048 RGB rendering changed') + return image.copy() + + 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 rendering of the 4x4 board and cumulative score; ' + 'PNG transport only.'), + 'goal': 'Maximize the native merge score and build the largest possible tile.', + } + + 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 2048 action') + observation, reward, terminated, truncated, info = self.env.step(ACTIONS[action]) + if isinstance(reward, bool) or not isinstance(reward, numbers.Integral) or reward < 0: + raise ValueError('native 2048 reward changed') + if truncated: + raise ValueError('unexpected native 2048 truncation') + self._validate_native(observation, info) + reward = int(reward) + if reward != int(info['step_score']): + raise ValueError('native 2048 reward disagrees with step score') + self.steps += 1 + self.total_return += reward + if self.total_return != int(info['total_score']): + raise ValueError('native 2048 cumulative score changed') + self.image = self._render() + self.ended = bool(terminated) + return Transition(float(reward), bool(terminated), False) + + def success(self): + return int(self.env.unwrapped.board.max()) >= self.instance['target_power'] + + def metrics(self): + native = self.env.unwrapped + maximum = int(native.board.max()) + invalid = int(native.illegal_count) + return { + 'target_reached': int(self.success()), + 'native_score': int(native.total_score), + 'max_tile': 2 ** maximum, + 'valid_moves': self.steps - invalid, + 'invalid_moves': invalid, + 'native_return': self.total_return, + } + + def fingerprint(self): + native = self.env.unwrapped + return state_hash({ + 'board': native.board, + 'rng': native.np_random.bit_generator.state, + 'step_score': native.step_score, + 'total_score': native.total_score, + 'is_legal': native.is_legal, + 'illegal_count': native.illegal_count, + 'steps': self.steps, + 'return': self.total_return, + 'ended': self.ended, + }) + + def frame(self): + return self.image.copy() + + def close(self): + self.env.close() diff --git a/game_first_exam/benchmarks/game2048/instance_schema.py b/game_first_exam/benchmarks/game2048/instance_schema.py new file mode 100644 index 0000000..67e1c1d --- /dev/null +++ b/game_first_exam/benchmarks/game2048/instance_schema.py @@ -0,0 +1,39 @@ +"""Trusted stdlib-only schema for the native Gymnasium 2048 profile.""" +from config_schema import validate_engine_versions + +SCHEMA_VERSION = '1.0.0' +BENCHMARK = 'game2048' +FIELDS = {'engine_versions', 'board_size', 'native_max_power', + 'native_render_shape', 'target_power'} +METRICS = {'target_reached', 'native_score', 'max_tile', 'valid_moves', + 'invalid_moves', 'native_return'} +PROFILES = {'native-rgb-board-score-v1'} +REDUCERS = {('family_macro', '1.0.0')} +ENGINE_VERSIONS = { + 'gymnasium-2048': '0.1.2', + 'gymnasium': '1.3.0', + 'numpy': '1.26.4', + 'pygame': '2.6.1', +} + + +def validate(value): + validate_engine_versions(value['engine_versions'], ENGINE_VERSIONS) + if (value['env_id'] != 'gymnasium_2048/TwentyFortyEight-v0' + or value['family'] != '2048-classic'): + raise ValueError('unsupported 2048 environment/family') + if value['board_size'] != 4 or value['native_max_power'] != 16: + raise ValueError('unsupported native 2048 board profile') + if value['native_render_shape'] != [460, 400, 3]: + raise ValueError('unsupported native 2048 render profile') + if value['target_power'] != 11: + raise ValueError('the supported target is the native 2048 tile') + if type(value['max_steps']) is not int or not 1 <= value['max_steps'] <= 10000: + raise ValueError('2048 requires a public action cap in [1, 10000]') + if value['capabilities'] != {'images': True, 'action_mode': 'enum', + 'timing': 'action-stepped', 'native_truncation': False}: + raise ValueError('unsupported 2048 capabilities') + if value['metric_spec'] != {'primary': 'native_score', 'reducer': 'family_macro', + 'reducer_version': '1.0.0', + 'success_label': '2048_tile_reached'}: + raise ValueError('unsupported 2048 scoring profile') diff --git a/game_first_exam/benchmarks/game2048/metric_rules.py b/game_first_exam/benchmarks/game2048/metric_rules.py new file mode 100644 index 0000000..75ffe3b --- /dev/null +++ b/game_first_exam/benchmarks/game2048/metric_rules.py @@ -0,0 +1,35 @@ +"""Validate native 2048 score, tile and move-count relationships.""" +import math + + +def validate_metrics(final, instance): + metrics = final['metrics'] + expected = {'target_reached', 'native_score', 'max_tile', 'valid_moves', + 'invalid_moves', 'native_return'} + if set(metrics) != expected: + raise ValueError('wrong 2048 metric fields') + for key in ('target_reached', 'native_score', 'max_tile', + 'valid_moves', 'invalid_moves'): + if type(metrics[key]) is not int: + raise ValueError('2048 integer metric has wrong type: ' + key) + score, maximum = metrics['native_score'], metrics['max_tile'] + valid, invalid = metrics['valid_moves'], metrics['invalid_moves'] + if score < 0 or score % 4 or valid < 0 or invalid < 0: + raise ValueError('invalid 2048 score or move count') + if (maximum < 2 or maximum > 2 ** (instance['native_max_power'] - 1) + or maximum & (maximum - 1)): + raise ValueError('invalid 2048 maximum tile') + if valid + invalid != final['steps']: + raise ValueError('2048 move counts disagree with accepted steps') + if not isinstance(metrics['native_return'], (int, float)) or isinstance( + metrics['native_return'], bool) or not math.isfinite(metrics['native_return']): + raise ValueError('invalid 2048 native return') + if metrics['native_return'] != score or final['return'] != score: + raise ValueError('2048 score disagrees with native return') + reached = int(maximum >= 2 ** instance['target_power']) + if metrics['target_reached'] != reached: + raise ValueError('2048 target flag disagrees with maximum tile') + if final['success'] != (bool(reached) and not final['sim_error']): + raise ValueError('2048 success disagrees with target tile') + if final['steps'] == 0 and (score or valid or invalid or maximum > 4): + raise ValueError('2048 progress without an action') diff --git a/game_first_exam/benchmarks/game2048/requirements.txt b/game_first_exam/benchmarks/game2048/requirements.txt new file mode 100644 index 0000000..1eba85b --- /dev/null +++ b/game_first_exam/benchmarks/game2048/requirements.txt @@ -0,0 +1,10 @@ +cloudpickle==3.1.3 +Farama-Notifications==0.0.6 +gymnasium==1.3.0 +gymnasium-2048==0.1.2 +ImageIO==2.37.0 +imageio-ffmpeg==0.6.0 +numpy==1.26.4 +pillow==10.4.0 +pygame==2.6.1 +typing_extensions==4.16.0 diff --git a/game_first_exam/images/game2048-files/FILES.json b/game_first_exam/images/game2048-files/FILES.json new file mode 100644 index 0000000..aa1f39a --- /dev/null +++ b/game_first_exam/images/game2048-files/FILES.json @@ -0,0 +1,10 @@ +{ + "image": "ghcr.io/mll-lab-nu/efe:game2048-files-0.1.0@sha256:593f0e1acddbaa5ded9063240faae3f503a7fbd47796e881353d49313e3bcd5b", + "source": "game_first_exam/benchmarks/game2048", + "files": { + "adapter.py": "0847f01610056431292e0fde192c4fe27ba7a12246bd02e205743a596372918c", + "metric_rules.py": "16cf8351b56e9e6c81d0205224ecd0ba5d190a3f7039177eb410b4aff7a7a5b6", + "requirements.txt": "e9a56545e89778489fd2d5ee1922bb85cec310b2b7620178db6f31871988340f", + "instance_schema.py": "24f1dd3940edb74c4ea23527bf53004a7285f114446b7c402cba29f7cc0877d7" + } +} diff --git a/game_first_exam/images/game2048-files/README.md b/game_first_exam/images/game2048-files/README.md new file mode 100644 index 0000000..b50b59e --- /dev/null +++ b/game_first_exam/images/game2048-files/README.md @@ -0,0 +1,4 @@ +# game2048-files + +Files-only image for the Gymnasium 2048 adapter. Build locally with +`python scripts/files_image.py build game2048-files`. The pinned image is not published by this local integration. diff --git a/game_first_exam/images/game2048-files/VERSION b/game_first_exam/images/game2048-files/VERSION new file mode 100644 index 0000000..6e8bf73 --- /dev/null +++ b/game_first_exam/images/game2048-files/VERSION @@ -0,0 +1 @@ +0.1.0 diff --git a/game_first_exam/tests/envs/game2048.Dockerfile b/game_first_exam/tests/envs/game2048.Dockerfile new file mode 100644 index 0000000..94f5c35 --- /dev/null +++ b/game_first_exam/tests/envs/game2048.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 fonts-dejavu-core && rm -rf /var/lib/apt/lists/* +COPY game_first_exam/tests/envs/locks/game2048.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/envs/locks/game2048.txt b/game_first_exam/tests/envs/locks/game2048.txt new file mode 100644 index 0000000..1eba85b --- /dev/null +++ b/game_first_exam/tests/envs/locks/game2048.txt @@ -0,0 +1,10 @@ +cloudpickle==3.1.3 +Farama-Notifications==0.0.6 +gymnasium==1.3.0 +gymnasium-2048==0.1.2 +ImageIO==2.37.0 +imageio-ffmpeg==0.6.0 +numpy==1.26.4 +pillow==10.4.0 +pygame==2.6.1 +typing_extensions==4.16.0 diff --git a/game_first_exam/tests/test_game2048_contract.py b/game_first_exam/tests/test_game2048_contract.py new file mode 100644 index 0000000..e678309 --- /dev/null +++ b/game_first_exam/tests/test_game2048_contract.py @@ -0,0 +1,254 @@ +"""2048 adapter/service regressions with a deterministic native-shaped 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/game2048' / filename) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +backend = load('game2048_adapter_test', 'adapter.py') +schema = register_instance_schema(load('game2048_schema_test', 'instance_schema.py')) +rules = load('game2048_rules_test', 'metric_rules.py') + + +class Space: + n = 4 + shape = (4, 4, 16) + + +class Engine: + """Small native-shaped engine: target on step two, game over on step three.""" + def __init__(self): + self.unwrapped = self + self.action_space = Space() + self.observation_space = Space() + self.np_random = np.random.default_rng(1) + self.board = np.zeros((4, 4), dtype=np.uint8) + self.step_score = 0 + self.total_score = 0 + self.is_legal = True + self.illegal_count = 0 + self.actions = [] + self.reset_count = 0 + self.closed = False + self.image = np.zeros((460, 400, 3), dtype=np.uint8) + + def _observation(self): + out = np.zeros((4, 4, 16), dtype=np.uint8) + rows, cols = np.indices(self.board.shape) + out[rows, cols, self.board] = 1 + return out + + def _info(self): + return {'board': self.board, 'step_score': self.step_score, + 'total_score': self.total_score, 'max': int(self.board.max()), + 'is_legal': self.is_legal, 'illegal_count': self.illegal_count} + + def reset(self, seed=None): + self.reset_count += 1 + self.np_random = np.random.default_rng(seed) + self.board.fill(0) + self.board[0, 0], self.board[1, 1] = 1, 2 + self.step_score = self.total_score = self.illegal_count = 0 + self.is_legal = True + self.image.fill(seed % 255) + return self._observation(), self._info() + + def step(self, action): + self.actions.append(action) + self.step_score = 0 + if len(self.actions) == 1: + self.board[0, 0] = 2 + self.step_score = 4 + elif len(self.actions) == 2: + self.board[0, 1] = 11 + self.step_score = 2048 + elif action == 3: + self.is_legal = False + self.illegal_count += 1 + self.total_score += self.step_score + terminated = len(self.actions) == 3 + self.image.fill(100 + len(self.actions)) + return self._observation(), self.step_score, terminated, False, self._info() + + def render(self): + return self.image.copy() + + 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': 'game2048', + 'env_id': 'gymnasium_2048/TwentyFortyEight-v0', 'family': '2048-classic', + 'seed': 42, 'max_steps': 1000, 'initial_state_sha256': '0' * 64, + 'observation_profile': 'native-rgb-board-score-v1', + 'capabilities': {'images': True, 'action_mode': 'enum', + 'timing': 'action-stepped', 'native_truncation': False}, + 'engine_versions': dict(schema.ENGINE_VERSIONS), + 'board_size': 4, 'native_max_power': 16, + 'native_render_shape': [460, 400, 3], 'target_power': 11, + 'metric_spec': {'primary': 'native_score', 'reducer': 'family_macro', + 'reducer_version': '1.0.0', + 'success_label': '2048_tile_reached'}, + } + + +class Game2048ContractTests(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/game2048/requirements.txt' + lock = ROOT / 'game_first_exam/tests/envs/locks/game2048.txt' + self.assertEqual(runtime.read_text(), lock.read_text()) + + def test_native_profile_and_all_four_actions(self): + adapter = self.adapter() + self.assertEqual(adapter.env.reset_count, 1) + self.assertEqual(adapter.frame().shape, (460, 400, 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': 'UP', 'expected_step': 0, 'request_id': 'isolation-audit'})] + forbidden = {'seed', 'target_power', 'engine_versions', 'board', 'rng', + 'fingerprint', 'metrics', 'native_score', 'native_return', + 'max_tile', 'initial_state_sha256', 'is_legal'} + + def keys(value): + if isinstance(value, dict): + return set(value) | set().union(*(keys(v) for v in value.values()), set()) + if isinstance(value, list): + return set().union(*(keys(v) for v 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_native_score_target_and_game_over(self): + adapter = self.adapter() + self.assertEqual(adapter.step('UP').reward, 4) + self.assertEqual(adapter.step('RIGHT').reward, 2048) + self.assertTrue(adapter.success()) + transition = adapter.step('DOWN') + self.assertTrue(transition.terminated) + self.assertFalse(transition.truncated) + self.assertEqual(adapter.metrics(), { + 'target_reached': 1, 'native_score': 2052, 'max_tile': 2048, + 'valid_moves': 3, 'invalid_moves': 0, 'native_return': 2052.0, + }) + with self.assertRaisesRegex(ValueError, 'episode closed'): + adapter.step('UP') + + def test_invalid_action_does_not_advance(self): + adapter = self.adapter() + with self.assertRaisesRegex(ValueError, 'unknown 2048 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': 'UP', 'expected_step': 0, 'request_id': 'one'} + response = game.submit(first) + self.assertEqual(game.submit(first), response) + game.submit({'action': 'RIGHT', 'expected_step': 1, 'request_id': 'two'}) + game.submit({'action': 'DOWN', 'expected_step': 2, 'request_id': 'three'}) + self.assertEqual(len(adapter.env.actions), 3) + result = grade(game.final, config, rules.validate_metrics) + self.assertEqual((result['primary_score'], result['success']), (2052, 1)) + corrupted = copy.deepcopy(game.final) + corrupted['metrics']['native_score'] = 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 [('board_size', 5), ('native_max_power', 17), + ('native_render_shape', [400, 400, 3]), ('target_power', 10), + ('max_steps', None), ('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_game2048_native.py b/game_first_exam/tests/test_game2048_native.py new file mode 100644 index 0000000..53cc9ef --- /dev/null +++ b/game_first_exam/tests/test_game2048_native.py @@ -0,0 +1,115 @@ +"""Compare the adapter against direct pinned Gymnasium 2048 calls.""" +import importlib.util +import sys +import unittest +from pathlib import Path + +import gymnasium as gym +import gymnasium_2048 # noqa: F401 - registration +import numpy as np + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT / 'game_first_exam/runtime')) +spec = importlib.util.spec_from_file_location( + 'game2048_native_backend', ROOT / 'game_first_exam/benchmarks/game2048/adapter.py') +backend = importlib.util.module_from_spec(spec) +spec.loader.exec_module(backend) + + +def config(seed=42): + return { + 'engine_versions': {'gymnasium-2048': '0.1.2', 'gymnasium': '1.3.0', + 'numpy': '1.26.4', 'pygame': '2.6.1'}, + 'env_id': 'gymnasium_2048/TwentyFortyEight-v0', 'seed': seed, + 'board_size': 4, 'native_max_power': 16, + 'native_render_shape': [460, 400, 3], 'target_power': 11, + } + + +def native_env(cfg): + return gym.make(cfg['env_id'], render_mode='rgb_array', size=cfg['board_size'], + max_pow=cfg['native_max_power']) + + +def native_state(env): + native = env.unwrapped + return { + 'board': native.board.copy(), + 'rng': native.np_random.bit_generator.state, + 'step_score': native.step_score, + 'total_score': native.total_score, + 'is_legal': native.is_legal, + 'illegal_count': native.illegal_count, + } + + +class Game2048NativeTests(unittest.TestCase): + def assert_state_equal(self, left, right): + np.testing.assert_array_equal(left.pop('board'), right.pop('board')) + 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.env.unwrapped._get_obs(), observation) + np.testing.assert_array_equal(adapter.frame(), raw.render()) + observation, reward, terminated, truncated, _ = 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(), raw.render()) + np.testing.assert_array_equal(adapter.env.unwrapped._get_obs(), observation) + self.assert_state_equal(native_state(adapter.env), native_state(raw)) + finally: + adapter.close(); raw.close() + + def test_seeded_trajectory_matches_native(self): + sequence = ['UP', 'RIGHT', 'DOWN', 'LEFT', 'LEFT', 'UP', 'RIGHT', 'DOWN'] + for seed in (0, 42, 123): + with self.subTest(seed=seed): + cfg = config(seed) + adapter = backend.Adapter(cfg) + raw = native_env(cfg) + try: + observation, _ = raw.reset(seed=seed) + np.testing.assert_array_equal(adapter.env.unwrapped._get_obs(), observation) + initial = adapter.fingerprint() + adapter.spec(); adapter.observe(); adapter.metrics(); adapter.frame() + self.assertEqual(adapter.fingerprint(), initial) + for step in range(512): + name = sequence[step % len(sequence)] + observation, reward, terminated, truncated, _ = raw.step( + backend.ACTIONS[name]) + transition = adapter.step(name) + self.assertEqual((transition.reward, transition.terminated, + transition.truncated), + (float(reward), bool(terminated), bool(truncated))) + np.testing.assert_array_equal(adapter.env.unwrapped._get_obs(), observation) + np.testing.assert_array_equal(adapter.frame(), raw.render()) + self.assert_state_equal(native_state(adapter.env), native_state(raw)) + if terminated or truncated: + break + else: + self.fail('native 2048 episode did not end within 512 actions') + finally: + adapter.close(); raw.close() + + def test_seeded_initial_states_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()