diff --git a/.github/workflows/games.yml b/.github/workflows/games.yml index ebee4f6..da7ab75 100644 --- a/.github/workflows/games.yml +++ b/.github/workflows/games.yml @@ -25,12 +25,28 @@ jobs: strategy: fail-fast: false matrix: - benchmark: [common, minigrid, crafter, textworld, babaisai, minihack] + benchmark: [common, minigrid, crafter, textworld, babaisai, minihack, towermind] steps: - uses: actions/checkout@v4 with: {persist-credentials: false} - run: docker build -f game_first_exam/tests/envs/${{ matrix.benchmark }}.Dockerfile -t game-tests:${{ matrix.benchmark }} . - - run: docker run --rm -v "$PWD:/repo:ro" game-tests:${{ matrix.benchmark }} bash game_first_exam/tests/run.sh ${{ matrix.benchmark }} + - if: matrix.benchmark != 'towermind' + run: docker run --rm -v "$PWD:/repo:ro" game-tests:${{ matrix.benchmark }} bash game_first_exam/tests/run.sh ${{ matrix.benchmark }} + - if: matrix.benchmark == 'towermind' + run: docker run --rm --network none -v "$PWD:/repo:ro" game-tests:towermind bash game_first_exam/tests/run.sh towermind + - if: matrix.benchmark == 'towermind' + name: Check TowerMind sandbox boundary from a separate container + run: | + docker build --target client -f game_first_exam/tests/envs/towermind.Dockerfile -t game-tests:towermind-client . + bash game_first_exam/tests/check-towermind-network.sh + - if: matrix.benchmark == 'towermind' + uses: actions/setup-python@v5 + with: {python-version: '3.12'} + - if: matrix.benchmark == 'towermind' + name: Check TowerMind through Harbor's isolated agent and verifier + run: | + python -m pip install -e . + python game_first_exam/tests/check_towermind_harbor.py "$RUNNER_TEMP/towermind-harbor" harbor: runs-on: ubuntu-latest timeout-minutes: 15 diff --git a/configs/game_benchmarks.toml b/configs/game_benchmarks.toml index 8f77b59..c76095a 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.towermind] +schema = "game_first_exam/benchmarks/towermind/instance_schema.py" diff --git a/game_first_exam/benchmarks/towermind/README.md b/game_first_exam/benchmarks/towermind/README.md new file mode 100644 index 0000000..6e434a0 --- /dev/null +++ b/game_first_exam/benchmarks/towermind/README.md @@ -0,0 +1,24 @@ +# TowerMind adapter + +This development integration uses the upstream Unity Linux x86-64 player and both official TowerMind wrappers. `SOURCE.json` pins the archive and wrapper source by commit and SHA256. The simulator extracts a private copy and applies the level and seed selected for the run, following the upstream LLM example. The level seed is passed through the game configuration. The separate ML-Agents initialization seed uses the official Python example's default. All other game settings come from the pinned archive. + +Initialization resets through the TowerMind wrappers after the Gym bridge discovers its agent slots. The bridge uses the reported sensor names to route the player camera and JSON texture to the official observation wrapper. The first reset observation starts the public episode. The adapter records the first native terminal or interrupted transition and closes the episode. + +The public `player-rgb-v1` profile exposes one cached 512脳512 RGB player frame as PNG. Actions carry two coordinates in `[-3, 3]` and a native integer action type from 0 through 11 as a string, for example `"-1.5 1.2 2"`. The official wrapper handles native action mapping. The JSON state, raw step metadata, configuration, seed and fingerprints stay inside the simulator. The fingerprint covers the cached RGB pixels, JSON observation, instance identity and step outcomes. + +The development instance reports cumulative native reward as its primary metric. It stores the native-invalid and total action counts from the JSON feedback, using the upstream example's criteria and excluding no-ops. The shared runtime's Boolean outcome records native termination with the base alive, using health directly from the native observation. + +The CI Harbor 0.23.0 integration check creates a disposable development task in the runner's temporary directory and runs it with the native oracle. It checks the client and sim evidence collection. In the Linux CI trial, Harbor's verifier policy alone allowed a connection to the Docker host bridge. The development task also sets Docker Compose `network_mode: none` for the separate verifier in `tests/docker-compose.yaml`. The check requires only the loopback interface and confirms that the verifier cannot reach the same runner listener the agent reached. Harbor mounts `/logs/verifier` into the agent, so the verifier clears that directory before generating the grade. Simulator evidence comes exclusively from the `sim` artifact declaration. + +The Python ML-Agents gRPC listener binds to the simulator's own IPv4 loopback. The network test uses independent sim and client images, an internal Docker network and no shared mounts. Its client only carries the shared HTTP client, the connection helper and the probe. Keep those boundaries when packaging a Harbor task. Upstream static assets are public independently of access to the live simulator. + +The files-only image carries implementation and dependency inputs. The test image downloads and verifies the original assets at build time. It uses the upstream Colab example's Xvfb screen settings and lets Unity select its graphics backend. The image includes Mesa's software OpenGL and Vulkan drivers. When starting the official Linux player, the adapter disables the two Mesa anisotropic texture-filter extensions for that process. In the tested llvmpipe environment, the default filtering corrupts the byte values in the JSON sensor at reset. This renderer setting also applies to the player camera. The sensor and its stock decoder are used directly. The simulator loads the Gym bridge from the installed ML-Agents distribution directly because the package's Gym registry initializer attempts a remote manifest fetch. The Linux regression runs the stock wrappers with the upstream LLM launch sequence first, then compares adapter rewards and termination on the same action sequence. The host registers the native schema in `configs/game_benchmarks.toml`. The development instance in `game_first_exam/tests/fixtures/towermind-instance.json` exercises the integration before any exam is frozen. + +Run from the repository root on a Linux Docker host. + +```bash +docker build -f game_first_exam/tests/envs/towermind.Dockerfile -t game-tests:towermind . +docker run --rm --network none -v "$PWD:/repo:ro" game-tests:towermind bash game_first_exam/tests/run.sh towermind +docker build --target client -f game_first_exam/tests/envs/towermind.Dockerfile -t game-tests:towermind-client . +bash game_first_exam/tests/check-towermind-network.sh +``` diff --git a/game_first_exam/benchmarks/towermind/SOURCE.json b/game_first_exam/benchmarks/towermind/SOURCE.json new file mode 100644 index 0000000..9446889 --- /dev/null +++ b/game_first_exam/benchmarks/towermind/SOURCE.json @@ -0,0 +1,14 @@ +{ + "repository": "https://github.com/tb6147877/TowerMind", + "commit": "7ac5d5cb815ce022cdf6f6d40fa0a9fcc9be3e71", + "files": { + "linux.zip": { + "path": "compressed_env/linux.zip", + "sha256": "153f363150f5e33f4827599498e2d7bda504045a4ae258e013bb504ea4273e19" + }, + "wrappers.py": { + "path": "common/wrappers.py", + "sha256": "440eb20ac34f6fc80dcffca1938c95f49ea178b48a241c03771aae646617a15c" + } + } +} diff --git a/game_first_exam/benchmarks/towermind/adapter.py b/game_first_exam/benchmarks/towermind/adapter.py new file mode 100644 index 0000000..e34264f --- /dev/null +++ b/game_first_exam/benchmarks/towermind/adapter.py @@ -0,0 +1,141 @@ +"""Expose one cached player RGB frame and one native decision per accepted action.""" +from hashlib import sha256 +from importlib.metadata import version +import math +from pathlib import Path +import re +from tempfile import TemporaryDirectory + +import numpy as np + +from config_schema import validate_instance +from contracts import Transition +from encoding import png, state_hash +from instance_schema import CAPABILITIES +from native_assets import prepare_game + + +NATIVE_ASSETS = Path("/opt/towermind") +COORDINATE = r"-?(?:[0-2](?:\.[0-9]{1,9})?|3(?:\.0{1,9})?)" +ACTION_PATTERN = rf"{COORDINATE} {COORDINATE} (?:[0-9]|1[01])" +ACTION_LENGTH = 28 + + +def parse_action(action): + if not isinstance(action, str) or not re.fullmatch(ACTION_PATTERN, action): + raise ValueError("expected 'x y action_type' within the declared bounds") + x, y, action_type = action.split(" ") + return float(x), float(y), int(action_type) + + +def open_native(player, wrappers_path): + from native import open_native as launch + + return launch(player, wrappers_path) + + +class Adapter: + def __init__(self, instance, assets=None): + validate_instance(instance) + for package, expected in instance["engine_versions"].items(): + if version(package) != expected: + raise ValueError(f"TowerMind dependency version mismatch: {package}") + self.instance = dict(instance) + self._workspace = TemporaryDirectory(prefix="towermind-") + self._env = None + self._decisions = 0 + self._return = 0.0 + self._counted_actions = self._invalid_actions = 0 + self._terminated = self._truncated = False + source = NATIVE_ASSETS if assets is None or not (assets / "linux.zip").is_file() else assets + try: + player = prepare_game(source, Path(self._workspace.name), instance) + self._env, observation = open_native(player, source / "wrappers.py") + self._cache(observation) + except Exception: + self.close() + raise + + def _cache(self, observation): + health = observation["text"]["Level_Current_Health"] + if type(health) is not int or health < 0: + raise ValueError("invalid native TowerMind base health") + image = observation["image"] + if image.shape == (3, 512, 512): + image = np.moveaxis(image, 0, -1) + if image.shape != (512, 512, 3) or image.dtype != np.uint8: + raise ValueError("expected native 512x512 RGB uint8 frame") + self._image = np.array(image, copy=True, order="C") + self._image.flags.writeable = False + self._frame_sha256 = sha256(self._image).hexdigest() + self._public_png = png(self._image) + self._native_text = observation["text"] + + def spec(self): + return { + "adapter_version": "1.0.0", + "capabilities": dict(CAPABILITIES), + "action_schema": {"type": "string", "pattern": ACTION_PATTERN, "max_length": ACTION_LENGTH}, + "observation": "Cached native 512x512 RGB player frame encoded as PNG.", + "actions": "Submit x y action_type. Coordinates are in [-3, 3], and action_type is 0–11.", + } + + def observe(self): + return {"image_png_base64": self._public_png} + + def step(self, action): + if self._terminated or self._truncated: + raise ValueError("episode closed") + observation, reward, done, info = self._env.step(parse_action(action)) + reward = float(reward) + if not math.isfinite(reward): + raise ValueError("invalid native TowerMind reward") + outcome = observation["text"]["Agent_Last_Action_Info"] + action_type, error_code = outcome["Action_Index"], outcome["Error_Code"] + if type(action_type) is not int or not 0 <= action_type <= 11 or type(error_code) is not int: + raise ValueError("invalid native TowerMind action feedback") + self._cache(observation) + # Match the upstream LLM example's counters for reported actions. + if action_type != 6: + self._counted_actions += 1 + self._invalid_actions += int(error_code > 0) + interrupted = bool(info["step"].interrupted[0]) if done else False + self._terminated = bool(done and not interrupted) + self._truncated = interrupted + self._decisions += 1 + self._return += reward + return Transition(reward, self._terminated, self._truncated) + + def success(self): + # Compatibility flag for the shared service's native outcome record. + return self._terminated and self._native_text["Level_Current_Health"] > 0 + + def metrics(self): + return { + "native_return": self._return, + "base_health": self._native_text["Level_Current_Health"], + "native_decisions": self._decisions, + "native_counted_actions": self._counted_actions, + "native_invalid_actions": self._invalid_actions, + } + + def fingerprint(self): + # Unity does not export a complete engine checkpoint or the internal RNG state. + return state_hash({ + "archive": self.instance["engine_archive_sha256"], + "level": self.instance["level_id"], "seed": self.instance["seed"], + "frame_sha256": self._frame_sha256, "decisions": self._decisions, "return": self._return, + "text": self._native_text, + "terminated": self._terminated, "truncated": self._truncated, + }) + + def frame(self): + return self._image + + def close(self): + try: + if self._env is not None: + env, self._env = self._env, None + env.close() + finally: + self._workspace.cleanup() diff --git a/game_first_exam/benchmarks/towermind/instance_schema.py b/game_first_exam/benchmarks/towermind/instance_schema.py new file mode 100644 index 0000000..40d588f --- /dev/null +++ b/game_first_exam/benchmarks/towermind/instance_schema.py @@ -0,0 +1,37 @@ +"""Trusted adapter profile. Importable without simulator dependencies.""" +from config_schema import validate_engine_versions + + +SCHEMA_VERSION = "1.0.0" +BENCHMARK = "towermind" +FIELDS = {"level_id", "engine_versions", "engine_archive_sha256"} +METRICS = {"native_return"} +PROFILES = {"player-rgb-v1"} +REDUCERS = {("family_macro", "1.0.0")} +CAPABILITIES = { + "images": True, "action_mode": "text", "timing": "action-stepped", "native_truncation": True, +} +ARCHIVE_SHA256 = "153f363150f5e33f4827599498e2d7bda504045a4ae258e013bb504ea4273e19" +ENGINE_VERSIONS = { + "mlagents-envs": "1.1.0", + "gym": "0.26.2", + "numpy": "1.23.5", + "grpcio": "1.48.2", + "protobuf": "3.20.3", + "opencv-python-headless": "4.10.0.84", +} + + +def validate(value): + validate_engine_versions(value["engine_versions"], ENGINE_VERSIONS) + level = value["level_id"] + if type(level) is not int or not 0 <= level <= 8 or value["env_id"] != f"TowerMind-Level-{level}": + raise ValueError("unsupported native TowerMind level") + if value["seed"] == 0: + raise ValueError("TowerMind profile requires a positive seed") + if value["engine_archive_sha256"] != ARCHIVE_SHA256: + raise ValueError("unsupported native TowerMind archive") + if value["capabilities"] != CAPABILITIES: + raise ValueError("TowerMind requires the RGB action-stepped profile") + if value["metric_spec"]["success_label"] != "native_level_completed": + raise ValueError("unsupported TowerMind success label") diff --git a/game_first_exam/benchmarks/towermind/metric_rules.py b/game_first_exam/benchmarks/towermind/metric_rules.py new file mode 100644 index 0000000..1fb21fa --- /dev/null +++ b/game_first_exam/benchmarks/towermind/metric_rules.py @@ -0,0 +1,17 @@ +"""Validate native outcome evidence without loading Unity.""" +def validate_metrics(final, instance): + metrics = final["metrics"] + health = metrics["base_health"] + if type(health) is not int or health < 0: + raise ValueError("invalid TowerMind base health") + if type(metrics["native_decisions"]) is not int or metrics["native_decisions"] != final["steps"]: + raise ValueError("TowerMind decision count disagrees with the service") + reward = metrics["native_return"] + if type(reward) not in (int, float) or reward != final["return"]: + raise ValueError("TowerMind cumulative return disagrees with the service") + counted, invalid = metrics["native_counted_actions"], metrics["native_invalid_actions"] + if type(counted) is not int or type(invalid) is not int or not 0 <= invalid <= counted <= final["steps"]: + raise ValueError("invalid TowerMind action counts") + won = final["reason"] == "native_terminated" and health > 0 + if final["success"] != won: + raise ValueError("TowerMind success requires a completed native level with the base alive") diff --git a/game_first_exam/benchmarks/towermind/native.py b/game_first_exam/benchmarks/towermind/native.py new file mode 100644 index 0000000..b5e3bd6 --- /dev/null +++ b/game_first_exam/benchmarks/towermind/native.py @@ -0,0 +1,121 @@ +"""Pinned ML-Agents bridge. Only the simulator process can reach the Unity RPC listener.""" +from concurrent.futures import ThreadPoolExecutor +from importlib.metadata import distribution +from importlib.util import module_from_spec, spec_from_file_location +from json import JSONDecodeError + +import grpc +from mlagents_envs.environment import UnityEnvironment +from mlagents_envs.rpc_communicator import ( + RpcCommunicator, + UnityToExternalServicerImplementation, + add_UnityToExternalProtoServicer_to_server, +) +from mlagents_envs.side_channel.engine_configuration_channel import EngineConfigurationChannel + + +RPC_PORT = 5005 +NO_OP = (0.0, 0.0, 6) + + +def load_source(name, path): + spec = spec_from_file_location(name, path) + module = module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def load_gym_bridge(): + # Importing mlagents_envs.envs fetches a remote registry at module import. + # Load only the Gym bridge from the pinned, installed distribution. + path = distribution("mlagents-envs").locate_file("mlagents_envs/envs/unity_gym_env.py") + return load_source("_towermind_unity_gym", path).UnityToGymWrapper + + +class LoopbackCommunicator(RpcCommunicator): + def create_server(self): + # ML-Agents 1.1.0 otherwise binds [::]. The public HTTP server is a separate listener. + self.check_port(self.port) + self.server = grpc.server( + ThreadPoolExecutor(max_workers=10), options=(("grpc.so_reuseport", 0),) + ) + self.unity_to_external = UnityToExternalServicerImplementation() + try: + add_UnityToExternalProtoServicer_to_server(self.unity_to_external, self.server) + if self.server.add_insecure_port(f"127.0.0.1:{self.port}") != self.port: + raise RuntimeError("TowerMind RPC listener failed to bind loopback") + self.server.start() + except Exception: + self.server.stop(0) + self.unity_to_external.parent_conn.close() + self.unity_to_external.child_conn.close() + raise + self.is_open = True + + +class LocalUnity(UnityEnvironment): + _initializing = True + + @staticmethod + def _get_communicator(worker_id, base_port, timeout_wait): + return LoopbackCommunicator(worker_id, base_port, timeout_wait) + + def reset(self): + if not self._initializing: + raise RuntimeError("TowerMind simulator supports one episode") + return super().reset() + + +def multimodal_observations(gym, wrappers): + # The stock wrapper expects the camera followed by the text texture. + # The Gym bridge returns visual sensors in the order announced by Unity. + visual = [spec for spec in gym.group_spec.observation_specs if len(spec.shape) == 3] + cameras = [ + index for index, spec in enumerate(visual) + if spec.name == "CameraSensor" and spec.shape in ((512, 512, 3), (3, 512, 512)) + ] + text_sensors = [index for index, spec in enumerate(visual) if spec.name == "RenderTextureSensor"] + specs = [(spec.name, spec.shape) for spec in visual] + if len(cameras) != 1 or len(text_sensors) != 1: + raise ValueError(f"expected one native RGB camera and one text texture, got {specs}") + camera, = cameras + text, = text_sensors + + class NativeObservations(wrappers.TowerMindMultiModalObsWrapper): + def _convert_obs(self, observation): + try: + return super()._convert_obs([observation[camera], observation[text]]) + except JSONDecodeError as error: + raise ValueError( + f"TowerMind text texture is not valid JSON at offset {error.pos}, " + f"decoded length {len(error.doc)}, native sensors {specs}" + ) from None + + return NativeObservations(gym, use_image=True, use_text=True, use_state=False) + + +def open_native(player, wrappers_path): + """Run the upstream startup sequence before exposing the first decision.""" + gym_wrapper = load_gym_bridge() + wrappers = load_source("_towermind_upstream_wrappers", wrappers_path) + channel = EngineConfigurationChannel() + channel.set_configuration_parameters(target_frame_rate=-1, time_scale=20.0, capture_frame_rate=60) + unity = LocalUnity( + file_name=str(player), base_port=RPC_PORT, timeout_wait=60, + side_channels=[channel], log_folder=str(player.parent), + ) + try: + gym = gym_wrapper(unity, uint8_visual=True, allow_multiple_obs=True) + env = wrappers.TowerMindActionMappingWrapper(multimodal_observations(gym, wrappers)) + # UnityToGymWrapper resets during its constructor to inspect agent slots. + # TowerMind's example then resets the wrapped environment to obtain the + # playable observation. + initial = env.reset() + unity._initializing = False + decision, terminal = unity.get_steps(gym.name) + if len(decision) != 1 or len(terminal): + raise ValueError("unexpected TowerMind initial decision") + return env, initial + except Exception: + unity.close() + raise diff --git a/game_first_exam/benchmarks/towermind/native_assets.py b/game_first_exam/benchmarks/towermind/native_assets.py new file mode 100644 index 0000000..379d0c9 --- /dev/null +++ b/game_first_exam/benchmarks/towermind/native_assets.py @@ -0,0 +1,67 @@ +"""Pin upstream assets at image build and prepare a private copy for each simulator.""" +import hashlib +import json +from pathlib import Path +import shutil +import sys +from urllib.request import urlopen +from zipfile import ZipFile + + +SOURCE = json.loads(Path(__file__).with_name("SOURCE.json").read_text()) +ARCHIVE_SHA256 = SOURCE["files"]["linux.zip"]["sha256"] + + +def verify_asset(path): + digest = hashlib.sha256() + with path.open("rb") as stream: + for block in iter(lambda: stream.read(1024 * 1024), b""): + digest.update(block) + if digest.hexdigest() != SOURCE["files"][path.name]["sha256"]: + raise ValueError(f"unexpected TowerMind asset digest: {path.name}") + + +def download_assets(directory): + directory.mkdir(parents=True, exist_ok=True) + upstream = f"https://raw.githubusercontent.com/tb6147877/TowerMind/{SOURCE['commit']}" + for name, description in SOURCE["files"].items(): + destination = directory / name + if not destination.exists(): + with urlopen(f"{upstream}/{description['path']}", timeout=120) as response: + with destination.open("wb") as stream: + shutil.copyfileobj(response, stream) + verify_asset(destination) + + +def prepare_game(assets, workspace, instance): + archive = assets / "linux.zip" + verify_asset(archive) + verify_asset(assets / "wrappers.py") + with ZipFile(archive) as bundle: + bundle.extractall(workspace) + directory = workspace / "linux" + player = directory / "td.x86_64" + player.chmod(0o700) + configs = directory / "td_Data/StreamingAssets/Config" + settings_path = configs / "EnvConfig.json" + settings = json.loads(settings_path.read_text(encoding="utf-8")) + # The upstream LLM example changes only the level and seed. + settings["RandomSeed"] = instance["seed"] + settings_path.write_text(json.dumps(settings), encoding="utf-8") + (configs / "FixedLevelsConfig.json").write_text( + json.dumps({"CurrentLevel": instance["level_id"]}), encoding="utf-8" + ) + # Mesa llvmpipe can filter adjacent byte values in TowerMind's JSON texture. + # Scope the renderer setting to the Unity child; leave the original player intact. + launcher = directory / "launch.x86_64" + launcher.write_bytes( + b'#!/bin/sh\n' + b'export MESA_EXTENSION_OVERRIDE="-GL_EXT_texture_filter_anisotropic -GL_ARB_texture_filter_anisotropic"\n' + b'exec "${0%/*}/td.x86_64" "$@"\n' + ) + launcher.chmod(0o700) + return launcher + + +if __name__ == "__main__": + download_assets(Path(sys.argv[1])) diff --git a/game_first_exam/benchmarks/towermind/requirements.txt b/game_first_exam/benchmarks/towermind/requirements.txt new file mode 100644 index 0000000..5b4bbfb --- /dev/null +++ b/game_first_exam/benchmarks/towermind/requirements.txt @@ -0,0 +1,17 @@ +# Resolved for Linux x86-64, CPython 3.10.12. +cloudpickle==3.1.3 +filelock==4.1.0 +grpcio==1.48.2 +gym==0.26.2 +gym-notices==0.1.0 +imageio==2.34.2 +imageio-ffmpeg==0.5.1 +mlagents-envs==1.1.0 +numpy==1.23.5 +opencv-python-headless==4.10.0.84 +pettingzoo==1.15.0 +pillow==10.4.0 +protobuf==3.20.3 +pyyaml==6.0.3 +setuptools==84.2.1 +six==1.17.0 diff --git a/game_first_exam/images/towermind-files/FILES.json b/game_first_exam/images/towermind-files/FILES.json new file mode 100644 index 0000000..bd37f39 --- /dev/null +++ b/game_first_exam/images/towermind-files/FILES.json @@ -0,0 +1,13 @@ +{ + "image": "ghcr.io/mll-lab-nu/efe:towermind-files-0.1.8@sha256:a7de67aac76712b167632fb73bd9c45b76af18fd9ff97171e7249799c5059d70", + "source": "game_first_exam/benchmarks/towermind", + "files": { + "adapter.py": "772157c6f86a927dcd4139936cb71766e26f426c69ab6e71c3d023caeaf8ef70", + "instance_schema.py": "5839f40497a13cc4a074258db508419e99fc73dcffc0b07c5d6c31e7193cf8c5", + "metric_rules.py": "992513d482e4dc39edf5bb71c17c6acfe6fedd771d2692144538cf280b56ad47", + "native.py": "4fc3cbdbf8d4b4ef411ab15e66117aff69d178071565afb2d170f6a994c2ade5", + "native_assets.py": "22fdc08da4222f5b76bf2f4d9448e29a04e412ef678e04e6d1e208bb46efb52f", + "requirements.txt": "1dae4bbe8f73c36d8ef74c6b9fcd6eedc20a8a7ce239d8e247122ac01f54b43a", + "SOURCE.json": "f1cd82c5b88d0095c0d3087ed5a7c5f76f2a8160414b199793d24ea378dad989" + } +} diff --git a/game_first_exam/images/towermind-files/README.md b/game_first_exam/images/towermind-files/README.md new file mode 100644 index 0000000..23f1ee2 --- /dev/null +++ b/game_first_exam/images/towermind-files/README.md @@ -0,0 +1,3 @@ +# towermind-files + +Build this files-only image locally with `python scripts/files_image.py build towermind-files`. It packages the adapter, configuration and grading contracts, provenance, dependency lock and Unity bridge. The simulator build fetches the pinned upstream game archive separately. diff --git a/game_first_exam/images/towermind-files/VERSION b/game_first_exam/images/towermind-files/VERSION new file mode 100644 index 0000000..699c6c6 --- /dev/null +++ b/game_first_exam/images/towermind-files/VERSION @@ -0,0 +1 @@ +0.1.8 diff --git a/game_first_exam/tests/check-towermind-network.sh b/game_first_exam/tests/check-towermind-network.sh new file mode 100644 index 0000000..7519f0e --- /dev/null +++ b/game_first_exam/tests/check-towermind-network.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash +# Use a new internal network, with no host ports or shared volumes. +set -euo pipefail +network="towermind-test-$$-$RANDOM" +sim="$network-sim" +cleanup() { + docker rm -f "$sim" >/dev/null 2>&1 || true + docker network rm "$network" >/dev/null 2>&1 || true +} +docker network create --internal "$network" >/dev/null +trap cleanup EXIT +docker run -d --init --name "$sim" --network "$network" --network-alias sim \ + "${1:-game-tests:towermind}" >/dev/null +if ! docker run --rm --network "$network" "${2:-game-tests:towermind-client}"; then + docker inspect --format '{{.State.Status}} (exit {{.State.ExitCode}}), command {{json .Config.Cmd}}' "$sim" + docker logs "$sim" + exit 1 +fi diff --git a/game_first_exam/tests/check_towermind_harbor.py b/game_first_exam/tests/check_towermind_harbor.py new file mode 100644 index 0000000..15004cd --- /dev/null +++ b/game_first_exam/tests/check_towermind_harbor.py @@ -0,0 +1,229 @@ +"""Run a disposable TowerMind trial through Harbor's Docker and separate verifier.""" +import json +from pathlib import Path +import re +from shutil import copy2 +import socket +import subprocess +import sys +from textwrap import dedent + + +ROOT = Path(__file__).resolve().parents[2] +TESTS = ROOT / "game_first_exam/tests" +RUNTIME = ROOT / "game_first_exam/runtime" +BENCHMARK = ROOT / "game_first_exam/benchmarks/towermind" +SIM_IMAGE = "game-tests:towermind" +CLIENT_IMAGE = "game-tests:towermind-client" + + +def write(path, content): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(dedent(content).lstrip(), encoding="utf-8", newline="\n") + + +def freeze_instance(): + # Run the same player, renderer and screen configuration as the Harbor simulator. + code = """ +import sys +sys.path.insert(0, 'game_first_exam/tests') +from towermind_fixture import instance +from adapter import Adapter +adapter = Adapter(instance()) +try: + print('Initial SHA256:', adapter.fingerprint()) +finally: + adapter.close() +""" + run = subprocess.run( + ["docker", "run", "--rm", "--init", "--network", "none", SIM_IMAGE, + "xvfb-run", "-a", "-s", "-screen 0 1400x900x24", "python", "-c", code], + check=True, stdout=subprocess.PIPE, text=True, + ) + hashes = re.findall(r"^Initial SHA256: ([0-9a-f]{64})$", run.stdout, re.MULTILINE) + if len(hashes) != 1: + raise ValueError("expected the simulator's initial fingerprint") + config = json.loads((TESTS / "fixtures/towermind-instance.json").read_text(encoding="utf-8")) + config["initial_state_sha256"] = hashes[0] + return json.dumps(config, indent=2) + "\n" + + +def stage_task(task, instance, endpoint): + write(task / "instruction.md", """ + # TowerMind isolation smoke test + + Use the public GameClient to inspect the initial player frame and submit one command. + This development check exercises Harbor's container and evidence boundaries. + """) + write(task / "task.toml", """ + schema_version = "1.3" + artifacts = [{ source = "/data/final.json", service = "sim" }] + + [environment] + build_timeout_sec = 300.0 + cpus = 2 + memory_mb = 2048 + storage_mb = 2048 + + [agent] + timeout_sec = 180.0 + network_mode = "public" + + [verifier] + timeout_sec = 60.0 + environment_mode = "separate" + network_mode = "no-network" + + [[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 + """) + write(task / "environment/docker-compose.yaml", """ + services: + main: + depends_on: [sim] + sim: + build: + context: sim + dockerfile: Dockerfile + init: true + command: ["xvfb-run", "-a", "-s", "-screen 0 1400x900x24", "python", "/srv/server.py"] + healthcheck: + test: ["CMD", "python", "-c", "from urllib.request import urlopen; urlopen('http://127.0.0.1:8000/spec', timeout=1).close()"] + interval: 2s + timeout: 2s + retries: 40 + """) + write(task / "environment/Dockerfile", f""" + FROM {CLIENT_IMAGE} + USER root + """) + write(task / "environment/sim/Dockerfile", f""" + FROM {SIM_IMAGE} + USER root + RUN mkdir -p /srv /data && chown 65534:65534 /data \\ + && cp /repo/game_first_exam/runtime/*.py /repo/game_first_exam/benchmarks/towermind/*.py /srv/ \\ + && cp /repo/game_first_exam/benchmarks/towermind/SOURCE.json /srv/ + COPY instance.json /srv/instance.json + USER 65534:65534 + WORKDIR /srv + """) + write(task / "environment/sim/instance.json", instance) + for directory in ("solution", "tests"): + write(task / directory / "canary.py", f"ADDRESS = {endpoint!r}\n") + write(task / "solution/solve.sh", """ + #!/bin/bash + set -euo pipefail + PYTHONPATH=/app:/solution python - <<'PY' + from pathlib import Path + import socket + + from canary import ADDRESS + from towermind_probe import main + + with socket.create_connection(ADDRESS, timeout=3): + print("Harbor agent reached the test listener on the runner.") + + for path in ("/tests", "/data/final.json", "/var/run/docker.sock", + "/logs/verifier/reward.json", "/logs/verifier/reward.txt"): + assert not Path(path).exists(), f"agent can see private path: {path}" + + mountpoints = {line.split()[4] for line in Path("/proc/self/mountinfo").read_text().splitlines()} + if "/logs/verifier" in mountpoints: + print("Harbor exposes a verifier log mount to the agent; treat its contents as untrusted.") + Path("/logs/verifier/agent-marker").write_text("untrusted agent output") + main() + Path("/app/agent-marker").write_text("agent-only filesystem change") + print("Harbor agent container isolation passed.") + PY + """) + write(task / "tests/instance.json", instance) + # Harbor builds the separate verifier from tests/, including its own Compose file. + write(task / "tests/docker-compose.yaml", """ + services: + main: + network_mode: none + """) + write(task / "tests/Dockerfile", """ + FROM docker.io/library/python:3.12.10-slim-bookworm@sha256:fd95fa221297a88e1cf49c55ec1828edd7c5a428187e67b5d1805692d11588db + COPY . /tests/ + RUN chmod +x /tests/test.sh + """) + write(task / "tests/test.sh", """ + #!/bin/bash + set -euo pipefail + # Harbor 0.23.0 mounts this output directory into the agent too. + find /logs/verifier -mindepth 1 -maxdepth 1 -exec rm -rf -- {} + + python /tests/check_isolation.py 2>/logs/verifier/isolation-error.log + python /tests/grade.py 2>/logs/verifier/grade-error.log + """) + write(task / "tests/check_isolation.py", """ + import json + from pathlib import Path + import socket + + from canary import ADDRESS + + assert {name for _, name in socket.if_nameindex()} == {"lo"}, "verifier has a non-loopback interface" + try: + connection = socket.create_connection(ADDRESS, timeout=3) + except OSError: + pass + else: + connection.close() + raise AssertionError("offline verifier reached the test listener on the runner") + assert not Path("/app/agent-marker").exists(), "verifier inherited the agent filesystem" + assert not Path("/logs/verifier/agent-marker").exists(), "agent output survived verifier cleanup" + evidence = json.loads(Path("/data/final.json").read_text()) + assert evidence["benchmark"] == "towermind" and evidence["result_valid"] is True + assert evidence["steps"] == 1 and evidence["reason"] == "agent_finished" + Path("/logs/verifier/isolation.txt").write_text( + "Harbor separate verifier is offline, has a fresh filesystem and received sealed sim evidence.\\n" + ) + """) + for name in ("grade.py", "config_schema.py", "reducers.py"): + copy2(RUNTIME / name, task / "tests" / name) + for name in ("instance_schema.py", "metric_rules.py"): + copy2(BENCHMARK / name, task / "tests" / name) + + +def main(workdir): + task = workdir / "towermind-isolation" + jobs = workdir / "jobs" + instance = freeze_instance() + job = jobs / "towermind-isolation" + bridge = json.loads(subprocess.check_output(["docker", "network", "inspect", "bridge"], text=True)) + gateway = bridge[0]["IPAM"]["Config"][0]["Gateway"] + # Keep a known-reachable TCP listener alive for both the agent and verifier checks. + with socket.create_server((gateway, 0)) as listener: + stage_task(task, instance, listener.getsockname()) + run = subprocess.run([ + "harbor", "run", "-p", str(task), "-c", str(ROOT / "configs/harbor/oracle.json"), + "--jobs-dir", str(jobs), "--job-name", job.name, "-y", + ]) + for pattern in ("*/agent/oracle.txt", "*/verifier/isolation.txt", "*/verifier/*-error.log", "*/trial.log"): + for log in job.glob(pattern): + if content := log.read_text(encoding="utf-8", errors="replace")[-3500:]: + print(f"{log.name}: {content}", flush=True) + markers = list(job.glob("*/verifier/isolation.txt")) + if run.returncode or len(markers) != 1 or not markers[0].with_name("reward.json").is_file(): + run.check_returncode() + raise RuntimeError("the isolated verifier did not generate a grade") + marker = markers[0] + trial = json.loads((marker.parent.parent / "result.json").read_text(encoding="utf-8")) + assert trial.get("exception_info") is None and trial["verifier_result"]["rewards"] is not None + result = json.loads(marker.with_name("metrics.json").read_text(encoding="utf-8")) + assert result["result_valid"] is True + assert result["reason"] == "agent_finished" and result["steps"] == 1 + assert result["infra_error"] == 0 and result["primary_metric"] == "native_return" + print("TowerMind passed the Harbor agent, simulator and verifier isolation checks.") + + +if __name__ == "__main__": + main(Path(sys.argv[1]).resolve()) diff --git a/game_first_exam/tests/envs/README.md b/game_first_exam/tests/envs/README.md index 99c196e..2afb37a 100644 --- a/game_first_exam/tests/envs/README.md +++ b/game_first_exam/tests/envs/README.md @@ -1,6 +1,6 @@ # Fixed game test environments -All images pin Python 3.12.10 by OCI digest and install explicit Python dependency versions with `--no-deps`. `common` needs no native game package. Each adapter has an independent image and missing dependencies fail the tests. The existing required `invariants` job depends on common unit tests and all adapter matrix jobs. +Images pin their Python base by OCI digest and install explicit Python dependency versions with `--no-deps`. TowerMind uses Python 3.10.12 for ML-Agents compatibility. See the [TowerMind adapter notes](../../benchmarks/towermind/README.md) for its offline simulator and two-container checks. `common` needs no native game package. Each adapter has an independent image and missing dependencies fail the tests. The existing required `invariants` job depends on common unit tests and all adapter matrix jobs. ```bash docker build -f game_first_exam/tests/envs/common.Dockerfile -t game-tests:common . diff --git a/game_first_exam/tests/envs/towermind.Dockerfile b/game_first_exam/tests/envs/towermind.Dockerfile new file mode 100644 index 0000000..460d43b --- /dev/null +++ b/game_first_exam/tests/envs/towermind.Dockerfile @@ -0,0 +1,29 @@ +FROM --platform=linux/amd64 docker.io/library/python:3.10.12-slim-bookworm@sha256:4d440b214e447deddc0a94de23a3d97d28dfafdf125a8b4bb8073381510c9ee2 AS base +ENV PYTHONUNBUFFERED=1 + +FROM base AS client +WORKDIR /app +COPY game_first_exam/runtime/game_client.py shared/connection/service_connection.py /app/ +COPY game_first_exam/tests/towermind_probe.py /app/ +USER 65534:65534 +CMD ["python", "/app/towermind_probe.py"] + +FROM base AS sim +RUN apt-get update && apt-get install -y --no-install-recommends \ + ca-certificates libasound2 libgl1 libgl1-mesa-dri libglx-mesa0 libglib2.0-0 \ + libx11-6 libxcursor1 libxext6 libxfixes3 libxi6 libxinerama1 libxrandr2 \ + libxrender1 libvulkan1 mesa-vulkan-drivers xauth xvfb \ + && rm -rf /var/lib/apt/lists/* +ENV LIBGL_ALWAYS_SOFTWARE=1 HOME=/tmp +WORKDIR /repo +COPY game_first_exam/benchmarks/towermind/ /repo/game_first_exam/benchmarks/towermind/ +RUN pip install --no-cache-dir --no-deps setuptools==84.2.1 wheel==0.45.1 \ + && pip install --no-cache-dir --no-deps --no-build-isolation -r game_first_exam/benchmarks/towermind/requirements.txt \ + && pip check \ + && python game_first_exam/benchmarks/towermind/native_assets.py /opt/towermind +COPY game_first_exam/runtime/ /repo/game_first_exam/runtime/ +COPY game_first_exam/tests/fixtures/towermind-instance.json /repo/game_first_exam/tests/fixtures/ +COPY game_first_exam/tests/towermind_fixture.py game_first_exam/tests/test_towermind_contract.py \ + game_first_exam/tests/test_towermind_native.py /repo/game_first_exam/tests/ +USER 65534:65534 +CMD ["xvfb-run", "-a", "-s", "-screen 0 1400x900x24", "python", "game_first_exam/tests/towermind_fixture.py"] diff --git a/game_first_exam/tests/fixtures/towermind-instance.json b/game_first_exam/tests/fixtures/towermind-instance.json new file mode 100644 index 0000000..42ed810 --- /dev/null +++ b/game_first_exam/tests/fixtures/towermind-instance.json @@ -0,0 +1,34 @@ +{ + "schema_version": "game-instance/2.2", + "protocol": "game-standard/2.2", + "adapter_version": "1.0.0", + "capabilities": { + "images": true, + "action_mode": "text", + "timing": "action-stepped", + "native_truncation": true + }, + "benchmark": "towermind", + "env_id": "TowerMind-Level-0", + "family": "development", + "level_id": 0, + "seed": 42, + "max_steps": null, + "initial_state_sha256": "0000000000000000000000000000000000000000000000000000000000000000", + "engine_versions": { + "mlagents-envs": "1.1.0", + "gym": "0.26.2", + "numpy": "1.23.5", + "grpcio": "1.48.2", + "protobuf": "3.20.3", + "opencv-python-headless": "4.10.0.84" + }, + "engine_archive_sha256": "153f363150f5e33f4827599498e2d7bda504045a4ae258e013bb504ea4273e19", + "observation_profile": "player-rgb-v1", + "metric_spec": { + "primary": "native_return", + "success_label": "native_level_completed", + "reducer": "family_macro", + "reducer_version": "1.0.0" + } +} diff --git a/game_first_exam/tests/run.sh b/game_first_exam/tests/run.sh index a033e85..e0c6ca6 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 ;; + towermind) + python3 game_first_exam/tests/test_towermind_contract.py + xvfb-run -a -s "-screen 0 1400x900x24" python3 game_first_exam/tests/test_towermind_native.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_game_configuration.py b/game_first_exam/tests/test_game_configuration.py index 37561f9..0ac2eea 100644 --- a/game_first_exam/tests/test_game_configuration.py +++ b/game_first_exam/tests/test_game_configuration.py @@ -24,20 +24,24 @@ from grade import grade from run_games import aggregate from server import EnvironmentFault, Game, InvalidAction +from task_conventions import iter_tasks, mode_of from test_game_service import Backend, instance from test_games_runner import record, trial class ConfigTests(unittest.TestCase): def test_each_bundled_schema_works_without_repo_or_engine_packages(self): + tasks = [task for task in iter_tasks() if mode_of(task) == 'standard' and '-i00-' not in task.name] for benchmark, schema in schema_paths().items(): - task = next(p for p in sorted((ROOT / 'game_first_exam/tasks' / benchmark).glob('*-standard')) if '-i00-' not in p.name) + # A registered benchmark can have an integration fixture before its first reviewed exam. + sample = next((task / 'tests/instance.json' for task in tasks if task.parent.name == benchmark), + ROOT / 'game_first_exam/tests/fixtures' / f'{benchmark}-instance.json') with self.subTest(benchmark=benchmark), tempfile.TemporaryDirectory() as tmp: out = Path(tmp) for name in ('config_schema.py', 'reducers.py'): shutil.copyfile(ROOT / 'game_first_exam/runtime' / name, out / name) shutil.copyfile(schema, out / 'instance_schema.py') - shutil.copyfile(task / 'tests/instance.json', out / 'instance.json') + shutil.copyfile(sample, out / 'instance.json') program = '''import json, sys sys.path.insert(0, '.') from config_schema import validate_instance diff --git a/game_first_exam/tests/test_towermind_contract.py b/game_first_exam/tests/test_towermind_contract.py new file mode 100644 index 0000000..de9d63e --- /dev/null +++ b/game_first_exam/tests/test_towermind_contract.py @@ -0,0 +1,245 @@ +"""Verify the public projection, action validation and grading without launching Unity.""" +import base64 +from contextlib import contextmanager +from io import BytesIO +from json import JSONDecodeError +from pathlib import Path +from tempfile import TemporaryDirectory +from types import SimpleNamespace +import unittest +from unittest.mock import patch + +import numpy as np +from PIL import Image + +from towermind_fixture import instance +import adapter +from config_schema import validate_instance +from grade import grade +from metric_rules import validate_metrics +from native_assets import ARCHIVE_SHA256 +from server import EnvironmentFault, Game, InvalidAction + + +def native_observation(shade=91, health=20, action_type=6, error_code=0): + return { + "image": np.full((512, 512, 3), shade, dtype=np.uint8), + "text": { + "Level_Current_Health": health, + "Agent_Last_Action_Info": {"Action_Index": action_type, "Error_Code": error_code}, + "private": "hidden-wave-sentinel", + }, + } + + +class StubNative: + def __init__(self, outcome): + self.outcome = outcome + self.actions = [] + self.closed = False + + def step(self, action): + self.actions.append(action) + health = 0 if self.outcome == "destroyed" else 20 + reward = {"destroyed": -20.0, "feedback": -1.01, "nonfinite_reward": float("nan")}.get(self.outcome, 0.0) + observation = native_observation(92, health, action[2], int(self.outcome == "feedback")) + return observation, np.float32(reward), True, { + "step": SimpleNamespace(interrupted=[self.outcome == "interrupted"]) + } + + def close(self): + self.closed = True + + +@contextmanager +def session(outcome): + config = instance() + native = StubNative(outcome) + with TemporaryDirectory() as output: + with ( + patch.object(adapter, "version", side_effect=config["engine_versions"].__getitem__), + patch.object(adapter, "prepare_game", return_value=Path("unused")), + patch.object(adapter, "open_native", return_value=(native, native_observation())), + ): + game_adapter = adapter.Adapter(config) + config["initial_state_sha256"] = game_adapter.fingerprint() + with patch("server.Recorder.frame"): # PNG projection is covered below; no encoder needed here. + game = Game(game_adapter, config, output) + try: + yield game, config, native + finally: + game.close() + + +class TowerMindContract(unittest.TestCase): + def test_gym_bridge_can_load_offline(self): + with patch("urllib.request.urlopen", side_effect=AssertionError("unexpected runtime download")): + from native import load_gym_bridge + + self.assertEqual(load_gym_bridge().__name__, "UnityToGymWrapper") + + def test_explicit_reset_routes_image_and_text_to_the_official_wrapper(self): + import native + + unity = native.LocalUnity.__new__(native.LocalUnity) + player_frame = native_observation()["image"] + payloads = iter((None, ["text texture", player_frame, "private vector"])) + unity.get_steps = lambda _: ([object()], []) + + def receive_reset(player): + player.payload = next(payloads) + + class GymBridge: + name = "tower-defender" + group_spec = SimpleNamespace(observation_specs=[ + SimpleNamespace(name="VectorSensor", shape=(32,)), + SimpleNamespace(name="RenderTextureSensor", shape=(128, 128, 3)), + SimpleNamespace(name="CameraSensor", shape=player_frame.shape), + ]) + + def __init__(self, player, **_): + self.player = player + player.reset() + + def reset(self): + self.player.reset() + return self.player.payload + + class Modalities: + def __init__(self, gym, **flags): + self.gym = gym + self.flags = flags + + def _convert_obs(self, observation): + return {"image": observation[0], "text": observation[1]} + + def reset(self): + return self._convert_obs(self.gym.reset()) + + wrappers = SimpleNamespace( + TowerMindMultiModalObsWrapper=Modalities, + TowerMindActionMappingWrapper=lambda env: env, + ) + with ( + patch.object(native, "LocalUnity", return_value=unity) as launch, + patch.object(native, "load_gym_bridge", return_value=GymBridge), + patch.object(native, "load_source", return_value=wrappers), + patch.object(native.UnityEnvironment, "reset", autospec=True, side_effect=receive_reset) as reset, + ): + env, initial = native.open_native(Path("td.x86_64"), Path("wrappers.py")) + self.assertNotIn("seed", launch.call_args.kwargs) + self.assertEqual(env.flags, {"use_image": True, "use_text": True, "use_state": False}) + self.assertEqual(set(initial), {"image", "text"}) + self.assertIs(initial["image"], player_frame) + self.assertEqual(initial["text"], "text texture") + with self.assertRaisesRegex(RuntimeError, "one episode"): + env.reset() + self.assertEqual(reset.call_count, 2) + + def test_missing_or_ambiguous_native_sensor_fails_closed(self): + from native import multimodal_observations + + other = SimpleNamespace(name="RenderTextureSensor", shape=(512, 512, 3)) + camera = SimpleNamespace(name="CameraSensor", shape=(512, 512, 3)) + for specs in ([other], [camera], [camera, camera, other], [camera, other, other]): + gym = SimpleNamespace(group_spec=SimpleNamespace(observation_specs=specs)) + with self.subTest(specs=specs), self.assertRaisesRegex(ValueError, "expected one"): + multimodal_observations(gym, None) + + def test_text_decode_diagnostic_omits_private_data(self): + from native import multimodal_observations + + class Modalities: + def __init__(self, _, **flags): + pass + + def _convert_obs(self, observation): + raise JSONDecodeError("invalid", "hidden-wave-sentinel", 0) + + specs = [ + SimpleNamespace(name="CameraSensor", shape=(3, 512, 512)), + SimpleNamespace(name="RenderTextureSensor", shape=(3, 128, 128)), + ] + gym = SimpleNamespace(group_spec=SimpleNamespace(observation_specs=specs)) + env = multimodal_observations(gym, SimpleNamespace(TowerMindMultiModalObsWrapper=Modalities)) + with self.assertRaisesRegex(ValueError, "offset 0, decoded length 20") as error: + env._convert_obs([None, None]) + self.assertNotIn("hidden-wave-sentinel", str(error.exception)) + + def test_schema_rejects_drift(self): + config = instance() + self.assertEqual(config["engine_archive_sha256"], ARCHIVE_SHA256) + validate_instance(config) + for update in ({"seed": 0}, {"level_id": 9}, {"engine_archive_sha256": "1" * 64}, + {"observation_profile": "unfiltered-json"}, {"hidden_field": True}): + with self.subTest(update=update), self.assertRaises(ValueError): + validate_instance(dict(config, **update)) + + def test_rgb_is_only_public_observation_and_reading_is_pure(self): + with session("completed") as (game, config, native): + before = game.adapter.fingerprint() + self.assertEqual(game.spec()["reset_budget"], 0) + observation = game.observe()["observation"] + self.assertEqual(set(observation), {"image_png_base64"}) + with Image.open(BytesIO(base64.b64decode(observation["image_png_base64"]))) as image: + self.assertEqual((image.mode, image.size, image.getpixel((0, 0))), ("RGB", (512, 512), (91, 91, 91))) + self.assertEqual(game.observe()["observation"], observation) + self.assertEqual(game.adapter.fingerprint(), before) + self.assertEqual(native.actions, []) + self.assertNotIn("hidden-wave-sentinel", str(game.spec())) + self.assertNotIn(config["engine_archive_sha256"], str(game.spec())) + self.assertTrue(native.closed) + + def test_server_rejects_malformed_action_before_game_moves(self): + with session("completed") as (game, _, native): + for action in ("reset", "3.01 0 1", "0 0 12", "nan 0 0", "0 0 0\n", "0 0 1", [0, 0, 0]): + with self.subTest(action=action), self.assertRaises(InvalidAction): + game.submit({"action": action, "expected_step": 0, "request_id": "bad"}) + self.assertEqual((game.steps, native.actions), (0, [])) + + def test_native_outcomes_and_public_early_stop_are_distinct(self): + for outcome, reason, success, score in ( + ("completed", "native_terminated", True, 0.0), + ("destroyed", "native_terminated", False, -20.0), + ("interrupted", "native_truncated", False, 0.0), + ("early", "agent_finished", False, 0.0), + ): + with self.subTest(outcome=outcome), session(outcome) as (game, config, native): + if outcome == "early": + game.finalize("agent_finished") + else: + action = {"action": "-3.000000000 3.000000000 11", "expected_step": 0, "request_id": "legal"} + self.assertTrue(game.submit(action)["done"]) + self.assertTrue(game.submit(action)["done"]) # duplicate must not execute again + self.assertEqual(native.actions, [(-3.0, 3.0, 11)]) + result = grade(game.final, config, validate_metrics) + self.assertEqual((result["reason"], result["primary_score"]), (reason, score)) + self.assertEqual(game.final["success"], success) + + def test_native_reward_and_reported_action_outcome_are_independent(self): + with session("feedback") as (game, config, _): + game.submit({"action": "0 0 2", "expected_step": 0, "request_id": "mixed"}) + self.assertEqual(grade(game.final, config, validate_metrics)["primary_score"], float(np.float32(-1.01))) + self.assertEqual(game.final["metrics"]["base_health"], 20) + self.assertEqual(game.final["metrics"]["native_counted_actions"], 1) + self.assertEqual(game.final["metrics"]["native_invalid_actions"], 1) + game.final["metrics"]["native_invalid_actions"] = 2 + with self.assertRaisesRegex(ValueError, "action counts"): + validate_metrics(game.final, config) + + def test_no_op_is_excluded_from_native_action_counts(self): + with session("completed") as (game, _, _): + game.submit({"action": "0 0 6", "expected_step": 0, "request_id": "no-op"}) + self.assertEqual(game.final["metrics"]["native_counted_actions"], 0) + self.assertEqual(game.final["metrics"]["native_invalid_actions"], 0) + + def test_nonfinite_native_reward_invalidates_attempt(self): + with session("nonfinite_reward") as (game, _, _): + with self.assertRaises(EnvironmentFault): + game.submit({"action": "0 0 6", "expected_step": 0, "request_id": "reward-drift"}) + self.assertEqual(game.final["reason"], "environment_error") + self.assertFalse(game.final["result_valid"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/game_first_exam/tests/test_towermind_native.py b/game_first_exam/tests/test_towermind_native.py new file mode 100644 index 0000000..777dd60 --- /dev/null +++ b/game_first_exam/tests/test_towermind_native.py @@ -0,0 +1,136 @@ +"""Native equivalence and timing checks for the pinned TowerMind Linux player.""" +import os +import socket +from json import JSONDecodeError +from pathlib import Path +from tempfile import TemporaryDirectory +import time +import unittest +from unittest.mock import patch + +import numpy as np +from mlagents_envs.environment import UnityEnvironment +from mlagents_envs.side_channel.engine_configuration_channel import EngineConfigurationChannel + +from towermind_fixture import instance +from adapter import Adapter, NATIVE_ASSETS +from native import NO_OP, RPC_PORT, load_gym_bridge, load_source +from native_assets import prepare_game +from metric_rules import validate_metrics +from server import Game + + +COMMANDS = [("0 0 6", NO_OP), ("-1.5 1.2 2", (-1.5, 1.2, 2))] * 6 +MAX_REFERENCE_DECISIONS = 4096 + + +class TowerMindNative(unittest.TestCase): + def test_01_upstream_reference_matches_the_adapter_through_termination(self): + config = instance() + with TemporaryDirectory() as workspace: + prepare_game(NATIVE_ASSETS, Path(workspace), config) + player = Path(workspace) / "linux/td.x86_64" + # Run the official LLM example's Gym sequence without a model. + # This reference uses plain UnityEnvironment and both stock wrappers. + wrappers = load_source("_towermind_reference_wrappers", NATIVE_ASSETS / "wrappers.py") + settings = EngineConfigurationChannel() + settings.set_configuration_parameters(target_frame_rate=-1, time_scale=20.0, capture_frame_rate=60) + # The reference starts the stock executable directly under the same Mesa profile. + mesa = "-GL_EXT_texture_filter_anisotropic -GL_ARB_texture_filter_anisotropic" + with patch.dict(os.environ, {"MESA_EXTENSION_OVERRIDE": mesa}): + unity = UnityEnvironment(file_name=str(player), side_channels=[settings], + timeout_wait=60, log_folder=str(player.parent)) + try: + bridge = load_gym_bridge()(unity, uint8_visual=True, allow_multiple_obs=True) + observations = wrappers.TowerMindMultiModalObsWrapper( + bridge, use_image=True, use_text=True, use_state=False + ) + env = wrappers.TowerMindActionMappingWrapper(observations) + try: + initial = env.reset() + except JSONDecodeError as error: + specs = [(spec.name, spec.shape) for spec in bridge.group_spec.observation_specs] + self.fail( + f"stock TowerMind LLM wrappers failed during reset before Game Exam: " + f"JSON offset {error.pos}, decoded length {len(error.doc)}, sensors {specs}" + ) + self.assertEqual(set(initial), {"image", "text"}) + expected = [] + for index in range(MAX_REFERENCE_DECISIONS): + command, action = COMMANDS[index] if index < len(COMMANDS) else ("0 0 6", NO_OP) + observation, reward, done, info = env.step(action) + interrupted = info["step"].interrupted[0] if done else False + status = observation["text"] + expected.append((command, float(reward), bool(done), bool(interrupted), + status["Level_Current_Health"], status["Agent_Last_Action_Info"])) + if done: + break + self.assertTrue(done, "expected a native ending within the reference decision cap") + finally: + if unity._loaded: + unity.close() + + adapter = Adapter(config) + try: + with socket.create_connection(("127.0.0.1", RPC_PORT), timeout=2): + pass + initial_frame = initial["image"] + if initial_frame.shape == (3, 512, 512): + initial_frame = initial_frame.transpose(1, 2, 0) + self.assertEqual(adapter.frame().shape, initial_frame.shape) + self.assertEqual(adapter.frame().dtype, np.uint8) + self.assertGreater(np.ptp(adapter.frame()), 0, "expected a rendered player camera") + reference_return = 0.0 + counted = invalid = 0 + for index, (command, reward, done, interrupted, health, outcome) in enumerate(expected): + if index in (0, 1, 5): + before = adapter.fingerprint() + adapter.spec() + adapter.observe() + adapter.frame() + time.sleep(1) + adapter.observe() + self.assertEqual(adapter.fingerprint(), before) + transition = adapter.step(command) + self.assertEqual( + (transition.reward, transition.terminated, transition.truncated), + (reward, done and not interrupted, interrupted), + f"decision {index + 1}", + ) + self.assertEqual(adapter.metrics()["base_health"], health, f"base health at decision {index + 1}") + reference_return += reward + if outcome["Action_Index"] != 6: + counted += 1 + invalid += int(outcome["Error_Code"] > 0) + metrics = adapter.metrics() + self.assertEqual(metrics["native_return"], reference_return) + self.assertEqual(metrics["base_health"], health) + self.assertEqual(metrics["native_counted_actions"], counted) + self.assertEqual(metrics["native_invalid_actions"], invalid) + print(f"Stock and adapted TowerMind matched through {len(expected)} decisions, return {reference_return}.") + with self.assertRaisesRegex(ValueError, "episode closed"): + adapter.step("0 0 6") + finally: + adapter.close() + + def test_public_service_keeps_native_result_on_a_budget_stop(self): + config = instance() + config["max_steps"] = 1 + adapter = Adapter(config) + config["initial_state_sha256"] = adapter.fingerprint() + with TemporaryDirectory() as directory: + game = Game(adapter, config, directory) + try: + reply = game.submit({"action": "0 0 0", "expected_step": 0, "request_id": "native-first"}) + self.assertTrue(reply["done"]) + self.assertEqual(set(reply["observation"]), {"image_png_base64"}) + self.assertEqual(game.final["reason"], "step_limit") + self.assertFalse(game.final["success"]) + validate_metrics(game.final, config) + self.assertIsNone(game.recorder.error) + finally: + game.close() + + +if __name__ == "__main__": + unittest.main() diff --git a/game_first_exam/tests/towermind_fixture.py b/game_first_exam/tests/towermind_fixture.py new file mode 100644 index 0000000..1f65e93 --- /dev/null +++ b/game_first_exam/tests/towermind_fixture.py @@ -0,0 +1,52 @@ +"""Development instance for tests only. No task or suite registration.""" +import json +from pathlib import Path +import sys + + +ROOT = Path(__file__).resolve().parents[2] +RUNTIME = ROOT / "game_first_exam/runtime" +BENCHMARK = ROOT / "game_first_exam/benchmarks/towermind" +sys.path[:0] = [str(RUNTIME), str(BENCHMARK)] + +import instance_schema +from config_schema import register_instance_schema + + +register_instance_schema(instance_schema) + + +def instance(): + return json.loads((Path(__file__).parent / "fixtures/towermind-instance.json").read_text()) + + +def serve(): + """Launch the real public HTTP handler with a development instance for the peer-container probe.""" + from http.server import HTTPServer + import signal + from tempfile import TemporaryDirectory + + from adapter import Adapter + from server import Game, Handler + + def stop(*_): + raise SystemExit(0) + + signal.signal(signal.SIGTERM, stop) + config = instance() + with TemporaryDirectory() as directory: + adapter = Adapter(config) + config["initial_state_sha256"] = adapter.fingerprint() + game = Game(adapter, config, directory, wall_clock=180) + try: + if game.final is not None: + raise RuntimeError("TowerMind development simulator initialization failed") + with HTTPServer(("0.0.0.0", 8000), Handler) as server: + server.game = game + server.serve_forever() + finally: + game.close() + + +if __name__ == "__main__": + serve() diff --git a/game_first_exam/tests/towermind_probe.py b/game_first_exam/tests/towermind_probe.py new file mode 100644 index 0000000..5c9c906 --- /dev/null +++ b/game_first_exam/tests/towermind_probe.py @@ -0,0 +1,35 @@ +"""Exercise the public interface from a container built with only client-side files.""" +import base64 +from pathlib import Path +import socket + +from game_client import GameClient + + +def main(): + client = GameClient(url="http://sim:8000", startup_timeout=120) + spec = client.spec() + assert spec["reset_budget"] == 0 + assert "seed" not in spec and "engine_archive_sha256" not in spec + obs = client.observe() + assert set(obs["observation"]) == {"image_png_base64"} + assert obs["step"] == 0 + assert base64.b64decode(obs["observation"]["image_png_base64"], validate=True).startswith(b"\x89PNG\r\n\x1a\n") + try: + with socket.create_connection(("sim", 5005), timeout=3): + raise AssertionError("the simulator's loopback RPC port is reachable from the client") + except (ConnectionRefusedError, TimeoutError): + pass + for private_path in ("/opt/towermind", "/repo", "/data"): + assert not Path(private_path).exists(), f"unexpected sim path in client: {private_path}" + # Debian supplies an empty /srv in the base image. No simulator files belong there. + service_dir = Path("/srv") + assert not service_dir.exists() or not any(service_dir.iterdir()), "simulator files in client /srv" + obs = client.step("0 0 0", expected_step=0) + assert obs["step"] == 1 + assert set(obs["observation"]) == {"image_png_base64"} + print("TowerMind public HTTP is usable, with the RPC listener and native assets confined to the simulator") + + +if __name__ == "__main__": + main()