From 9a8ebc0164aec1b123c6d3ee5fe80b68991e7e90 Mon Sep 17 00:00:00 2001 From: maomao868 <196136225+maomao868@users.noreply.github.com> Date: Fri, 20 Nov 2026 06:20:15 -0800 Subject: [PATCH 01/17] Add TowerMind benchmark adapter and isolation tests --- .github/workflows/games.yml | 12 +- .../benchmarks/towermind/README.md | 18 +++ .../benchmarks/towermind/SOURCE.json | 14 ++ .../benchmarks/towermind/adapter.py | 127 ++++++++++++++++++ .../benchmarks/towermind/instance_schema.py | 36 +++++ .../benchmarks/towermind/metric_rules.py | 19 +++ .../benchmarks/towermind/native.py | 96 +++++++++++++ .../benchmarks/towermind/native_assets.py | 68 ++++++++++ .../benchmarks/towermind/requirements.txt | 17 +++ .../images/towermind-files/FILES.json | 13 ++ .../images/towermind-files/README.md | 3 + .../images/towermind-files/VERSION | 1 + .../tests/check-towermind-network.sh | 17 +++ game_first_exam/tests/envs/README.md | 2 +- .../tests/envs/towermind.Dockerfile | 28 ++++ game_first_exam/tests/run.sh | 4 + .../tests/test_towermind_contract.py | 125 +++++++++++++++++ .../tests/test_towermind_native.py | 108 +++++++++++++++ game_first_exam/tests/towermind_fixture.py | 63 +++++++++ game_first_exam/tests/towermind_probe.py | 32 +++++ 20 files changed, 800 insertions(+), 3 deletions(-) create mode 100644 game_first_exam/benchmarks/towermind/README.md create mode 100644 game_first_exam/benchmarks/towermind/SOURCE.json create mode 100644 game_first_exam/benchmarks/towermind/adapter.py create mode 100644 game_first_exam/benchmarks/towermind/instance_schema.py create mode 100644 game_first_exam/benchmarks/towermind/metric_rules.py create mode 100644 game_first_exam/benchmarks/towermind/native.py create mode 100644 game_first_exam/benchmarks/towermind/native_assets.py create mode 100644 game_first_exam/benchmarks/towermind/requirements.txt create mode 100644 game_first_exam/images/towermind-files/FILES.json create mode 100644 game_first_exam/images/towermind-files/README.md create mode 100644 game_first_exam/images/towermind-files/VERSION create mode 100644 game_first_exam/tests/check-towermind-network.sh create mode 100644 game_first_exam/tests/envs/towermind.Dockerfile create mode 100644 game_first_exam/tests/test_towermind_contract.py create mode 100644 game_first_exam/tests/test_towermind_native.py create mode 100644 game_first_exam/tests/towermind_fixture.py create mode 100644 game_first_exam/tests/towermind_probe.py diff --git a/.github/workflows/games.yml b/.github/workflows/games.yml index ebee4f6..1869623 100644 --- a/.github/workflows/games.yml +++ b/.github/workflows/games.yml @@ -25,12 +25,20 @@ 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 harbor: runs-on: ubuntu-latest timeout-minutes: 15 diff --git a/game_first_exam/benchmarks/towermind/README.md b/game_first_exam/benchmarks/towermind/README.md new file mode 100644 index 0000000..67d9643 --- /dev/null +++ b/game_first_exam/benchmarks/towermind/README.md @@ -0,0 +1,18 @@ +# TowerMind adapter + +This development integration uses the upstream Unity Linux x86-64 player and the two official TowerMind wrappers. `SOURCE.json` pins the archive and wrapper source by commit and SHA256. The simulator extracts its own copy, selects an original benchmark level and a positive seed, keeps the native 16-step decision interval, disables automatic level progression and retries, and selects the native sparse reward. The pinned Unity Gym bridge reuses its startup reset as the initial decision. 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. Structured observations, raw step metadata, configuration, seed and fingerprints stay inside the simulator. The fingerprint covers the cached native JSON, instance identity and step outcomes. Unity's full state and RNG checkpoint are unavailable. + +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 and uses Xvfb with software OpenGL for rendering. 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. A test-only instance drives native equivalence, idle interval and first-episode checks. Benchmark discovery for model evaluation will be added with a frozen task. + +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..3832dfa --- /dev/null +++ b/game_first_exam/benchmarks/towermind/adapter.py @@ -0,0 +1,127 @@ +"""Expose one cached player RGB frame and one native decision per accepted action.""" +from importlib.metadata import version +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, seed): + from native import open_native as launch + + return launch(player, wrappers_path, seed) + + +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._terminated = self._truncated = False + source = NATIVE_ASSETS if assets is None or not (assets / "linux.zip").is_file() else assets + try: + player, self._initial_health = prepare_game(source, Path(self._workspace.name), instance) + self._env, observation = open_native(player, source / "wrappers.py", instance["seed"]) + self._cache(observation) + if self._health != self._initial_health: + raise ValueError("unexpected starting base health") + except Exception: + self.close() + raise + + def _cache(self, observation): + 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._public_png = png(self._image) + self._state = observation["text"] + self._health = self._state["Level_Current_Health"] + if type(self._health) is not int or not 0 <= self._health <= self._initial_health: + raise ValueError("invalid native base health") + + 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)) + 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 += float(reward) + self._cache(observation) + return Transition(float(reward), self._terminated, self._truncated) + + def success(self): + # The native level ends when the base is destroyed or all attackers are resolved. + return self._terminated and self._health > 0 + + def metrics(self): + return { + "native_success": int(self.success()), + "native_return": self._return, + "initial_base_health": self._initial_health, + "base_health": self._health, + "native_decisions": self._decisions, + } + + 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"], + "state": self._state, "decisions": self._decisions, "return": self._return, + "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..98d2f49 --- /dev/null +++ b/game_first_exam/benchmarks/towermind/instance_schema.py @@ -0,0 +1,36 @@ +"""Trusted adapter profile. Importable without simulator dependencies.""" +from config_schema import validate_engine_versions +from contracts import Capabilities + + +SCHEMA_VERSION = "1.0.0" +BENCHMARK = "towermind" +FIELDS = {"level_id", "engine_versions", "engine_archive_sha256"} +METRICS = {"native_success"} +PROFILES = {"player-rgb-v1"} +REDUCERS = {("family_macro", "1.0.0")} +CAPABILITIES = Capabilities(images=True, action_mode="text", native_truncation=True).to_dict() +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..58fd09b --- /dev/null +++ b/game_first_exam/benchmarks/towermind/metric_rules.py @@ -0,0 +1,19 @@ +"""Validate native outcome evidence without loading Unity.""" +import math + + +def validate_metrics(final, instance): + metrics = final["metrics"] + health, initial = metrics["base_health"], metrics["initial_base_health"] + if type(health) is not int or type(initial) is not int or not 0 <= health <= initial or initial < 1: + 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 not math.isclose(reward, final["return"], abs_tol=1e-8): + raise ValueError("TowerMind cumulative return disagrees with the service") + if not math.isclose(reward, health - initial, abs_tol=1e-8): + raise ValueError("TowerMind sparse return disagrees with base health") + won = final["reason"] == "native_terminated" and health > 0 + if type(metrics["native_success"]) is not int or metrics["native_success"] != int(won) or 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..56b21dd --- /dev/null +++ b/game_first_exam/benchmarks/towermind/native.py @@ -0,0 +1,96 @@ +"""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 + +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 + + +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 + _initial_reset_done = False + + @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") + # Gym may first step to discover behavior specs, which itself calls reset. + if not self._initial_reset_done: + super().reset() + self._initial_reset_done = True + + +def open_native(player, wrappers_path, seed): + """Use the Gym constructor's native reset as the initial 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), seed=seed, base_port=RPC_PORT, timeout_wait=60, + side_channels=[channel], additional_args=["-batchmode", "-force-glcore"], + log_folder=str(player.parent), + ) + try: + gym = gym_wrapper(unity, uint8_visual=True, allow_multiple_obs=True) + unity._initializing = False + decision, terminal = unity.get_steps(gym.name) + if len(decision) != 1 or len(terminal): + raise ValueError("unexpected TowerMind initial decision") + raw_observation, _, _, _ = gym._single_step(decision) + modalities = wrappers.TowerMindMultiModalObsWrapper( + gym, use_image=True, use_text=True, use_state=False + ) + initial = modalities._convert_obs(raw_observation) + return wrappers.TowerMindActionMappingWrapper(modalities), 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..3c947f2 --- /dev/null +++ b/game_first_exam/benchmarks/towermind/native_assets.py @@ -0,0 +1,68 @@ +"""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")) + if settings["DecisionPeriod"] != 16: + raise ValueError("unexpected native decision period") + levels_path = configs / "BenchmarkLevelsConfig.json" + levels = json.loads(levels_path.read_text(encoding="utf-8"))["Levels"] + level, = (row for row in levels if row["ID"] == instance["level_id"]) + settings.update( + GeneralizationLevel=0, LevelsConfigFileName=levels_path.name, + RandomSeed=instance["seed"], IsAutoPlayLevels=1, IsRepeatFailingLevels=0, + IsHumanPlayerPlaying=0, IsDrlReward=0, IsDebug=0, IsRecordingEnabled=0, + IsOnlyPixelObs=0, NeedsNaturalLanguageObservation=0, + NeedsRealtimeLanguageObservation=0, + ) + settings_path.write_text(json.dumps(settings), encoding="utf-8") + (configs / "FixedLevelsConfig.json").write_text( + json.dumps({"CurrentLevel": instance["level_id"]}), encoding="utf-8" + ) + return player, level["TotalLife"] + + +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..a129800 --- /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.0@sha256:1ae7467e975684e69252f8dc30b5f861ff7f8e98daffda9f827d4564a64cc8e8", + "source": "game_first_exam/benchmarks/towermind", + "files": { + "adapter.py": "9d2841610a00e0ce632021f51013f427950d178f77d2d76884ee2e9cb44db17c", + "instance_schema.py": "6103859ea8ce74a0bd6ee9c234e9eb58d912314bbb19b1b5aa89d9e5f96d065f", + "metric_rules.py": "8111b52f913a6fc7b893879ca9479f923aa813d301f5918a21fa0b10883671a3", + "native.py": "8f267cca75b08e90f56e354e20c4db9891030829add84c3e7ec6862a00c9c2ff", + "native_assets.py": "14116a2024bbfc2327fff6faa8b273e9fd4d794da399cb11616e962884a10a63", + "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..6e8bf73 --- /dev/null +++ b/game_first_exam/images/towermind-files/VERSION @@ -0,0 +1 @@ +0.1.0 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..f0e98bd --- /dev/null +++ b/game_first_exam/tests/check-towermind-network.sh @@ -0,0 +1,17 @@ +#!/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 --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 logs "$sim" + exit 1 +fi 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..7098a19 --- /dev/null +++ b/game_first_exam/tests/envs/towermind.Dockerfile @@ -0,0 +1,28 @@ +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 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/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", "python", "game_first_exam/tests/towermind_fixture.py"] diff --git a/game_first_exam/tests/run.sh b/game_first_exam/tests/run.sh index a033e85..047a8de 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 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_towermind_contract.py b/game_first_exam/tests/test_towermind_contract.py new file mode 100644 index 0000000..7c475ae --- /dev/null +++ b/game_first_exam/tests/test_towermind_contract.py @@ -0,0 +1,125 @@ +"""Verify the public projection, action validation and grading without launching Unity.""" +import base64 +from contextlib import contextmanager +from io import BytesIO +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 Game, InvalidAction + + +def native_observation(health, shade=91): + return { + "image": np.full((512, 512, 3), shade, dtype=np.uint8), + "text": {"Level_Current_Health": health, "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 + return native_observation(health, 92), health - 20, 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"), 20)), + patch.object(adapter, "open_native", return_value=(native, native_observation(20))), + ): + 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_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 in ( + ("completed", "native_terminated", 1), + ("destroyed", "native_terminated", 0), + ("interrupted", "native_truncated", 0), + ("early", "agent_finished", 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, success)) + + +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..95766eb --- /dev/null +++ b/game_first_exam/tests/test_towermind_native.py @@ -0,0 +1,108 @@ +"""Native equivalence and timing checks for the pinned TowerMind Linux player.""" +import socket +from pathlib import Path +from tempfile import TemporaryDirectory +import time +import unittest + +import numpy as np + +from towermind_fixture import instance +from adapter import Adapter, NATIVE_ASSETS +from native import RPC_PORT, open_native +from native_assets import prepare_game +from metric_rules import validate_metrics +from server import Game + + +COMMANDS = [("0 0 0", (0.0, 0.0, 0)), ("-1.5 1.2 2", (-1.5, 1.2, 2))] * 6 + + +def native_snapshot(observation, reward, done, interrupted): + return observation["text"], float(reward), bool(done), bool(interrupted) + + +class TowerMindNative(unittest.TestCase): + def test_native_trajectory_and_idle_intervals(self): + config = instance() + with TemporaryDirectory() as workspace: + player, _ = prepare_game(NATIVE_ASSETS, Path(workspace), config) + env, initial = open_native(player, NATIVE_ASSETS / "wrappers.py", config["seed"]) + try: + with self.assertRaisesRegex(RuntimeError, "one episode"): + env.reset() + with socket.create_connection(("127.0.0.1", RPC_PORT), timeout=2): + pass + expected = [] + for _, action in COMMANDS: + observation, reward, done, info = env.step(action) + interrupted = info["step"].interrupted[0] if done else False + expected.append(native_snapshot(observation, reward, done, interrupted)) + self.assertFalse(done) + finally: + env.close() + + adapter = Adapter(config) + try: + self.assertEqual(adapter._state, initial["text"]) + 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) + for index, ((command, _), item) in enumerate(zip(COMMANDS, expected)): + before = adapter.fingerprint() + adapter.spec() + adapter.observe() + adapter.frame() + if index in (1, 5): + time.sleep(1) + adapter.observe() + self.assertEqual(adapter.fingerprint(), before) + transition = adapter.step(command) + self.assertEqual( + (adapter._state, transition.reward, transition.terminated or transition.truncated, + transition.truncated), + item, + ) + finally: + adapter.close() + + def test_native_terminal_uses_first_episode(self): + config = instance() + adapter = Adapter(config) + try: + for _ in range(4096): + transition = adapter.step("0 0 0") + if transition.terminated or transition.truncated: + break + self.assertTrue(transition.terminated, "expected a native ending in development level 0") + metrics = adapter.metrics() + self.assertEqual(metrics["native_return"], metrics["base_health"] - metrics["initial_base_health"]) + self.assertEqual(adapter.success(), metrics["base_health"] > 0) + with self.assertRaisesRegex(ValueError, "episode closed"): + adapter.step("0 0 0") + finally: + adapter.close() + + def test_public_service_stops_without_awarding_completion(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..3625bab --- /dev/null +++ b/game_first_exam/tests/towermind_fixture.py @@ -0,0 +1,63 @@ +"""Development instance for tests only. No task or suite registration.""" +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 PROTOCOL, INSTANCE_SCHEMA, register_instance_schema + + +register_instance_schema(instance_schema) + + +def instance(): + return { + "schema_version": INSTANCE_SCHEMA, "protocol": PROTOCOL, "adapter_version": "1.0.0", + "capabilities": dict(instance_schema.CAPABILITIES), + "benchmark": "towermind", "env_id": "TowerMind-Level-0", "family": "development", + "level_id": 0, "seed": 42, "max_steps": None, "initial_state_sha256": "0" * 64, + "engine_versions": dict(instance_schema.ENGINE_VERSIONS), + "engine_archive_sha256": instance_schema.ARCHIVE_SHA256, + "observation_profile": "player-rgb-v1", + "metric_spec": { + "primary": "native_success", "success_label": "native_level_completed", + "reducer": "family_macro", "reducer_version": "1.0.0", + }, + } + + +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..a9adf54 --- /dev/null +++ b/game_first_exam/tests/towermind_probe.py @@ -0,0 +1,32 @@ +"""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", "/srv", "/data"): + assert not Path(private_path).exists(), f"unexpected sim path in client: {private_path}" + 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() From 25ba5845930d0ef48cd3cc5ff741b19487d6ef89 Mon Sep 17 00:00:00 2001 From: maomao868 <196136225+maomao868@users.noreply.github.com> Date: Fri, 20 Nov 2026 06:46:56 -0800 Subject: [PATCH 02/17] Read the TowerMind initial observation after the upstream reset --- .../benchmarks/towermind/README.md | 2 +- .../benchmarks/towermind/native.py | 23 ++++++----- .../images/towermind-files/FILES.json | 4 +- .../images/towermind-files/VERSION | 2 +- .../tests/test_towermind_contract.py | 38 +++++++++++++++++++ 5 files changed, 53 insertions(+), 16 deletions(-) diff --git a/game_first_exam/benchmarks/towermind/README.md b/game_first_exam/benchmarks/towermind/README.md index 67d9643..efe2a76 100644 --- a/game_first_exam/benchmarks/towermind/README.md +++ b/game_first_exam/benchmarks/towermind/README.md @@ -1,6 +1,6 @@ # TowerMind adapter -This development integration uses the upstream Unity Linux x86-64 player and the two official TowerMind wrappers. `SOURCE.json` pins the archive and wrapper source by commit and SHA256. The simulator extracts its own copy, selects an original benchmark level and a positive seed, keeps the native 16-step decision interval, disables automatic level progression and retries, and selects the native sparse reward. The pinned Unity Gym bridge reuses its startup reset as the initial decision. The adapter records the first native terminal or interrupted transition and closes the episode. +This development integration uses the upstream Unity Linux x86-64 player and the two official TowerMind wrappers. `SOURCE.json` pins the archive and wrapper source by commit and SHA256. The simulator extracts its own copy, selects an original benchmark level and a positive seed, keeps the native 16-step decision interval, disables automatic level progression and retries, and selects the native sparse reward. Initialization follows the upstream example and resets through the TowerMind wrappers after the Gym bridge has discovered its agent slots. The first playable observation starts the single 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. Structured observations, raw step metadata, configuration, seed and fingerprints stay inside the simulator. The fingerprint covers the cached native JSON, instance identity and step outcomes. Unity's full state and RNG checkpoint are unavailable. diff --git a/game_first_exam/benchmarks/towermind/native.py b/game_first_exam/benchmarks/towermind/native.py index 56b21dd..f7f11b5 100644 --- a/game_first_exam/benchmarks/towermind/native.py +++ b/game_first_exam/benchmarks/towermind/native.py @@ -53,7 +53,6 @@ def create_server(self): class LocalUnity(UnityEnvironment): _initializing = True - _initial_reset_done = False @staticmethod def _get_communicator(worker_id, base_port, timeout_wait): @@ -62,14 +61,11 @@ def _get_communicator(worker_id, base_port, timeout_wait): def reset(self): if not self._initializing: raise RuntimeError("TowerMind simulator supports one episode") - # Gym may first step to discover behavior specs, which itself calls reset. - if not self._initial_reset_done: - super().reset() - self._initial_reset_done = True + return super().reset() def open_native(player, wrappers_path, seed): - """Use the Gym constructor's native reset as the initial decision.""" + """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() @@ -81,16 +77,19 @@ def open_native(player, wrappers_path, seed): ) try: gym = gym_wrapper(unity, uint8_visual=True, allow_multiple_obs=True) + modalities = wrappers.TowerMindMultiModalObsWrapper( + gym, use_image=True, use_text=True, use_state=False + ) + env = wrappers.TowerMindActionMappingWrapper(modalities) + # UnityToGymWrapper resets during its constructor to inspect agent slots. + # TowerMind's example then resets the wrapped environment to obtain the + # playable observation. The constructor snapshot can have an empty JSON sensor. + 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") - raw_observation, _, _, _ = gym._single_step(decision) - modalities = wrappers.TowerMindMultiModalObsWrapper( - gym, use_image=True, use_text=True, use_state=False - ) - initial = modalities._convert_obs(raw_observation) - return wrappers.TowerMindActionMappingWrapper(modalities), initial + return env, initial except Exception: unity.close() raise diff --git a/game_first_exam/images/towermind-files/FILES.json b/game_first_exam/images/towermind-files/FILES.json index a129800..c6db6eb 100644 --- a/game_first_exam/images/towermind-files/FILES.json +++ b/game_first_exam/images/towermind-files/FILES.json @@ -1,11 +1,11 @@ { - "image": "ghcr.io/mll-lab-nu/efe:towermind-files-0.1.0@sha256:1ae7467e975684e69252f8dc30b5f861ff7f8e98daffda9f827d4564a64cc8e8", + "image": "ghcr.io/mll-lab-nu/efe:towermind-files-0.1.1@sha256:1bef518eb6bd32a4a0ff19b1281a9fd1be5992c419b6f296f07565fc7b39c650", "source": "game_first_exam/benchmarks/towermind", "files": { "adapter.py": "9d2841610a00e0ce632021f51013f427950d178f77d2d76884ee2e9cb44db17c", "instance_schema.py": "6103859ea8ce74a0bd6ee9c234e9eb58d912314bbb19b1b5aa89d9e5f96d065f", "metric_rules.py": "8111b52f913a6fc7b893879ca9479f923aa813d301f5918a21fa0b10883671a3", - "native.py": "8f267cca75b08e90f56e354e20c4db9891030829add84c3e7ec6862a00c9c2ff", + "native.py": "fe9b2eb76d8b8d6619c07e58146769687886a697db997bb24136cca1636fadc4", "native_assets.py": "14116a2024bbfc2327fff6faa8b273e9fd4d794da399cb11616e962884a10a63", "requirements.txt": "1dae4bbe8f73c36d8ef74c6b9fcd6eedc20a8a7ce239d8e247122ac01f54b43a", "SOURCE.json": "f1cd82c5b88d0095c0d3087ed5a7c5f76f2a8160414b199793d24ea378dad989" diff --git a/game_first_exam/images/towermind-files/VERSION b/game_first_exam/images/towermind-files/VERSION index 6e8bf73..17e51c3 100644 --- a/game_first_exam/images/towermind-files/VERSION +++ b/game_first_exam/images/towermind-files/VERSION @@ -1 +1 @@ -0.1.0 +0.1.1 diff --git a/game_first_exam/tests/test_towermind_contract.py b/game_first_exam/tests/test_towermind_contract.py index 7c475ae..34d1276 100644 --- a/game_first_exam/tests/test_towermind_contract.py +++ b/game_first_exam/tests/test_towermind_contract.py @@ -2,6 +2,7 @@ import base64 from contextlib import contextmanager from io import BytesIO +import json from pathlib import Path from tempfile import TemporaryDirectory from types import SimpleNamespace @@ -71,6 +72,43 @@ def test_gym_bridge_can_load_offline(self): self.assertEqual(load_gym_bridge().__name__, "UnityToGymWrapper") + def test_initial_decision_comes_from_explicit_reset_after_handshake(self): + import native + + unity = native.LocalUnity.__new__(native.LocalUnity) + payloads = iter(("", '{"Level_Current_Health": 20}')) + unity.get_steps = lambda _: ([object()], []) + + def receive_reset(player): + player.payload = next(payloads) + + class GymBridge: + name = "tower-defender" + + def __init__(self, player, **_): + self.player = player + player.reset() # Slot discovery sees an empty text sensor. + + def reset(self): + self.player.reset() + return {"text": json.loads(self.player.payload)} + + wrappers = SimpleNamespace( + TowerMindMultiModalObsWrapper=lambda gym, **_: gym, + TowerMindActionMappingWrapper=lambda env: env, + ) + with ( + patch.object(native, "LocalUnity", return_value=unity), + 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"), 42) + self.assertEqual(initial["text"]["Level_Current_Health"], 20) + with self.assertRaisesRegex(RuntimeError, "one episode"): + env.reset() + self.assertEqual(reset.call_count, 2) + def test_schema_rejects_drift(self): config = instance() self.assertEqual(config["engine_archive_sha256"], ARCHIVE_SHA256) From 148c230553f6739c4693d18cc7ba40ac9a51075f Mon Sep 17 00:00:00 2001 From: maomao868 <196136225+maomao868@users.noreply.github.com> Date: Fri, 20 Nov 2026 06:55:34 -0800 Subject: [PATCH 03/17] Handle blank TowerMind startup observations and pin the intended level --- .../benchmarks/towermind/README.md | 6 ++-- .../benchmarks/towermind/native.py | 30 +++++++++++++++++-- .../benchmarks/towermind/native_assets.py | 3 +- .../images/towermind-files/FILES.json | 6 ++-- .../images/towermind-files/VERSION | 2 +- .../tests/envs/towermind.Dockerfile | 4 +-- game_first_exam/tests/run.sh | 2 +- .../tests/test_towermind_contract.py | 28 ++++++++++++++++- .../tests/test_towermind_native.py | 8 ++--- 9 files changed, 71 insertions(+), 18 deletions(-) diff --git a/game_first_exam/benchmarks/towermind/README.md b/game_first_exam/benchmarks/towermind/README.md index efe2a76..cfd246d 100644 --- a/game_first_exam/benchmarks/towermind/README.md +++ b/game_first_exam/benchmarks/towermind/README.md @@ -1,12 +1,14 @@ # TowerMind adapter -This development integration uses the upstream Unity Linux x86-64 player and the two official TowerMind wrappers. `SOURCE.json` pins the archive and wrapper source by commit and SHA256. The simulator extracts its own copy, selects an original benchmark level and a positive seed, keeps the native 16-step decision interval, disables automatic level progression and retries, and selects the native sparse reward. Initialization follows the upstream example and resets through the TowerMind wrappers after the Gym bridge has discovered its agent slots. The first playable observation starts the single public episode. The adapter records the first native terminal or interrupted transition and closes the episode. +This development integration uses the upstream Unity Linux x86-64 player and the two official TowerMind wrappers. `SOURCE.json` pins the archive and wrapper source by commit and SHA256. The simulator extracts its own copy, selects an original benchmark level and a positive seed, keeps the native 16-step decision interval and selects the native sparse reward. For this pinned player, `IsAutoPlayLevels=0` selects the configured level and `1` cycles levels. Retries are off. + +Initialization resets through the TowerMind wrappers after the Gym bridge discovers its agent slots. The player writes its text texture during physics updates. If reset returns a blank text sensor, the simulator advances one native no-op decision (action 6) and requires a valid observation with zero reward and no termination. This advances the native clock before the public episode starts. The first playable observation starts the single 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. Structured observations, raw step metadata, configuration, seed and fingerprints stay inside the simulator. The fingerprint covers the cached native JSON, instance identity and step outcomes. Unity's full state and RNG checkpoint are unavailable. 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 and uses Xvfb with software OpenGL for rendering. 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. A test-only instance drives native equivalence, idle interval and first-episode checks. Benchmark discovery for model evaluation will be added with a frozen task. +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. 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. A test-only instance drives native equivalence, idle interval and first-episode checks. Benchmark discovery for model evaluation will be added with a frozen task. Run from the repository root on a Linux Docker host. diff --git a/game_first_exam/benchmarks/towermind/native.py b/game_first_exam/benchmarks/towermind/native.py index f7f11b5..2484d7b 100644 --- a/game_first_exam/benchmarks/towermind/native.py +++ b/game_first_exam/benchmarks/towermind/native.py @@ -2,6 +2,7 @@ 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 @@ -14,6 +15,7 @@ RPC_PORT = 5005 +NO_OP = (0.0, 0.0, 6) def load_source(name, path): @@ -64,6 +66,29 @@ def reset(self): return super().reset() +def first_observation(env): + try: + return env.reset() + except JSONDecodeError as exc: + if exc.doc.strip("\x00 \t\r\n"): + raise ValueError( + f"TowerMind reset returned invalid nonempty JSON ({len(exc.doc)} characters, offset {exc.pos})" + ) from exc + + # The pinned player writes its JSON texture in FixedUpdate, after reset may + # already have returned. Action 6 is its native no-op. Advance at most one + # decision here, before any actions or grading are exposed to the client. + try: + observation, reward, done, _ = env.step(NO_OP) + except JSONDecodeError as exc: + raise ValueError( + f"TowerMind JSON is invalid after one no-op startup decision ({len(exc.doc)} characters, offset {exc.pos})" + ) from exc + if done or float(reward) != 0.0: + raise ValueError("TowerMind startup decision ended the episode or changed its reward") + return observation + + def open_native(player, wrappers_path, seed): """Run the upstream startup sequence before exposing the first decision.""" gym_wrapper = load_gym_bridge() @@ -72,8 +97,7 @@ def open_native(player, wrappers_path, seed): channel.set_configuration_parameters(target_frame_rate=-1, time_scale=20.0, capture_frame_rate=60) unity = LocalUnity( file_name=str(player), seed=seed, base_port=RPC_PORT, timeout_wait=60, - side_channels=[channel], additional_args=["-batchmode", "-force-glcore"], - log_folder=str(player.parent), + side_channels=[channel], log_folder=str(player.parent), ) try: gym = gym_wrapper(unity, uint8_visual=True, allow_multiple_obs=True) @@ -84,7 +108,7 @@ def open_native(player, wrappers_path, seed): # UnityToGymWrapper resets during its constructor to inspect agent slots. # TowerMind's example then resets the wrapped environment to obtain the # playable observation. The constructor snapshot can have an empty JSON sensor. - initial = env.reset() + initial = first_observation(env) unity._initializing = False decision, terminal = unity.get_steps(gym.name) if len(decision) != 1 or len(terminal): diff --git a/game_first_exam/benchmarks/towermind/native_assets.py b/game_first_exam/benchmarks/towermind/native_assets.py index 3c947f2..29a48a0 100644 --- a/game_first_exam/benchmarks/towermind/native_assets.py +++ b/game_first_exam/benchmarks/towermind/native_assets.py @@ -52,7 +52,8 @@ def prepare_game(assets, workspace, instance): level, = (row for row in levels if row["ID"] == instance["level_id"]) settings.update( GeneralizationLevel=0, LevelsConfigFileName=levels_path.name, - RandomSeed=instance["seed"], IsAutoPlayLevels=1, IsRepeatFailingLevels=0, + # The pinned player cycles levels when IsAutoPlayLevels equals 1. + RandomSeed=instance["seed"], IsAutoPlayLevels=0, IsRepeatFailingLevels=0, IsHumanPlayerPlaying=0, IsDrlReward=0, IsDebug=0, IsRecordingEnabled=0, IsOnlyPixelObs=0, NeedsNaturalLanguageObservation=0, NeedsRealtimeLanguageObservation=0, diff --git a/game_first_exam/images/towermind-files/FILES.json b/game_first_exam/images/towermind-files/FILES.json index c6db6eb..d25deeb 100644 --- a/game_first_exam/images/towermind-files/FILES.json +++ b/game_first_exam/images/towermind-files/FILES.json @@ -1,12 +1,12 @@ { - "image": "ghcr.io/mll-lab-nu/efe:towermind-files-0.1.1@sha256:1bef518eb6bd32a4a0ff19b1281a9fd1be5992c419b6f296f07565fc7b39c650", + "image": "ghcr.io/mll-lab-nu/efe:towermind-files-0.1.2@sha256:37cec277d95a2b2f159f64cad5ecb6bb3c8c99d57c69340dbe65fa45fb17dbe0", "source": "game_first_exam/benchmarks/towermind", "files": { "adapter.py": "9d2841610a00e0ce632021f51013f427950d178f77d2d76884ee2e9cb44db17c", "instance_schema.py": "6103859ea8ce74a0bd6ee9c234e9eb58d912314bbb19b1b5aa89d9e5f96d065f", "metric_rules.py": "8111b52f913a6fc7b893879ca9479f923aa813d301f5918a21fa0b10883671a3", - "native.py": "fe9b2eb76d8b8d6619c07e58146769687886a697db997bb24136cca1636fadc4", - "native_assets.py": "14116a2024bbfc2327fff6faa8b273e9fd4d794da399cb11616e962884a10a63", + "native.py": "10c4fe522877be4556df3beba17c5222795e0f858d8b71b18385acdcfacf51b8", + "native_assets.py": "53ab1481a4c5b47a414015cdcc09bb6132a68cd322e052f72cce2123970d8798", "requirements.txt": "1dae4bbe8f73c36d8ef74c6b9fcd6eedc20a8a7ce239d8e247122ac01f54b43a", "SOURCE.json": "f1cd82c5b88d0095c0d3087ed5a7c5f76f2a8160414b199793d24ea378dad989" } diff --git a/game_first_exam/images/towermind-files/VERSION b/game_first_exam/images/towermind-files/VERSION index 17e51c3..d917d3e 100644 --- a/game_first_exam/images/towermind-files/VERSION +++ b/game_first_exam/images/towermind-files/VERSION @@ -1 +1 @@ -0.1.1 +0.1.2 diff --git a/game_first_exam/tests/envs/towermind.Dockerfile b/game_first_exam/tests/envs/towermind.Dockerfile index 7098a19..d09e609 100644 --- a/game_first_exam/tests/envs/towermind.Dockerfile +++ b/game_first_exam/tests/envs/towermind.Dockerfile @@ -12,7 +12,7 @@ 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 xauth xvfb \ + libxrender1 libvulkan1 mesa-vulkan-drivers xauth xvfb \ && rm -rf /var/lib/apt/lists/* ENV LIBGL_ALWAYS_SOFTWARE=1 HOME=/tmp WORKDIR /repo @@ -25,4 +25,4 @@ COPY game_first_exam/runtime/ /repo/game_first_exam/runtime/ 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", "python", "game_first_exam/tests/towermind_fixture.py"] +CMD ["xvfb-run", "-a", "-s", "-screen 0 1400x900x24", "python", "game_first_exam/tests/towermind_fixture.py"] diff --git a/game_first_exam/tests/run.sh b/game_first_exam/tests/run.sh index 047a8de..e0c6ca6 100755 --- a/game_first_exam/tests/run.sh +++ b/game_first_exam/tests/run.sh @@ -21,7 +21,7 @@ case "${1:-common}" in ;; towermind) python3 game_first_exam/tests/test_towermind_contract.py - xvfb-run -a python3 game_first_exam/tests/test_towermind_native.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" diff --git a/game_first_exam/tests/test_towermind_contract.py b/game_first_exam/tests/test_towermind_contract.py index 34d1276..37ef942 100644 --- a/game_first_exam/tests/test_towermind_contract.py +++ b/game_first_exam/tests/test_towermind_contract.py @@ -7,7 +7,7 @@ from tempfile import TemporaryDirectory from types import SimpleNamespace import unittest -from unittest.mock import patch +from unittest.mock import Mock, patch import numpy as np from PIL import Image @@ -109,6 +109,32 @@ def reset(self): env.reset() self.assertEqual(reset.call_count, 2) + def test_blank_startup_sensor_advances_one_native_no_op(self): + from native import first_observation + + env = Mock() + env.reset.side_effect = json.JSONDecodeError("Expecting value", "\x00" * 4, 0) + frame = native_observation(20) + env.step.return_value = (frame, 0.0, False, {}) + self.assertIs(first_observation(env), frame) + env.step.assert_called_once_with((0.0, 0.0, 6)) + env.reset.assert_called_once_with() + + def test_startup_rejects_corrupt_data_and_never_skips_a_terminal_or_reward(self): + from native import first_observation + + env = Mock() + env.reset.side_effect = json.JSONDecodeError("Expecting value", "corrupt", 0) + with self.assertRaisesRegex(ValueError, "invalid nonempty JSON"): + first_observation(env) + env.step.assert_not_called() + for reward, done in ((-1.0, False), (0.0, True)): + with self.subTest(reward=reward, done=done): + env.reset.side_effect = json.JSONDecodeError("Expecting value", "", 0) + env.step.return_value = (native_observation(20), reward, done, {}) + with self.assertRaisesRegex(ValueError, "startup decision ended"): + first_observation(env) + def test_schema_rejects_drift(self): config = instance() self.assertEqual(config["engine_archive_sha256"], ARCHIVE_SHA256) diff --git a/game_first_exam/tests/test_towermind_native.py b/game_first_exam/tests/test_towermind_native.py index 95766eb..43db152 100644 --- a/game_first_exam/tests/test_towermind_native.py +++ b/game_first_exam/tests/test_towermind_native.py @@ -9,13 +9,13 @@ from towermind_fixture import instance from adapter import Adapter, NATIVE_ASSETS -from native import RPC_PORT, open_native +from native import NO_OP, RPC_PORT, open_native from native_assets import prepare_game from metric_rules import validate_metrics from server import Game -COMMANDS = [("0 0 0", (0.0, 0.0, 0)), ("-1.5 1.2 2", (-1.5, 1.2, 2))] * 6 +COMMANDS = [("0 0 6", NO_OP), ("-1.5 1.2 2", (-1.5, 1.2, 2))] * 6 def native_snapshot(observation, reward, done, interrupted): @@ -73,7 +73,7 @@ def test_native_terminal_uses_first_episode(self): adapter = Adapter(config) try: for _ in range(4096): - transition = adapter.step("0 0 0") + transition = adapter.step("0 0 6") if transition.terminated or transition.truncated: break self.assertTrue(transition.terminated, "expected a native ending in development level 0") @@ -81,7 +81,7 @@ def test_native_terminal_uses_first_episode(self): self.assertEqual(metrics["native_return"], metrics["base_health"] - metrics["initial_base_health"]) self.assertEqual(adapter.success(), metrics["base_health"] > 0) with self.assertRaisesRegex(ValueError, "episode closed"): - adapter.step("0 0 0") + adapter.step("0 0 6") finally: adapter.close() From 2a55b9a4a383e3a53304af8d7c3b5753c9b45f2e Mon Sep 17 00:00:00 2001 From: maomao868 <196136225+maomao868@users.noreply.github.com> Date: Fri, 20 Nov 2026 07:06:05 -0800 Subject: [PATCH 04/17] Handle nonempty TowerMind startup frames and log both decode stages --- .../benchmarks/towermind/README.md | 2 +- .../benchmarks/towermind/native.py | 29 ++++++++-------- .../images/towermind-files/FILES.json | 4 +-- .../images/towermind-files/VERSION | 2 +- .../tests/test_towermind_contract.py | 33 ++++++++++++------- 5 files changed, 40 insertions(+), 30 deletions(-) diff --git a/game_first_exam/benchmarks/towermind/README.md b/game_first_exam/benchmarks/towermind/README.md index cfd246d..72cbad1 100644 --- a/game_first_exam/benchmarks/towermind/README.md +++ b/game_first_exam/benchmarks/towermind/README.md @@ -2,7 +2,7 @@ This development integration uses the upstream Unity Linux x86-64 player and the two official TowerMind wrappers. `SOURCE.json` pins the archive and wrapper source by commit and SHA256. The simulator extracts its own copy, selects an original benchmark level and a positive seed, keeps the native 16-step decision interval and selects the native sparse reward. For this pinned player, `IsAutoPlayLevels=0` selects the configured level and `1` cycles levels. Retries are off. -Initialization resets through the TowerMind wrappers after the Gym bridge discovers its agent slots. The player writes its text texture during physics updates. If reset returns a blank text sensor, the simulator advances one native no-op decision (action 6) and requires a valid observation with zero reward and no termination. This advances the native clock before the public episode starts. The first playable observation starts the single public episode. The adapter records the first native terminal or interrupted transition and closes the episode. +Initialization resets through the TowerMind wrappers after the Gym bridge discovers its agent slots. The player writes its text texture during physics updates. If the reset texture cannot be decoded as JSON, the simulator advances one native no-op decision (action 6) and requires a valid observation with zero reward and no termination. This advances the native clock before the public episode starts. If decoding fails again, startup fails and the diagnostic reports both stages without dumping the observations. The first playable observation starts the single 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. Structured observations, raw step metadata, configuration, seed and fingerprints stay inside the simulator. The fingerprint covers the cached native JSON, instance identity and step outcomes. Unity's full state and RNG checkpoint are unavailable. diff --git a/game_first_exam/benchmarks/towermind/native.py b/game_first_exam/benchmarks/towermind/native.py index 2484d7b..4616eeb 100644 --- a/game_first_exam/benchmarks/towermind/native.py +++ b/game_first_exam/benchmarks/towermind/native.py @@ -69,26 +69,27 @@ def reset(self): def first_observation(env): try: return env.reset() - except JSONDecodeError as exc: - if exc.doc.strip("\x00 \t\r\n"): + except JSONDecodeError as reset_error: + # The player writes its JSON texture in FixedUpdate. A reset can yield a + # nonempty texture before that write. Action 6 is the native no-op. + try: + observation, reward, done, _ = env.step(NO_OP) + except JSONDecodeError as step_error: raise ValueError( - f"TowerMind reset returned invalid nonempty JSON ({len(exc.doc)} characters, offset {exc.pos})" - ) from exc - - # The pinned player writes its JSON texture in FixedUpdate, after reset may - # already have returned. Action 6 is its native no-op. Advance at most one - # decision here, before any actions or grading are exposed to the client. - try: - observation, reward, done, _ = env.step(NO_OP) - except JSONDecodeError as exc: - raise ValueError( - f"TowerMind JSON is invalid after one no-op startup decision ({len(exc.doc)} characters, offset {exc.pos})" - ) from exc + "TowerMind JSON is invalid after one no-op startup decision " + f"(reset: {decode_error_summary(reset_error)}; no-op: {decode_error_summary(step_error)})" + ) from step_error if done or float(reward) != 0.0: raise ValueError("TowerMind startup decision ended the episode or changed its reward") return observation +def decode_error_summary(error): + # Report byte-level markers to trusted logs without dumping the observation. + prefix = ",".join(str(ord(character)) for character in error.doc[:4]) or "none" + return f"{len(error.doc)} characters, offset {error.pos}, first character codes [{prefix}]" + + def open_native(player, wrappers_path, seed): """Run the upstream startup sequence before exposing the first decision.""" gym_wrapper = load_gym_bridge() diff --git a/game_first_exam/images/towermind-files/FILES.json b/game_first_exam/images/towermind-files/FILES.json index d25deeb..dfb38fd 100644 --- a/game_first_exam/images/towermind-files/FILES.json +++ b/game_first_exam/images/towermind-files/FILES.json @@ -1,11 +1,11 @@ { - "image": "ghcr.io/mll-lab-nu/efe:towermind-files-0.1.2@sha256:37cec277d95a2b2f159f64cad5ecb6bb3c8c99d57c69340dbe65fa45fb17dbe0", + "image": "ghcr.io/mll-lab-nu/efe:towermind-files-0.1.3@sha256:123f5c92905638242edc226a642a36906206d21e7868fc5ac75506b79e47ca72", "source": "game_first_exam/benchmarks/towermind", "files": { "adapter.py": "9d2841610a00e0ce632021f51013f427950d178f77d2d76884ee2e9cb44db17c", "instance_schema.py": "6103859ea8ce74a0bd6ee9c234e9eb58d912314bbb19b1b5aa89d9e5f96d065f", "metric_rules.py": "8111b52f913a6fc7b893879ca9479f923aa813d301f5918a21fa0b10883671a3", - "native.py": "10c4fe522877be4556df3beba17c5222795e0f858d8b71b18385acdcfacf51b8", + "native.py": "07f3445a91ba59c9082ba900fa3f17f517000547ecb8305167ff93ead8721b56", "native_assets.py": "53ab1481a4c5b47a414015cdcc09bb6132a68cd322e052f72cce2123970d8798", "requirements.txt": "1dae4bbe8f73c36d8ef74c6b9fcd6eedc20a8a7ce239d8e247122ac01f54b43a", "SOURCE.json": "f1cd82c5b88d0095c0d3087ed5a7c5f76f2a8160414b199793d24ea378dad989" diff --git a/game_first_exam/images/towermind-files/VERSION b/game_first_exam/images/towermind-files/VERSION index d917d3e..b1e80bb 100644 --- a/game_first_exam/images/towermind-files/VERSION +++ b/game_first_exam/images/towermind-files/VERSION @@ -1 +1 @@ -0.1.2 +0.1.3 diff --git a/game_first_exam/tests/test_towermind_contract.py b/game_first_exam/tests/test_towermind_contract.py index 37ef942..452ffba 100644 --- a/game_first_exam/tests/test_towermind_contract.py +++ b/game_first_exam/tests/test_towermind_contract.py @@ -109,27 +109,36 @@ def reset(self): env.reset() self.assertEqual(reset.call_count, 2) - def test_blank_startup_sensor_advances_one_native_no_op(self): + def test_invalid_startup_sensor_advances_one_native_no_op(self): from native import first_observation - env = Mock() - env.reset.side_effect = json.JSONDecodeError("Expecting value", "\x00" * 4, 0) frame = native_observation(20) - env.step.return_value = (frame, 0.0, False, {}) - self.assertIs(first_observation(env), frame) - env.step.assert_called_once_with((0.0, 0.0, 6)) - env.reset.assert_called_once_with() - - def test_startup_rejects_corrupt_data_and_never_skips_a_terminal_or_reward(self): + for payload in ("\x00" * 4, "X" * 90): + with self.subTest(payload_length=len(payload)): + env = Mock() + env.reset.side_effect = json.JSONDecodeError("Expecting value", payload, 0) + env.step.return_value = (frame, 0.0, False, {}) + self.assertIs(first_observation(env), frame) + env.step.assert_called_once_with((0.0, 0.0, 6)) + env.reset.assert_called_once_with() + + def test_startup_aborts_after_a_single_invalid_no_op(self): from native import first_observation env = Mock() - env.reset.side_effect = json.JSONDecodeError("Expecting value", "corrupt", 0) - with self.assertRaisesRegex(ValueError, "invalid nonempty JSON"): + env.reset.side_effect = json.JSONDecodeError("Expecting value", "X" * 90, 0) + env.step.side_effect = json.JSONDecodeError("Expecting value", "bad sensor", 0) + with self.assertRaisesRegex(ValueError, "reset: 90 characters.*no-op: 10 characters") as failure: first_observation(env) - env.step.assert_not_called() + self.assertNotIn("bad sensor", str(failure.exception)) + env.step.assert_called_once_with((0.0, 0.0, 6)) + + def test_startup_never_skips_a_terminal_or_reward(self): + from native import first_observation + for reward, done in ((-1.0, False), (0.0, True)): with self.subTest(reward=reward, done=done): + env = Mock() env.reset.side_effect = json.JSONDecodeError("Expecting value", "", 0) env.step.return_value = (native_observation(20), reward, done, {}) with self.assertRaisesRegex(ValueError, "startup decision ended"): From 4661c0a70a40b7845c03ca2ee7170ef5b4281aae Mon Sep 17 00:00:00 2001 From: maomao868 <196136225+maomao868@users.noreply.github.com> Date: Fri, 20 Nov 2026 07:26:41 -0800 Subject: [PATCH 05/17] Use TowerMind pixel-only observations in the simulator --- .../benchmarks/towermind/README.md | 6 +- .../benchmarks/towermind/adapter.py | 37 ++++-- .../benchmarks/towermind/instance_schema.py | 4 + .../benchmarks/towermind/metric_rules.py | 10 +- .../benchmarks/towermind/native.py | 47 ++++---- .../benchmarks/towermind/native_assets.py | 6 +- .../images/towermind-files/FILES.json | 12 +- .../images/towermind-files/VERSION | 2 +- .../tests/test_towermind_contract.py | 108 ++++++++++-------- .../tests/test_towermind_native.py | 14 +-- 10 files changed, 139 insertions(+), 107 deletions(-) diff --git a/game_first_exam/benchmarks/towermind/README.md b/game_first_exam/benchmarks/towermind/README.md index 72cbad1..9334b70 100644 --- a/game_first_exam/benchmarks/towermind/README.md +++ b/game_first_exam/benchmarks/towermind/README.md @@ -2,9 +2,11 @@ This development integration uses the upstream Unity Linux x86-64 player and the two official TowerMind wrappers. `SOURCE.json` pins the archive and wrapper source by commit and SHA256. The simulator extracts its own copy, selects an original benchmark level and a positive seed, keeps the native 16-step decision interval and selects the native sparse reward. For this pinned player, `IsAutoPlayLevels=0` selects the configured level and `1` cycles levels. Retries are off. -Initialization resets through the TowerMind wrappers after the Gym bridge discovers its agent slots. The player writes its text texture during physics updates. If the reset texture cannot be decoded as JSON, the simulator advances one native no-op decision (action 6) and requires a valid observation with zero reward and no termination. This advances the native clock before the public episode starts. If decoding fails again, startup fails and the diagnostic reports both stages without dumping the observations. The first playable observation starts the single public episode. The adapter records the first native terminal or interrupted transition and closes the episode. +Initialization resets through the TowerMind wrappers after the Gym bridge discovers its agent slots. The player runs in upstream pixel-only mode (`IsOnlyPixelObs=1`). The bridge selects the 512×512 RGB `CameraSensor` by its reported name and dimensions. The public episode starts at the reset observation. 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. Structured observations, raw step metadata, configuration, seed and fingerprints stay inside the simulator. The fingerprint covers the cached native JSON, instance identity and step outcomes. Unity's full state and RNG checkpoint are unavailable. +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 adapter drops any separate text or vector observations before caching the camera frame. Raw step metadata, configuration, seed and fingerprints stay inside the simulator. The fingerprint covers the cached RGB pixels, instance identity and step outcomes. + +The pinned sparse reward charges 1 per base breach and 0.005 per reported action outcome. The adapter uses these increments and the configured starting health to track base health. It returns each native reward unchanged. Success requires the first native episode to terminate with the base still alive. 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. diff --git a/game_first_exam/benchmarks/towermind/adapter.py b/game_first_exam/benchmarks/towermind/adapter.py index 3832dfa..da8b745 100644 --- a/game_first_exam/benchmarks/towermind/adapter.py +++ b/game_first_exam/benchmarks/towermind/adapter.py @@ -1,5 +1,7 @@ """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 @@ -9,7 +11,7 @@ from config_schema import validate_instance from contracts import Transition from encoding import png, state_hash -from instance_schema import CAPABILITIES +from instance_schema import CAPABILITIES, DECISION_PERIOD, REWARD_TOLERANCE, REWARD_UNITS_PER_BREACH from native_assets import prepare_game @@ -43,14 +45,14 @@ def __init__(self, instance, assets=None): self._env = None self._decisions = 0 self._return = 0.0 + self._action_feedback_events = 0 self._terminated = self._truncated = False source = NATIVE_ASSETS if assets is None or not (assets / "linux.zip").is_file() else assets try: player, self._initial_health = prepare_game(source, Path(self._workspace.name), instance) + self._health = self._initial_health self._env, observation = open_native(player, source / "wrappers.py", instance["seed"]) self._cache(observation) - if self._health != self._initial_health: - raise ValueError("unexpected starting base health") except Exception: self.close() raise @@ -63,11 +65,8 @@ def _cache(self, observation): 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._state = observation["text"] - self._health = self._state["Level_Current_Health"] - if type(self._health) is not int or not 0 <= self._health <= self._initial_health: - raise ValueError("invalid native base health") def spec(self): return { @@ -85,13 +84,28 @@ 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) or reward > 0: + raise ValueError("invalid native TowerMind reward") + # The pinned sparse mode charges 1 per breach and 0.005 per action + # outcome. Each physics tick can process at most one tracked action. + units = round(-reward * REWARD_UNITS_PER_BREACH) + breaches, feedback = divmod(units, REWARD_UNITS_PER_BREACH) + if ( + breaches > self._health + or feedback > DECISION_PERIOD + or not math.isclose(-reward, units / REWARD_UNITS_PER_BREACH, rel_tol=0, abs_tol=REWARD_TOLERANCE) + ): + raise ValueError("unexpected native TowerMind reward increment") + self._cache(observation) + self._health -= breaches + self._action_feedback_events += feedback 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 += float(reward) - self._cache(observation) - return Transition(float(reward), self._terminated, self._truncated) + self._return += reward + return Transition(reward, self._terminated, self._truncated) def success(self): # The native level ends when the base is destroyed or all attackers are resolved. @@ -104,6 +118,7 @@ def metrics(self): "initial_base_health": self._initial_health, "base_health": self._health, "native_decisions": self._decisions, + "native_action_feedback_events": self._action_feedback_events, } def fingerprint(self): @@ -111,7 +126,7 @@ def fingerprint(self): return state_hash({ "archive": self.instance["engine_archive_sha256"], "level": self.instance["level_id"], "seed": self.instance["seed"], - "state": self._state, "decisions": self._decisions, "return": self._return, + "frame_sha256": self._frame_sha256, "decisions": self._decisions, "return": self._return, "terminated": self._terminated, "truncated": self._truncated, }) diff --git a/game_first_exam/benchmarks/towermind/instance_schema.py b/game_first_exam/benchmarks/towermind/instance_schema.py index 98d2f49..9082b92 100644 --- a/game_first_exam/benchmarks/towermind/instance_schema.py +++ b/game_first_exam/benchmarks/towermind/instance_schema.py @@ -11,6 +11,10 @@ REDUCERS = {("family_macro", "1.0.0")} CAPABILITIES = Capabilities(images=True, action_mode="text", native_truncation=True).to_dict() ARCHIVE_SHA256 = "153f363150f5e33f4827599498e2d7bda504045a4ae258e013bb504ea4273e19" +DECISION_PERIOD = 16 +REWARD_UNITS_PER_BREACH = 200 +# Allow float32 accumulation within one native decision interval. +REWARD_TOLERANCE = 2e-5 ENGINE_VERSIONS = { "mlagents-envs": "1.1.0", "gym": "0.26.2", diff --git a/game_first_exam/benchmarks/towermind/metric_rules.py b/game_first_exam/benchmarks/towermind/metric_rules.py index 58fd09b..b0340d6 100644 --- a/game_first_exam/benchmarks/towermind/metric_rules.py +++ b/game_first_exam/benchmarks/towermind/metric_rules.py @@ -1,6 +1,8 @@ """Validate native outcome evidence without loading Unity.""" import math +from instance_schema import DECISION_PERIOD, REWARD_TOLERANCE, REWARD_UNITS_PER_BREACH + def validate_metrics(final, instance): metrics = final["metrics"] @@ -12,8 +14,12 @@ def validate_metrics(final, instance): reward = metrics["native_return"] if type(reward) not in (int, float) or not math.isclose(reward, final["return"], abs_tol=1e-8): raise ValueError("TowerMind cumulative return disagrees with the service") - if not math.isclose(reward, health - initial, abs_tol=1e-8): - raise ValueError("TowerMind sparse return disagrees with base health") + feedback = metrics["native_action_feedback_events"] + if type(feedback) is not int or not 0 <= feedback <= DECISION_PERIOD * final["steps"]: + raise ValueError("invalid TowerMind action feedback count") + expected = health - initial - feedback / REWARD_UNITS_PER_BREACH + if not math.isclose(reward, expected, rel_tol=0, abs_tol=REWARD_TOLERANCE * max(1, final["steps"])): + raise ValueError("TowerMind sparse return disagrees with base health and action feedback") won = final["reason"] == "native_terminated" and health > 0 if type(metrics["native_success"]) is not int or metrics["native_success"] != int(won) or 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 index 4616eeb..6efef97 100644 --- a/game_first_exam/benchmarks/towermind/native.py +++ b/game_first_exam/benchmarks/towermind/native.py @@ -2,7 +2,6 @@ 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 @@ -66,28 +65,25 @@ def reset(self): return super().reset() -def first_observation(env): - try: - return env.reset() - except JSONDecodeError as reset_error: - # The player writes its JSON texture in FixedUpdate. A reset can yield a - # nonempty texture before that write. Action 6 is the native no-op. - try: - observation, reward, done, _ = env.step(NO_OP) - except JSONDecodeError as step_error: - raise ValueError( - "TowerMind JSON is invalid after one no-op startup decision " - f"(reset: {decode_error_summary(reset_error)}; no-op: {decode_error_summary(step_error)})" - ) from step_error - if done or float(reward) != 0.0: - raise ValueError("TowerMind startup decision ended the episode or changed its reward") - return observation +def player_camera(gym, wrappers): + # The Gym bridge lists visual sensors in specification order, followed by + # the vector observation. Select the player camera even if Unity still + # registers its separate text texture in pixel-only mode. + 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)) + ] + if len(cameras) != 1: + specs = [(spec.name, spec.shape) for spec in visual] + raise ValueError(f"expected exactly one native 512x512 RGB CameraSensor, got {specs}") + camera, = cameras + class PlayerCamera(wrappers.TowerMindMultiModalObsWrapper): + def _convert_obs(self, observation): + return super()._convert_obs([observation[camera]]) -def decode_error_summary(error): - # Report byte-level markers to trusted logs without dumping the observation. - prefix = ",".join(str(ord(character)) for character in error.doc[:4]) or "none" - return f"{len(error.doc)} characters, offset {error.pos}, first character codes [{prefix}]" + return PlayerCamera(gym, use_image=True, use_text=False, use_state=False) def open_native(player, wrappers_path, seed): @@ -102,14 +98,11 @@ def open_native(player, wrappers_path, seed): ) try: gym = gym_wrapper(unity, uint8_visual=True, allow_multiple_obs=True) - modalities = wrappers.TowerMindMultiModalObsWrapper( - gym, use_image=True, use_text=True, use_state=False - ) - env = wrappers.TowerMindActionMappingWrapper(modalities) + env = wrappers.TowerMindActionMappingWrapper(player_camera(gym, wrappers)) # UnityToGymWrapper resets during its constructor to inspect agent slots. # TowerMind's example then resets the wrapped environment to obtain the - # playable observation. The constructor snapshot can have an empty JSON sensor. - initial = first_observation(env) + # playable observation. + initial = env.reset() unity._initializing = False decision, terminal = unity.get_steps(gym.name) if len(decision) != 1 or len(terminal): diff --git a/game_first_exam/benchmarks/towermind/native_assets.py b/game_first_exam/benchmarks/towermind/native_assets.py index 29a48a0..3ab8a47 100644 --- a/game_first_exam/benchmarks/towermind/native_assets.py +++ b/game_first_exam/benchmarks/towermind/native_assets.py @@ -34,6 +34,8 @@ def download_assets(directory): def prepare_game(assets, workspace, instance): + from instance_schema import DECISION_PERIOD + archive = assets / "linux.zip" verify_asset(archive) verify_asset(assets / "wrappers.py") @@ -45,7 +47,7 @@ def prepare_game(assets, workspace, instance): configs = directory / "td_Data/StreamingAssets/Config" settings_path = configs / "EnvConfig.json" settings = json.loads(settings_path.read_text(encoding="utf-8")) - if settings["DecisionPeriod"] != 16: + if settings["DecisionPeriod"] != DECISION_PERIOD: raise ValueError("unexpected native decision period") levels_path = configs / "BenchmarkLevelsConfig.json" levels = json.loads(levels_path.read_text(encoding="utf-8"))["Levels"] @@ -55,7 +57,7 @@ def prepare_game(assets, workspace, instance): # The pinned player cycles levels when IsAutoPlayLevels equals 1. RandomSeed=instance["seed"], IsAutoPlayLevels=0, IsRepeatFailingLevels=0, IsHumanPlayerPlaying=0, IsDrlReward=0, IsDebug=0, IsRecordingEnabled=0, - IsOnlyPixelObs=0, NeedsNaturalLanguageObservation=0, + IsOnlyPixelObs=1, NeedsNaturalLanguageObservation=0, NeedsRealtimeLanguageObservation=0, ) settings_path.write_text(json.dumps(settings), encoding="utf-8") diff --git a/game_first_exam/images/towermind-files/FILES.json b/game_first_exam/images/towermind-files/FILES.json index dfb38fd..825180f 100644 --- a/game_first_exam/images/towermind-files/FILES.json +++ b/game_first_exam/images/towermind-files/FILES.json @@ -1,12 +1,12 @@ { - "image": "ghcr.io/mll-lab-nu/efe:towermind-files-0.1.3@sha256:123f5c92905638242edc226a642a36906206d21e7868fc5ac75506b79e47ca72", + "image": "ghcr.io/mll-lab-nu/efe:towermind-files-0.1.4@sha256:0105ed8ba822b60be2f85924cd6240d417ee0550e0c1bb6cd2afb9d827b8da10", "source": "game_first_exam/benchmarks/towermind", "files": { - "adapter.py": "9d2841610a00e0ce632021f51013f427950d178f77d2d76884ee2e9cb44db17c", - "instance_schema.py": "6103859ea8ce74a0bd6ee9c234e9eb58d912314bbb19b1b5aa89d9e5f96d065f", - "metric_rules.py": "8111b52f913a6fc7b893879ca9479f923aa813d301f5918a21fa0b10883671a3", - "native.py": "07f3445a91ba59c9082ba900fa3f17f517000547ecb8305167ff93ead8721b56", - "native_assets.py": "53ab1481a4c5b47a414015cdcc09bb6132a68cd322e052f72cce2123970d8798", + "adapter.py": "0060e21d75d4953426fa8d2501c8e5d44d807194033a9b8814e54912ff831304", + "instance_schema.py": "928c5b103a471606dcd5245ab3ece19e6a4ac1a315ea2da99ff2e33453aab032", + "metric_rules.py": "85367d3681e0687323b14943dab528712992ce5b779b36973eb710f383911f79", + "native.py": "b91df8d9987874a867d085b3a9997be105560cd5168026f530a747208a6b5be9", + "native_assets.py": "b552cce39157967ed76767029a9cc57fe6a1dff0aa99459addefec8d1bb6d28b", "requirements.txt": "1dae4bbe8f73c36d8ef74c6b9fcd6eedc20a8a7ce239d8e247122ac01f54b43a", "SOURCE.json": "f1cd82c5b88d0095c0d3087ed5a7c5f76f2a8160414b199793d24ea378dad989" } diff --git a/game_first_exam/images/towermind-files/VERSION b/game_first_exam/images/towermind-files/VERSION index b1e80bb..845639e 100644 --- a/game_first_exam/images/towermind-files/VERSION +++ b/game_first_exam/images/towermind-files/VERSION @@ -1 +1 @@ -0.1.3 +0.1.4 diff --git a/game_first_exam/tests/test_towermind_contract.py b/game_first_exam/tests/test_towermind_contract.py index 452ffba..4e9743d 100644 --- a/game_first_exam/tests/test_towermind_contract.py +++ b/game_first_exam/tests/test_towermind_contract.py @@ -2,12 +2,11 @@ import base64 from contextlib import contextmanager from io import BytesIO -import json from pathlib import Path from tempfile import TemporaryDirectory from types import SimpleNamespace import unittest -from unittest.mock import Mock, patch +from unittest.mock import patch import numpy as np from PIL import Image @@ -18,13 +17,13 @@ from grade import grade from metric_rules import validate_metrics from native_assets import ARCHIVE_SHA256 -from server import Game, InvalidAction +from server import EnvironmentFault, Game, InvalidAction -def native_observation(health, shade=91): +def native_observation(shade=91): return { "image": np.full((512, 512, 3), shade, dtype=np.uint8), - "text": {"Level_Current_Health": health, "private": "hidden-wave-sentinel"}, + "text": {"Level_Current_Health": 99, "private": "hidden-wave-sentinel"}, } @@ -36,8 +35,9 @@ def __init__(self, outcome): def step(self, action): self.actions.append(action) - health = 0 if self.outcome == "destroyed" else 20 - return native_observation(health, 92), health - 20, True, { + breaches = 20 if self.outcome == "destroyed" else int(self.outcome == "feedback") + feedback = {"feedback": 0.01, "unexpected_reward": 0.0005}.get(self.outcome, 0) + return native_observation(92), np.float32(-breaches - feedback), True, { "step": SimpleNamespace(interrupted=[self.outcome == "interrupted"]) } @@ -53,7 +53,7 @@ def session(outcome): with ( patch.object(adapter, "version", side_effect=config["engine_versions"].__getitem__), patch.object(adapter, "prepare_game", return_value=(Path("unused"), 20)), - patch.object(adapter, "open_native", return_value=(native, native_observation(20))), + patch.object(adapter, "open_native", return_value=(native, native_observation())), ): game_adapter = adapter.Adapter(config) config["initial_state_sha256"] = game_adapter.fingerprint() @@ -72,11 +72,12 @@ def test_gym_bridge_can_load_offline(self): self.assertEqual(load_gym_bridge().__name__, "UnityToGymWrapper") - def test_initial_decision_comes_from_explicit_reset_after_handshake(self): + def test_explicit_reset_selects_only_the_player_camera(self): import native unity = native.LocalUnity.__new__(native.LocalUnity) - payloads = iter(("", '{"Level_Current_Health": 20}')) + player_frame = native_observation()["image"] + payloads = iter((None, ["private texture", player_frame, "private vector"])) unity.get_steps = lambda _: ([object()], []) def receive_reset(player): @@ -84,17 +85,33 @@ def receive_reset(player): 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() # Slot discovery sees an empty text sensor. + player.reset() def reset(self): self.player.reset() - return {"text": json.loads(self.player.payload)} + 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]} + + def reset(self): + return self._convert_obs(self.gym.reset()) wrappers = SimpleNamespace( - TowerMindMultiModalObsWrapper=lambda gym, **_: gym, + TowerMindMultiModalObsWrapper=Modalities, TowerMindActionMappingWrapper=lambda env: env, ) with ( @@ -104,45 +121,22 @@ def reset(self): 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"), 42) - self.assertEqual(initial["text"]["Level_Current_Health"], 20) + self.assertEqual(env.flags, {"use_image": True, "use_text": False, "use_state": False}) + self.assertEqual(set(initial), {"image"}) + self.assertIs(initial["image"], player_frame) with self.assertRaisesRegex(RuntimeError, "one episode"): env.reset() self.assertEqual(reset.call_count, 2) - def test_invalid_startup_sensor_advances_one_native_no_op(self): - from native import first_observation - - frame = native_observation(20) - for payload in ("\x00" * 4, "X" * 90): - with self.subTest(payload_length=len(payload)): - env = Mock() - env.reset.side_effect = json.JSONDecodeError("Expecting value", payload, 0) - env.step.return_value = (frame, 0.0, False, {}) - self.assertIs(first_observation(env), frame) - env.step.assert_called_once_with((0.0, 0.0, 6)) - env.reset.assert_called_once_with() - - def test_startup_aborts_after_a_single_invalid_no_op(self): - from native import first_observation - - env = Mock() - env.reset.side_effect = json.JSONDecodeError("Expecting value", "X" * 90, 0) - env.step.side_effect = json.JSONDecodeError("Expecting value", "bad sensor", 0) - with self.assertRaisesRegex(ValueError, "reset: 90 characters.*no-op: 10 characters") as failure: - first_observation(env) - self.assertNotIn("bad sensor", str(failure.exception)) - env.step.assert_called_once_with((0.0, 0.0, 6)) - - def test_startup_never_skips_a_terminal_or_reward(self): - from native import first_observation - - for reward, done in ((-1.0, False), (0.0, True)): - with self.subTest(reward=reward, done=done): - env = Mock() - env.reset.side_effect = json.JSONDecodeError("Expecting value", "", 0) - env.step.return_value = (native_observation(20), reward, done, {}) - with self.assertRaisesRegex(ValueError, "startup decision ended"): - first_observation(env) + def test_missing_or_ambiguous_camera_fails_closed(self): + from native import player_camera + + other = SimpleNamespace(name="RenderTextureSensor", shape=(512, 512, 3)) + camera = SimpleNamespace(name="CameraSensor", shape=(512, 512, 3)) + for specs in ([other], [camera, camera]): + gym = SimpleNamespace(group_spec=SimpleNamespace(observation_specs=specs)) + with self.subTest(specs=specs), self.assertRaisesRegex(ValueError, "exactly one"): + player_camera(gym, None) def test_schema_rejects_drift(self): config = instance() @@ -193,6 +187,24 @@ def test_native_outcomes_and_public_early_stop_are_distinct(self): result = grade(game.final, config, validate_metrics) self.assertEqual((result["reason"], result["primary_score"]), (reason, success)) + def test_native_reward_separates_breaches_and_action_feedback(self): + with session("feedback") as (game, config, _): + game.submit({"action": "0 0 2", "expected_step": 0, "request_id": "mixed"}) + self.assertEqual(game.final["return"], float(np.float32(-1.01))) + self.assertEqual(game.final["metrics"]["base_health"], 19) + self.assertEqual(game.final["metrics"]["native_action_feedback_events"], 2) + self.assertEqual(grade(game.final, config, validate_metrics)["primary_score"], 1) + game.final["metrics"]["native_action_feedback_events"] = 0 + with self.assertRaisesRegex(ValueError, "sparse return"): + validate_metrics(game.final, config) + + def test_unexpected_native_reward_invalidates_attempt(self): + with session("unexpected_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 index 43db152..d4a383a 100644 --- a/game_first_exam/tests/test_towermind_native.py +++ b/game_first_exam/tests/test_towermind_native.py @@ -18,10 +18,6 @@ COMMANDS = [("0 0 6", NO_OP), ("-1.5 1.2 2", (-1.5, 1.2, 2))] * 6 -def native_snapshot(observation, reward, done, interrupted): - return observation["text"], float(reward), bool(done), bool(interrupted) - - class TowerMindNative(unittest.TestCase): def test_native_trajectory_and_idle_intervals(self): config = instance() @@ -29,6 +25,7 @@ def test_native_trajectory_and_idle_intervals(self): player, _ = prepare_game(NATIVE_ASSETS, Path(workspace), config) env, initial = open_native(player, NATIVE_ASSETS / "wrappers.py", config["seed"]) try: + self.assertEqual(set(initial), {"image"}) with self.assertRaisesRegex(RuntimeError, "one episode"): env.reset() with socket.create_connection(("127.0.0.1", RPC_PORT), timeout=2): @@ -37,19 +34,20 @@ def test_native_trajectory_and_idle_intervals(self): for _, action in COMMANDS: observation, reward, done, info = env.step(action) interrupted = info["step"].interrupted[0] if done else False - expected.append(native_snapshot(observation, reward, done, interrupted)) + self.assertEqual(set(observation), {"image"}) + expected.append((float(reward), bool(done), bool(interrupted))) self.assertFalse(done) finally: env.close() adapter = Adapter(config) try: - self.assertEqual(adapter._state, initial["text"]) 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") for index, ((command, _), item) in enumerate(zip(COMMANDS, expected)): before = adapter.fingerprint() adapter.spec() @@ -61,8 +59,7 @@ def test_native_trajectory_and_idle_intervals(self): self.assertEqual(adapter.fingerprint(), before) transition = adapter.step(command) self.assertEqual( - (adapter._state, transition.reward, transition.terminated or transition.truncated, - transition.truncated), + (transition.reward, transition.terminated or transition.truncated, transition.truncated), item, ) finally: @@ -78,6 +75,7 @@ def test_native_terminal_uses_first_episode(self): break self.assertTrue(transition.terminated, "expected a native ending in development level 0") metrics = adapter.metrics() + self.assertEqual(metrics["native_action_feedback_events"], 0) self.assertEqual(metrics["native_return"], metrics["base_health"] - metrics["initial_base_health"]) self.assertEqual(adapter.success(), metrics["base_health"] > 0) with self.assertRaisesRegex(ValueError, "episode closed"): From da66d63b0ff14523935f1e5734de73d3db70c00d Mon Sep 17 00:00:00 2001 From: maomao868 <196136225+maomao868@users.noreply.github.com> Date: Fri, 20 Nov 2026 07:48:57 -0800 Subject: [PATCH 06/17] Preserve upstream TowerMind observations and metrics --- .../benchmarks/towermind/README.md | 10 +- .../benchmarks/towermind/adapter.py | 45 +++++---- .../benchmarks/towermind/instance_schema.py | 6 +- .../benchmarks/towermind/metric_rules.py | 22 ++--- .../benchmarks/towermind/native.py | 30 +++--- .../benchmarks/towermind/native_assets.py | 19 +--- .../images/towermind-files/FILES.json | 12 +-- .../images/towermind-files/VERSION | 2 +- .../tests/test_towermind_contract.py | 96 ++++++++++++------ .../tests/test_towermind_native.py | 99 +++++++++++-------- game_first_exam/tests/towermind_fixture.py | 2 +- 11 files changed, 190 insertions(+), 153 deletions(-) diff --git a/game_first_exam/benchmarks/towermind/README.md b/game_first_exam/benchmarks/towermind/README.md index 9334b70..b172325 100644 --- a/game_first_exam/benchmarks/towermind/README.md +++ b/game_first_exam/benchmarks/towermind/README.md @@ -1,16 +1,16 @@ # TowerMind adapter -This development integration uses the upstream Unity Linux x86-64 player and the two official TowerMind wrappers. `SOURCE.json` pins the archive and wrapper source by commit and SHA256. The simulator extracts its own copy, selects an original benchmark level and a positive seed, keeps the native 16-step decision interval and selects the native sparse reward. For this pinned player, `IsAutoPlayLevels=0` selects the configured level and `1` cycles levels. Retries are off. +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. All other settings come from the pinned archive. -Initialization resets through the TowerMind wrappers after the Gym bridge discovers its agent slots. The player runs in upstream pixel-only mode (`IsOnlyPixelObs=1`). The bridge selects the 512×512 RGB `CameraSensor` by its reported name and dimensions. The public episode starts at the reset observation. The adapter records the first native terminal or interrupted transition and closes the episode. +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 adapter drops any separate text or vector observations before caching the camera frame. Raw step metadata, configuration, seed and fingerprints stay inside the simulator. The fingerprint covers the cached RGB pixels, instance identity and step outcomes. +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 pinned sparse reward charges 1 per base breach and 0.005 per reported action outcome. The adapter uses these increments and the configured starting health to track base health. It returns each native reward unchanged. Success requires the first native episode to terminate with the base still alive. +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 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. 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. A test-only instance drives native equivalence, idle interval and first-episode checks. Benchmark discovery for model evaluation will be added with a frozen task. +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. 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. Its development instance is for integration tests. Run from the repository root on a Linux Docker host. diff --git a/game_first_exam/benchmarks/towermind/adapter.py b/game_first_exam/benchmarks/towermind/adapter.py index da8b745..b0002ff 100644 --- a/game_first_exam/benchmarks/towermind/adapter.py +++ b/game_first_exam/benchmarks/towermind/adapter.py @@ -11,7 +11,7 @@ from config_schema import validate_instance from contracts import Transition from encoding import png, state_hash -from instance_schema import CAPABILITIES, DECISION_PERIOD, REWARD_TOLERANCE, REWARD_UNITS_PER_BREACH +from instance_schema import CAPABILITIES from native_assets import prepare_game @@ -45,12 +45,11 @@ def __init__(self, instance, assets=None): self._env = None self._decisions = 0 self._return = 0.0 - self._action_feedback_events = 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, self._initial_health = prepare_game(source, Path(self._workspace.name), instance) - self._health = self._initial_health + player = prepare_game(source, Path(self._workspace.name), instance) self._env, observation = open_native(player, source / "wrappers.py", instance["seed"]) self._cache(observation) except Exception: @@ -58,6 +57,9 @@ def __init__(self, instance, assets=None): 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) @@ -67,6 +69,7 @@ def _cache(self, observation): 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 { @@ -85,21 +88,17 @@ def step(self, action): raise ValueError("episode closed") observation, reward, done, info = self._env.step(parse_action(action)) reward = float(reward) - if not math.isfinite(reward) or reward > 0: + if not math.isfinite(reward): raise ValueError("invalid native TowerMind reward") - # The pinned sparse mode charges 1 per breach and 0.005 per action - # outcome. Each physics tick can process at most one tracked action. - units = round(-reward * REWARD_UNITS_PER_BREACH) - breaches, feedback = divmod(units, REWARD_UNITS_PER_BREACH) - if ( - breaches > self._health - or feedback > DECISION_PERIOD - or not math.isclose(-reward, units / REWARD_UNITS_PER_BREACH, rel_tol=0, abs_tol=REWARD_TOLERANCE) - ): - raise ValueError("unexpected native TowerMind reward increment") + 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) - self._health -= breaches - self._action_feedback_events += feedback + # 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 @@ -108,17 +107,16 @@ def step(self, action): return Transition(reward, self._terminated, self._truncated) def success(self): - # The native level ends when the base is destroyed or all attackers are resolved. - return self._terminated and self._health > 0 + # 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_success": int(self.success()), "native_return": self._return, - "initial_base_health": self._initial_health, - "base_health": self._health, + "base_health": self._native_text["Level_Current_Health"], "native_decisions": self._decisions, - "native_action_feedback_events": self._action_feedback_events, + "native_counted_actions": self._counted_actions, + "native_invalid_actions": self._invalid_actions, } def fingerprint(self): @@ -127,6 +125,7 @@ def fingerprint(self): "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, }) diff --git a/game_first_exam/benchmarks/towermind/instance_schema.py b/game_first_exam/benchmarks/towermind/instance_schema.py index 9082b92..f8d15ba 100644 --- a/game_first_exam/benchmarks/towermind/instance_schema.py +++ b/game_first_exam/benchmarks/towermind/instance_schema.py @@ -6,15 +6,11 @@ SCHEMA_VERSION = "1.0.0" BENCHMARK = "towermind" FIELDS = {"level_id", "engine_versions", "engine_archive_sha256"} -METRICS = {"native_success"} +METRICS = {"native_return"} PROFILES = {"player-rgb-v1"} REDUCERS = {("family_macro", "1.0.0")} CAPABILITIES = Capabilities(images=True, action_mode="text", native_truncation=True).to_dict() ARCHIVE_SHA256 = "153f363150f5e33f4827599498e2d7bda504045a4ae258e013bb504ea4273e19" -DECISION_PERIOD = 16 -REWARD_UNITS_PER_BREACH = 200 -# Allow float32 accumulation within one native decision interval. -REWARD_TOLERANCE = 2e-5 ENGINE_VERSIONS = { "mlagents-envs": "1.1.0", "gym": "0.26.2", diff --git a/game_first_exam/benchmarks/towermind/metric_rules.py b/game_first_exam/benchmarks/towermind/metric_rules.py index b0340d6..1fb21fa 100644 --- a/game_first_exam/benchmarks/towermind/metric_rules.py +++ b/game_first_exam/benchmarks/towermind/metric_rules.py @@ -1,25 +1,17 @@ """Validate native outcome evidence without loading Unity.""" -import math - -from instance_schema import DECISION_PERIOD, REWARD_TOLERANCE, REWARD_UNITS_PER_BREACH - - def validate_metrics(final, instance): metrics = final["metrics"] - health, initial = metrics["base_health"], metrics["initial_base_health"] - if type(health) is not int or type(initial) is not int or not 0 <= health <= initial or initial < 1: + 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 not math.isclose(reward, final["return"], abs_tol=1e-8): + if type(reward) not in (int, float) or reward != final["return"]: raise ValueError("TowerMind cumulative return disagrees with the service") - feedback = metrics["native_action_feedback_events"] - if type(feedback) is not int or not 0 <= feedback <= DECISION_PERIOD * final["steps"]: - raise ValueError("invalid TowerMind action feedback count") - expected = health - initial - feedback / REWARD_UNITS_PER_BREACH - if not math.isclose(reward, expected, rel_tol=0, abs_tol=REWARD_TOLERANCE * max(1, final["steps"])): - raise ValueError("TowerMind sparse return disagrees with base health and action feedback") + 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 type(metrics["native_success"]) is not int or metrics["native_success"] != int(won) or final["success"] != won: + 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 index 6efef97..cd315fe 100644 --- a/game_first_exam/benchmarks/towermind/native.py +++ b/game_first_exam/benchmarks/towermind/native.py @@ -2,6 +2,7 @@ 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 @@ -65,25 +66,32 @@ def reset(self): return super().reset() -def player_camera(gym, wrappers): - # The Gym bridge lists visual sensors in specification order, followed by - # the vector observation. Select the player camera even if Unity still - # registers its separate text texture in pixel-only mode. +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)) ] - if len(cameras) != 1: - specs = [(spec.name, spec.shape) for spec in visual] - raise ValueError(f"expected exactly one native 512x512 RGB CameraSensor, got {specs}") + 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 PlayerCamera(wrappers.TowerMindMultiModalObsWrapper): + class NativeObservations(wrappers.TowerMindMultiModalObsWrapper): def _convert_obs(self, observation): - return super()._convert_obs([observation[camera]]) + 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 PlayerCamera(gym, use_image=True, use_text=False, use_state=False) + return NativeObservations(gym, use_image=True, use_text=True, use_state=False) def open_native(player, wrappers_path, seed): @@ -98,7 +106,7 @@ def open_native(player, wrappers_path, seed): ) try: gym = gym_wrapper(unity, uint8_visual=True, allow_multiple_obs=True) - env = wrappers.TowerMindActionMappingWrapper(player_camera(gym, wrappers)) + 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. diff --git a/game_first_exam/benchmarks/towermind/native_assets.py b/game_first_exam/benchmarks/towermind/native_assets.py index 3ab8a47..0eae060 100644 --- a/game_first_exam/benchmarks/towermind/native_assets.py +++ b/game_first_exam/benchmarks/towermind/native_assets.py @@ -34,8 +34,6 @@ def download_assets(directory): def prepare_game(assets, workspace, instance): - from instance_schema import DECISION_PERIOD - archive = assets / "linux.zip" verify_asset(archive) verify_asset(assets / "wrappers.py") @@ -47,24 +45,13 @@ def prepare_game(assets, workspace, instance): configs = directory / "td_Data/StreamingAssets/Config" settings_path = configs / "EnvConfig.json" settings = json.loads(settings_path.read_text(encoding="utf-8")) - if settings["DecisionPeriod"] != DECISION_PERIOD: - raise ValueError("unexpected native decision period") - levels_path = configs / "BenchmarkLevelsConfig.json" - levels = json.loads(levels_path.read_text(encoding="utf-8"))["Levels"] - level, = (row for row in levels if row["ID"] == instance["level_id"]) - settings.update( - GeneralizationLevel=0, LevelsConfigFileName=levels_path.name, - # The pinned player cycles levels when IsAutoPlayLevels equals 1. - RandomSeed=instance["seed"], IsAutoPlayLevels=0, IsRepeatFailingLevels=0, - IsHumanPlayerPlaying=0, IsDrlReward=0, IsDebug=0, IsRecordingEnabled=0, - IsOnlyPixelObs=1, NeedsNaturalLanguageObservation=0, - NeedsRealtimeLanguageObservation=0, - ) + # 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" ) - return player, level["TotalLife"] + return player if __name__ == "__main__": diff --git a/game_first_exam/images/towermind-files/FILES.json b/game_first_exam/images/towermind-files/FILES.json index 825180f..08d0604 100644 --- a/game_first_exam/images/towermind-files/FILES.json +++ b/game_first_exam/images/towermind-files/FILES.json @@ -1,12 +1,12 @@ { - "image": "ghcr.io/mll-lab-nu/efe:towermind-files-0.1.4@sha256:0105ed8ba822b60be2f85924cd6240d417ee0550e0c1bb6cd2afb9d827b8da10", + "image": "ghcr.io/mll-lab-nu/efe:towermind-files-0.1.5@sha256:80b25b33143f709ea28dc41d3cd37c4260c253db751a9fa46fd2c77808e0c6b4", "source": "game_first_exam/benchmarks/towermind", "files": { - "adapter.py": "0060e21d75d4953426fa8d2501c8e5d44d807194033a9b8814e54912ff831304", - "instance_schema.py": "928c5b103a471606dcd5245ab3ece19e6a4ac1a315ea2da99ff2e33453aab032", - "metric_rules.py": "85367d3681e0687323b14943dab528712992ce5b779b36973eb710f383911f79", - "native.py": "b91df8d9987874a867d085b3a9997be105560cd5168026f530a747208a6b5be9", - "native_assets.py": "b552cce39157967ed76767029a9cc57fe6a1dff0aa99459addefec8d1bb6d28b", + "adapter.py": "46364b24f4c860f7c51f5c81a78881474b7eeb8dad1d1b00acf87c92cce4aa67", + "instance_schema.py": "7ba5a1089c0a47770e92dda1e05effa177e99249c595821789aa6de2426a6b30", + "metric_rules.py": "992513d482e4dc39edf5bb71c17c6acfe6fedd771d2692144538cf280b56ad47", + "native.py": "6d78160f7cd442e9526d4401d12d3f4b7b80fd600675394af389d42e508728fa", + "native_assets.py": "f1aec5a05ead72025554c1183a806409b23e61951cfb3bfb7f7467d381eee9d7", "requirements.txt": "1dae4bbe8f73c36d8ef74c6b9fcd6eedc20a8a7ce239d8e247122ac01f54b43a", "SOURCE.json": "f1cd82c5b88d0095c0d3087ed5a7c5f76f2a8160414b199793d24ea378dad989" } diff --git a/game_first_exam/images/towermind-files/VERSION b/game_first_exam/images/towermind-files/VERSION index 845639e..9faa1b7 100644 --- a/game_first_exam/images/towermind-files/VERSION +++ b/game_first_exam/images/towermind-files/VERSION @@ -1 +1 @@ -0.1.4 +0.1.5 diff --git a/game_first_exam/tests/test_towermind_contract.py b/game_first_exam/tests/test_towermind_contract.py index 4e9743d..7667619 100644 --- a/game_first_exam/tests/test_towermind_contract.py +++ b/game_first_exam/tests/test_towermind_contract.py @@ -2,6 +2,7 @@ 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 @@ -20,10 +21,14 @@ from server import EnvironmentFault, Game, InvalidAction -def native_observation(shade=91): +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": 99, "private": "hidden-wave-sentinel"}, + "text": { + "Level_Current_Health": health, + "Agent_Last_Action_Info": {"Action_Index": action_type, "Error_Code": error_code}, + "private": "hidden-wave-sentinel", + }, } @@ -35,9 +40,10 @@ def __init__(self, outcome): def step(self, action): self.actions.append(action) - breaches = 20 if self.outcome == "destroyed" else int(self.outcome == "feedback") - feedback = {"feedback": 0.01, "unexpected_reward": 0.0005}.get(self.outcome, 0) - return native_observation(92), np.float32(-breaches - feedback), True, { + 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"]) } @@ -52,7 +58,7 @@ def session(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"), 20)), + patch.object(adapter, "prepare_game", return_value=Path("unused")), patch.object(adapter, "open_native", return_value=(native, native_observation())), ): game_adapter = adapter.Adapter(config) @@ -72,12 +78,12 @@ def test_gym_bridge_can_load_offline(self): self.assertEqual(load_gym_bridge().__name__, "UnityToGymWrapper") - def test_explicit_reset_selects_only_the_player_camera(self): + 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, ["private texture", player_frame, "private vector"])) + payloads = iter((None, ["text texture", player_frame, "private vector"])) unity.get_steps = lambda _: ([object()], []) def receive_reset(player): @@ -105,7 +111,7 @@ def __init__(self, gym, **flags): self.flags = flags def _convert_obs(self, observation): - return {"image": observation[0]} + return {"image": observation[0], "text": observation[1]} def reset(self): return self._convert_obs(self.gym.reset()) @@ -121,22 +127,43 @@ def reset(self): 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"), 42) - self.assertEqual(env.flags, {"use_image": True, "use_text": False, "use_state": False}) - self.assertEqual(set(initial), {"image"}) + 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_camera_fails_closed(self): - from native import player_camera + 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]): + 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, "exactly one"): - player_camera(gym, None) + 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() @@ -170,11 +197,11 @@ def test_server_rejects_malformed_action_before_game_moves(self): self.assertEqual((game.steps, native.actions), (0, [])) def test_native_outcomes_and_public_early_stop_are_distinct(self): - for outcome, reason, success in ( - ("completed", "native_terminated", 1), - ("destroyed", "native_terminated", 0), - ("interrupted", "native_truncated", 0), - ("early", "agent_finished", 0), + 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": @@ -185,21 +212,28 @@ def test_native_outcomes_and_public_early_stop_are_distinct(self): 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, success)) + self.assertEqual((result["reason"], result["primary_score"]), (reason, score)) + self.assertEqual(game.final["success"], success) - def test_native_reward_separates_breaches_and_action_feedback(self): + 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(game.final["return"], float(np.float32(-1.01))) - self.assertEqual(game.final["metrics"]["base_health"], 19) - self.assertEqual(game.final["metrics"]["native_action_feedback_events"], 2) - self.assertEqual(grade(game.final, config, validate_metrics)["primary_score"], 1) - game.final["metrics"]["native_action_feedback_events"] = 0 - with self.assertRaisesRegex(ValueError, "sparse return"): + 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_unexpected_native_reward_invalidates_attempt(self): - with session("unexpected_reward") as (game, _, _): + 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") diff --git a/game_first_exam/tests/test_towermind_native.py b/game_first_exam/tests/test_towermind_native.py index d4a383a..b3173b8 100644 --- a/game_first_exam/tests/test_towermind_native.py +++ b/game_first_exam/tests/test_towermind_native.py @@ -1,89 +1,110 @@ """Native equivalence and timing checks for the pinned TowerMind Linux player.""" import socket +from json import JSONDecodeError from pathlib import Path from tempfile import TemporaryDirectory import time import unittest 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, open_native +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_native_trajectory_and_idle_intervals(self): + def test_01_upstream_reference_matches_the_adapter_through_termination(self): config = instance() with TemporaryDirectory() as workspace: - player, _ = prepare_game(NATIVE_ASSETS, Path(workspace), config) - env, initial = open_native(player, NATIVE_ASSETS / "wrappers.py", config["seed"]) + player = prepare_game(NATIVE_ASSETS, Path(workspace), config) + # 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) + unity = UnityEnvironment(file_name=str(player), side_channels=[settings], + timeout_wait=60, log_folder=str(player.parent)) try: - self.assertEqual(set(initial), {"image"}) - with self.assertRaisesRegex(RuntimeError, "one episode"): - env.reset() - with socket.create_connection(("127.0.0.1", RPC_PORT), timeout=2): - pass + 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 _, action in COMMANDS: + 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 - self.assertEqual(set(observation), {"image"}) - expected.append((float(reward), bool(done), bool(interrupted))) - self.assertFalse(done) + 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: - env.close() + 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") - for index, ((command, _), item) in enumerate(zip(COMMANDS, expected)): - before = adapter.fingerprint() - adapter.spec() - adapter.observe() - adapter.frame() - if index in (1, 5): + 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) + self.assertEqual(adapter.fingerprint(), before) transition = adapter.step(command) self.assertEqual( - (transition.reward, transition.terminated or transition.truncated, transition.truncated), - item, + (transition.reward, transition.terminated, transition.truncated), + (reward, done and not interrupted, interrupted), + f"decision {index + 1}", ) - finally: - adapter.close() - - def test_native_terminal_uses_first_episode(self): - config = instance() - adapter = Adapter(config) - try: - for _ in range(4096): - transition = adapter.step("0 0 6") - if transition.terminated or transition.truncated: - break - self.assertTrue(transition.terminated, "expected a native ending in development level 0") + reference_return += reward + if outcome["Action_Index"] != 6: + counted += 1 + invalid += int(outcome["Error_Code"] > 0) metrics = adapter.metrics() - self.assertEqual(metrics["native_action_feedback_events"], 0) - self.assertEqual(metrics["native_return"], metrics["base_health"] - metrics["initial_base_health"]) - self.assertEqual(adapter.success(), metrics["base_health"] > 0) + 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) with self.assertRaisesRegex(ValueError, "episode closed"): adapter.step("0 0 6") finally: adapter.close() - def test_public_service_stops_without_awarding_completion(self): + def test_public_service_keeps_native_result_on_a_budget_stop(self): config = instance() config["max_steps"] = 1 adapter = Adapter(config) diff --git a/game_first_exam/tests/towermind_fixture.py b/game_first_exam/tests/towermind_fixture.py index 3625bab..968f680 100644 --- a/game_first_exam/tests/towermind_fixture.py +++ b/game_first_exam/tests/towermind_fixture.py @@ -25,7 +25,7 @@ def instance(): "engine_archive_sha256": instance_schema.ARCHIVE_SHA256, "observation_profile": "player-rgb-v1", "metric_spec": { - "primary": "native_success", "success_label": "native_level_completed", + "primary": "native_return", "success_label": "native_level_completed", "reducer": "family_macro", "reducer_version": "1.0.0", }, } From b701d0b8c38d05ad0548bcf9a76c8fdc4679778d Mon Sep 17 00:00:00 2001 From: maomao868 <196136225+maomao868@users.noreply.github.com> Date: Fri, 20 Nov 2026 07:54:17 -0800 Subject: [PATCH 07/17] Diagnose TowerMind texture readback in Linux CI --- .../tests/check-towermind-network.sh | 1 + .../tests/test_towermind_native.py | 43 ++++++++++++++++++- 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/game_first_exam/tests/check-towermind-network.sh b/game_first_exam/tests/check-towermind-network.sh index f0e98bd..912aede 100644 --- a/game_first_exam/tests/check-towermind-network.sh +++ b/game_first_exam/tests/check-towermind-network.sh @@ -12,6 +12,7 @@ trap cleanup EXIT docker run -d --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/test_towermind_native.py b/game_first_exam/tests/test_towermind_native.py index b3173b8..099bd76 100644 --- a/game_first_exam/tests/test_towermind_native.py +++ b/game_first_exam/tests/test_towermind_native.py @@ -1,4 +1,5 @@ """Native equivalence and timing checks for the pinned TowerMind Linux player.""" +import json import socket from json import JSONDecodeError from pathlib import Path @@ -22,6 +23,43 @@ MAX_REFERENCE_DECISIONS = 4096 +def report_texture_transport(player, wrappers): + for args in ([], ["-force-glcore"], ["-force-vulkan"]): + label = args[0] if args else "default" + log_path = player.parent / f"diagnostic-{label}.log" + settings = EngineConfigurationChannel() + settings.set_configuration_parameters(target_frame_rate=-1, time_scale=20.0, capture_frame_rate=60) + try: + unity = UnityEnvironment(file_name=str(player), side_channels=[settings], timeout_wait=20, + additional_args=args + ["-logFile", str(log_path)], seed=42) + try: + bridge = load_gym_bridge()(unity, uint8_visual=True, allow_multiple_obs=True) + texture = bridge.reset()[1] + for channel, plane in enumerate(texture): + bbox = np.argwhere(plane) + span = (bbox.min(axis=0).tolist(), bbox.max(axis=0).tolist()) if len(bbox) else () + print(f"reference {label} channel {channel}: {len(bbox)} nonzero pixels, spans {span}") + header = np.flip(texture, axis=1).reshape(-1)[:8].tolist() + print(f"reference {label} decoded header byte codes: {header}") + for rotation in range(4): + oriented = np.rot90(texture, rotation, axes=(1, 2)) + for mirrored, candidate in enumerate((oriented, oriented[:, :, ::-1])): + try: + result = wrappers.get_json_from_obs(candidate) + except json.JSONDecodeError: + continue + if isinstance(result, dict) and "Level_Current_Health" in result: + print(f"reference {label} decoded JSON, rotation={rotation * 90}, mirrored={bool(mirrored)}") + finally: + unity.close() + except Exception as error: + print(f"reference {label} transport probe failed: {type(error).__name__}") + if log_path.exists(): + for line in log_path.read_text(encoding="utf-8", errors="replace").splitlines(): + if line.startswith(("Renderer:", "Vendor:", "Version:", "GfxDevice:", "OpenGL", "Vulkan")): + print(f"reference {label}: {line.strip()}") + + class TowerMindNative(unittest.TestCase): def test_01_upstream_reference_matches_the_adapter_through_termination(self): config = instance() @@ -44,6 +82,8 @@ def test_01_upstream_reference_matches_the_adapter_through_termination(self): initial = env.reset() except JSONDecodeError as error: specs = [(spec.name, spec.shape) for spec in bridge.group_spec.observation_specs] + unity.close() + report_texture_transport(player, wrappers) 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}" @@ -61,7 +101,8 @@ def test_01_upstream_reference_matches_the_adapter_through_termination(self): break self.assertTrue(done, "expected a native ending within the reference decision cap") finally: - unity.close() + if unity._loaded: + unity.close() adapter = Adapter(config) try: From 21f01362a4046a50c6acdde684897ebdaa214e64 Mon Sep 17 00:00:00 2001 From: maomao868 <196136225+maomao868@users.noreply.github.com> Date: Fri, 20 Nov 2026 07:59:36 -0800 Subject: [PATCH 08/17] Compare the Unity text sensor with native diagnostic recording --- .../tests/test_towermind_native.py | 54 +++++++++++++------ 1 file changed, 38 insertions(+), 16 deletions(-) diff --git a/game_first_exam/tests/test_towermind_native.py b/game_first_exam/tests/test_towermind_native.py index 099bd76..2e38156 100644 --- a/game_first_exam/tests/test_towermind_native.py +++ b/game_first_exam/tests/test_towermind_native.py @@ -24,7 +24,15 @@ def report_texture_transport(player, wrappers): - for args in ([], ["-force-glcore"], ["-force-vulkan"]): + # The native recorder writes the same payload before it goes through the + # texture transport. Enable it only in this disposable diagnostic copy. + config_path = player.parent / "td_Data/StreamingAssets/Config/EnvConfig.json" + config = json.loads(config_path.read_text(encoding="utf-8")) + records = player.parent / "diagnostic-records" + records.mkdir() + config.update(IsRecordingEnabled=1, RecordingPath=str(records)) + config_path.write_text(json.dumps(config), encoding="utf-8") + for args in ([], ["-force-gfx-direct"]): label = args[0] if args else "default" log_path = player.parent / f"diagnostic-{label}.log" settings = EngineConfigurationChannel() @@ -35,21 +43,35 @@ def report_texture_transport(player, wrappers): try: bridge = load_gym_bridge()(unity, uint8_visual=True, allow_multiple_obs=True) texture = bridge.reset()[1] - for channel, plane in enumerate(texture): - bbox = np.argwhere(plane) - span = (bbox.min(axis=0).tolist(), bbox.max(axis=0).tolist()) if len(bbox) else () - print(f"reference {label} channel {channel}: {len(bbox)} nonzero pixels, spans {span}") - header = np.flip(texture, axis=1).reshape(-1)[:8].tolist() - print(f"reference {label} decoded header byte codes: {header}") - for rotation in range(4): - oriented = np.rot90(texture, rotation, axes=(1, 2)) - for mirrored, candidate in enumerate((oriented, oriented[:, :, ::-1])): - try: - result = wrappers.get_json_from_obs(candidate) - except json.JSONDecodeError: - continue - if isinstance(result, dict) and "Level_Current_Health" in result: - print(f"reference {label} decoded JSON, rotation={rotation * 90}, mirrored={bool(mirrored)}") + red = texture[0] + rows = np.count_nonzero(red, axis=1) + print(f"reference {label} nonzero texture pixels in first/last 20 rows: {rows[:20]}, {rows[-20:]}") + try: + wrappers.get_json_from_obs(texture) + except json.JSONDecodeError as error: + print(f"reference {label} stock decoder: length {len(error.doc)}, offset {error.pos}") + else: + print(f"reference {label} stock decoder: valid JSON") + paths = sorted(records.glob("*/game_internal_states/*"), key=lambda p: p.stat().st_mtime_ns) + if not paths: + print(f"reference {label} native diagnostic record absent") + continue + recorded = paths[-1].read_text(encoding="utf-8-sig") + try: + json.loads(recorded) + except json.JSONDecodeError as error: + print(f"reference {label} recorder: length {len(recorded)}, invalid JSON at {error.pos}") + else: + print(f"reference {label} recorder: length {len(recorded)}, valid JSON") + expected = np.array([ord(char) % 256 for char in recorded] + [64], dtype=np.uint8) + actual = red[red != 0] + common = np.minimum(np.bincount(expected, minlength=256), np.bincount(actual, minlength=256)).sum() + header = expected[:12].tobytes() + print(f"reference {label} recorder byte overlap: {common}/{len(expected)}, actual nonzero {len(actual)}") + for name, plane in (("raw", red), ("vertical flip", red[::-1]), + ("horizontal flip", red[:, ::-1]), ("transpose", red.T)): + stream = plane.ravel().tobytes() + print(f"reference {label} {name}: native header index {stream.find(header)}") finally: unity.close() except Exception as error: From fddae68a2124978cbcc65a7270fb142660d518fd Mon Sep 17 00:00:00 2001 From: maomao868 <196136225+maomao868@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:05:19 -0800 Subject: [PATCH 09/17] Check text pixel alignment and improve simulator test startup --- .../tests/check-towermind-network.sh | 2 +- .../tests/test_towermind_native.py | 30 ++++++++++++++----- 2 files changed, 24 insertions(+), 8 deletions(-) diff --git a/game_first_exam/tests/check-towermind-network.sh b/game_first_exam/tests/check-towermind-network.sh index 912aede..7519f0e 100644 --- a/game_first_exam/tests/check-towermind-network.sh +++ b/game_first_exam/tests/check-towermind-network.sh @@ -9,7 +9,7 @@ cleanup() { } docker network create --internal "$network" >/dev/null trap cleanup EXIT -docker run -d --name "$sim" --network "$network" --network-alias sim \ +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" diff --git a/game_first_exam/tests/test_towermind_native.py b/game_first_exam/tests/test_towermind_native.py index 2e38156..a50c81c 100644 --- a/game_first_exam/tests/test_towermind_native.py +++ b/game_first_exam/tests/test_towermind_native.py @@ -64,14 +64,30 @@ def report_texture_transport(player, wrappers): else: print(f"reference {label} recorder: length {len(recorded)}, valid JSON") expected = np.array([ord(char) % 256 for char in recorded] + [64], dtype=np.uint8) - actual = red[red != 0] - common = np.minimum(np.bincount(expected, minlength=256), np.bincount(actual, minlength=256)).sum() header = expected[:12].tobytes() - print(f"reference {label} recorder byte overlap: {common}/{len(expected)}, actual nonzero {len(actual)}") - for name, plane in (("raw", red), ("vertical flip", red[::-1]), - ("horizontal flip", red[:, ::-1]), ("transpose", red.T)): - stream = plane.ravel().tobytes() - print(f"reference {label} {name}: native header index {stream.find(header)}") + values = np.arange(256) / 255.0 + linear = np.where(values <= 0.04045, values / 12.92, ((values + 0.055) / 1.055) ** 2.4) + srgb = np.where(values <= 0.0031308, 12.92 * values, 1.055 * values ** (1 / 2.4) - 0.055) + for transfer, lut in (("identity", values), ("linear", linear), ("srgb", srgb)): + decoded = np.round(lut * 255).astype(np.uint8)[red] + actual = decoded[decoded != 0] + common = np.minimum(np.bincount(expected, minlength=256), np.bincount(actual, minlength=256)).sum() + print(f"reference {label} {transfer} byte overlap: {common}/{len(expected)}") + for rotation in range(4): + oriented = np.rot90(decoded, rotation) + for mirrored, plane in enumerate((oriented, oriented[:, ::-1])): + stream = plane.ravel().tobytes() + circular = stream + stream + start = circular.find(header) + end = circular.find(b"@", start) if start >= 0 else -1 + if 0 <= start < len(stream) and 0 <= end - start < len(stream): + try: + state = json.loads(circular[start:end]) + except (ValueError, UnicodeDecodeError): + continue + if isinstance(state, dict) and "Level_Current_Health" in state: + print(f"reference {label} valid JSON with {transfer}, " + f"rotation={rotation * 90}, mirrored={bool(mirrored)}, offset={start}") finally: unity.close() except Exception as error: From e87b95c07f7bac59f8d51b47a5ad8de3f836e067 Mon Sep 17 00:00:00 2001 From: maomao868 <196136225+maomao868@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:19:04 -0800 Subject: [PATCH 10/17] Test official TowerMind Direct3D player in Linux isolation --- .github/workflows/games.yml | 6 ++ .../tests/envs/towermind.Dockerfile | 11 ++++ .../tests/towermind_windows_probe.py | 65 +++++++++++++++++++ 3 files changed, 82 insertions(+) create mode 100644 game_first_exam/tests/towermind_windows_probe.py diff --git a/.github/workflows/games.yml b/.github/workflows/games.yml index 1869623..4042f3a 100644 --- a/.github/workflows/games.yml +++ b/.github/workflows/games.yml @@ -39,6 +39,12 @@ jobs: 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: ${{ failure() && matrix.benchmark == 'towermind' }} + name: Check the official Windows player under Wine + run: | + docker build --target windows-probe -f game_first_exam/tests/envs/towermind.Dockerfile -t game-tests:towermind-wine . + docker run --rm --init --network none -v "$PWD:/repo:ro" game-tests:towermind-wine \ + xvfb-run -a -s "-screen 0 1400x900x24" python game_first_exam/tests/towermind_windows_probe.py harbor: runs-on: ubuntu-latest timeout-minutes: 15 diff --git a/game_first_exam/tests/envs/towermind.Dockerfile b/game_first_exam/tests/envs/towermind.Dockerfile index d09e609..3cf8afa 100644 --- a/game_first_exam/tests/envs/towermind.Dockerfile +++ b/game_first_exam/tests/envs/towermind.Dockerfile @@ -26,3 +26,14 @@ COPY game_first_exam/tests/towermind_fixture.py game_first_exam/tests/test_tower 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"] + +FROM sim AS windows-probe +USER root +RUN apt-get update && apt-get install -y --no-install-recommends wine64 \ + && rm -rf /var/lib/apt/lists/* +ADD --chmod=0444 --checksum=sha256:1828afe2608a154e1107e42aa3f49dad85dd34bf9d98e1adc0c802100c37521b \ + https://raw.githubusercontent.com/tb6147877/TowerMind/7ac5d5cb815ce022cdf6f6d40fa0a9fcc9be3e71/compressed_env/windows.zip \ + /opt/towermind/windows.zip +USER 65534:65534 + +FROM sim AS default diff --git a/game_first_exam/tests/towermind_windows_probe.py b/game_first_exam/tests/towermind_windows_probe.py new file mode 100644 index 0000000..03f0f32 --- /dev/null +++ b/game_first_exam/tests/towermind_windows_probe.py @@ -0,0 +1,65 @@ +"""Test the official Windows player under Wine on the Linux CI runner.""" +import json +import os +from pathlib import Path +import shlex +from tempfile import TemporaryDirectory +from zipfile import ZipFile + +import towermind_fixture +from mlagents_envs.side_channel.engine_configuration_channel import EngineConfigurationChannel +from native import LocalUnity, NO_OP, load_gym_bridge, load_source + + +def main(): + assets = Path("/opt/towermind") + wrappers = load_source("_towermind_windows_wrappers", assets / "wrappers.py") + with TemporaryDirectory() as directory, ZipFile(assets / "windows.zip") as package: + work = Path(directory) + package.extractall(work) + player = work / "windows/TowerDefence.exe" + config = player.parent / "TowerDefence_Data/StreamingAssets/Config" + path = config / "EnvConfig.json" + settings = json.loads(path.read_text(encoding="utf-8-sig")) + settings["RandomSeed"] = 42 + path.write_text(json.dumps(settings), encoding="utf-8") + (config / "FixedLevelsConfig.json").write_text('{"CurrentLevel":0}', encoding="utf-8") + os.environ["WINEPREFIX"] = str(work / "prefix") + os.environ["WINEDLLOVERRIDES"] = "mscoree,mshtml=" + os.environ["WINEDEBUG"] = "-all" + launcher = work / "launch.x86_64" + launcher.write_text(f'#!/bin/sh\nexec /usr/lib/wine/wine64 {shlex.quote(str(player))} "$@"\n') + launcher.chmod(0o700) + channel = EngineConfigurationChannel() + channel.set_configuration_parameters(target_frame_rate=-1, time_scale=20.0, capture_frame_rate=60) + log = work / "player.log" + unity = None + try: + unity = LocalUnity( + file_name=str(launcher), timeout_wait=90, side_channels=[channel], + additional_args=["-batchmode", "-force-d3d11", "-logFile", f"Z:{log}"], + ) + 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 + ) + game = wrappers.TowerMindActionMappingWrapper(observations) + observation = game.reset() + assert set(observation) == {"image", "text"} + for action in [NO_OP, (-1.5, 1.2, 2)] * 3: + observation, _, done, _ = game.step(action) + assert not done and "Agent_Last_Action_Info" in observation["text"] + print("Official TowerMind Windows player and JSON decoder ran six decisions under Wine.") + except json.JSONDecodeError as error: + raise ValueError(f"Windows player text decode failed at offset {error.pos}, length {len(error.doc)}") from None + finally: + if unity is not None and unity._loaded: + unity.close() + if log.is_file(): + for line in log.read_text(encoding="utf-8", errors="replace").splitlines(): + if line.strip().startswith(("Renderer:", "Direct3D:", "Forcing GfxDevice:")): + print(line.strip()) + + +if __name__ == "__main__": + main() From 11adefdbf002189af624f8566d4a5d24c252e92f Mon Sep 17 00:00:00 2001 From: maomao868 <196136225+maomao868@users.noreply.github.com> Date: Sat, 21 Nov 2026 06:01:54 -0800 Subject: [PATCH 11/17] Match the official TowerMind seed sequence and test Mesa sampling --- .github/workflows/games.yml | 7 +- .../benchmarks/towermind/README.md | 2 +- .../benchmarks/towermind/adapter.py | 6 +- .../benchmarks/towermind/native.py | 4 +- .../images/towermind-files/FILES.json | 6 +- .../images/towermind-files/VERSION | 2 +- .../tests/envs/towermind.Dockerfile | 12 +--- .../tests/test_towermind_contract.py | 5 +- .../tests/test_towermind_native.py | 45 ++++++++++++- .../tests/towermind_windows_probe.py | 65 ------------------- 10 files changed, 61 insertions(+), 93 deletions(-) delete mode 100644 game_first_exam/tests/towermind_windows_probe.py diff --git a/.github/workflows/games.yml b/.github/workflows/games.yml index 4042f3a..0e46b6d 100644 --- a/.github/workflows/games.yml +++ b/.github/workflows/games.yml @@ -40,11 +40,10 @@ jobs: 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: ${{ failure() && matrix.benchmark == 'towermind' }} - name: Check the official Windows player under Wine + name: Diagnose the Linux renderer with the stock TowerMind wrapper run: | - docker build --target windows-probe -f game_first_exam/tests/envs/towermind.Dockerfile -t game-tests:towermind-wine . - docker run --rm --init --network none -v "$PWD:/repo:ro" game-tests:towermind-wine \ - xvfb-run -a -s "-screen 0 1400x900x24" python game_first_exam/tests/towermind_windows_probe.py + docker run --rm --init --network none -v "$PWD:/repo:ro" game-tests:towermind \ + xvfb-run -a -s "-screen 0 1400x900x24" python game_first_exam/tests/test_towermind_native.py --probe-renderers harbor: runs-on: ubuntu-latest timeout-minutes: 15 diff --git a/game_first_exam/benchmarks/towermind/README.md b/game_first_exam/benchmarks/towermind/README.md index b172325..911ce39 100644 --- a/game_first_exam/benchmarks/towermind/README.md +++ b/game_first_exam/benchmarks/towermind/README.md @@ -1,6 +1,6 @@ # 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. All other settings come from the pinned archive. +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. diff --git a/game_first_exam/benchmarks/towermind/adapter.py b/game_first_exam/benchmarks/towermind/adapter.py index b0002ff..e34264f 100644 --- a/game_first_exam/benchmarks/towermind/adapter.py +++ b/game_first_exam/benchmarks/towermind/adapter.py @@ -28,10 +28,10 @@ def parse_action(action): return float(x), float(y), int(action_type) -def open_native(player, wrappers_path, seed): +def open_native(player, wrappers_path): from native import open_native as launch - return launch(player, wrappers_path, seed) + return launch(player, wrappers_path) class Adapter: @@ -50,7 +50,7 @@ def __init__(self, instance, assets=None): 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", instance["seed"]) + self._env, observation = open_native(player, source / "wrappers.py") self._cache(observation) except Exception: self.close() diff --git a/game_first_exam/benchmarks/towermind/native.py b/game_first_exam/benchmarks/towermind/native.py index cd315fe..b5e3bd6 100644 --- a/game_first_exam/benchmarks/towermind/native.py +++ b/game_first_exam/benchmarks/towermind/native.py @@ -94,14 +94,14 @@ def _convert_obs(self, observation): return NativeObservations(gym, use_image=True, use_text=True, use_state=False) -def open_native(player, wrappers_path, seed): +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), seed=seed, base_port=RPC_PORT, timeout_wait=60, + file_name=str(player), base_port=RPC_PORT, timeout_wait=60, side_channels=[channel], log_folder=str(player.parent), ) try: diff --git a/game_first_exam/images/towermind-files/FILES.json b/game_first_exam/images/towermind-files/FILES.json index 08d0604..c631620 100644 --- a/game_first_exam/images/towermind-files/FILES.json +++ b/game_first_exam/images/towermind-files/FILES.json @@ -1,11 +1,11 @@ { - "image": "ghcr.io/mll-lab-nu/efe:towermind-files-0.1.5@sha256:80b25b33143f709ea28dc41d3cd37c4260c253db751a9fa46fd2c77808e0c6b4", + "image": "ghcr.io/mll-lab-nu/efe:towermind-files-0.1.6@sha256:2a3795343de02eda0a5e1c3e10fb15b7b237b254571705b502c2385c3d912bdd", "source": "game_first_exam/benchmarks/towermind", "files": { - "adapter.py": "46364b24f4c860f7c51f5c81a78881474b7eeb8dad1d1b00acf87c92cce4aa67", + "adapter.py": "772157c6f86a927dcd4139936cb71766e26f426c69ab6e71c3d023caeaf8ef70", "instance_schema.py": "7ba5a1089c0a47770e92dda1e05effa177e99249c595821789aa6de2426a6b30", "metric_rules.py": "992513d482e4dc39edf5bb71c17c6acfe6fedd771d2692144538cf280b56ad47", - "native.py": "6d78160f7cd442e9526d4401d12d3f4b7b80fd600675394af389d42e508728fa", + "native.py": "4fc3cbdbf8d4b4ef411ab15e66117aff69d178071565afb2d170f6a994c2ade5", "native_assets.py": "f1aec5a05ead72025554c1183a806409b23e61951cfb3bfb7f7467d381eee9d7", "requirements.txt": "1dae4bbe8f73c36d8ef74c6b9fcd6eedc20a8a7ce239d8e247122ac01f54b43a", "SOURCE.json": "f1cd82c5b88d0095c0d3087ed5a7c5f76f2a8160414b199793d24ea378dad989" diff --git a/game_first_exam/images/towermind-files/VERSION b/game_first_exam/images/towermind-files/VERSION index 9faa1b7..c946ee6 100644 --- a/game_first_exam/images/towermind-files/VERSION +++ b/game_first_exam/images/towermind-files/VERSION @@ -1 +1 @@ -0.1.5 +0.1.6 diff --git a/game_first_exam/tests/envs/towermind.Dockerfile b/game_first_exam/tests/envs/towermind.Dockerfile index 3cf8afa..d86025b 100644 --- a/game_first_exam/tests/envs/towermind.Dockerfile +++ b/game_first_exam/tests/envs/towermind.Dockerfile @@ -15,6 +15,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ libxrender1 libvulkan1 mesa-vulkan-drivers xauth xvfb \ && rm -rf /var/lib/apt/lists/* ENV LIBGL_ALWAYS_SOFTWARE=1 HOME=/tmp +ENV MESA_EXTENSION_OVERRIDE="-GL_EXT_texture_filter_anisotropic -GL_ARB_texture_filter_anisotropic" 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 \ @@ -26,14 +27,3 @@ COPY game_first_exam/tests/towermind_fixture.py game_first_exam/tests/test_tower 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"] - -FROM sim AS windows-probe -USER root -RUN apt-get update && apt-get install -y --no-install-recommends wine64 \ - && rm -rf /var/lib/apt/lists/* -ADD --chmod=0444 --checksum=sha256:1828afe2608a154e1107e42aa3f49dad85dd34bf9d98e1adc0c802100c37521b \ - https://raw.githubusercontent.com/tb6147877/TowerMind/7ac5d5cb815ce022cdf6f6d40fa0a9fcc9be3e71/compressed_env/windows.zip \ - /opt/towermind/windows.zip -USER 65534:65534 - -FROM sim AS default diff --git a/game_first_exam/tests/test_towermind_contract.py b/game_first_exam/tests/test_towermind_contract.py index 7667619..de9d63e 100644 --- a/game_first_exam/tests/test_towermind_contract.py +++ b/game_first_exam/tests/test_towermind_contract.py @@ -121,12 +121,13 @@ def reset(self): TowerMindActionMappingWrapper=lambda env: env, ) with ( - patch.object(native, "LocalUnity", return_value=unity), + 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"), 42) + 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) diff --git a/game_first_exam/tests/test_towermind_native.py b/game_first_exam/tests/test_towermind_native.py index a50c81c..cc2bc7e 100644 --- a/game_first_exam/tests/test_towermind_native.py +++ b/game_first_exam/tests/test_towermind_native.py @@ -1,6 +1,9 @@ """Native equivalence and timing checks for the pinned TowerMind Linux player.""" import json +import os import socket +import sys +from unittest.mock import patch from json import JSONDecodeError from pathlib import Path from tempfile import TemporaryDirectory @@ -98,6 +101,43 @@ def report_texture_transport(player, wrappers): print(f"reference {label}: {line.strip()}") +def probe_renderers(): + wrappers = load_source("_towermind_render_probe", NATIVE_ASSETS / "wrappers.py") + for label, overrides in ( + ("anisotropy-off", {}), + ("stock", {"MESA_EXTENSION_OVERRIDE": ""}), + ("alternate-sampler", {"MESA_EXTENSION_OVERRIDE": "", "GALLIVM_PERF": "no_aos_sampling"}), + ("point-sampling", {"LP_PERF": "no_linear"}), + ("softpipe", {"GALLIUM_DRIVER": "softpipe"}), + ("zink", {"GALLIUM_DRIVER": "zink", "MESA_LOADER_DRIVER_OVERRIDE": "zink"}), + ): + print(f"Starting renderer probe {label}", flush=True) + with TemporaryDirectory() as directory, patch.dict(os.environ, overrides): + player = prepare_game(NATIVE_ASSETS, Path(directory), instance()) + channel = EngineConfigurationChannel() + channel.set_configuration_parameters(target_frame_rate=-1, time_scale=20.0, capture_frame_rate=60) + unity = None + try: + unity = UnityEnvironment(file_name=str(player), timeout_wait=25, side_channels=[channel], + log_folder=str(player.parent)) + bridge = load_gym_bridge()(unity, uint8_visual=True, allow_multiple_obs=True) + obs = wrappers.TowerMindMultiModalObsWrapper(bridge, use_image=True, use_text=True, use_state=False) + env = wrappers.TowerMindActionMappingWrapper(obs) + observation = env.reset() + assert "Level_Current_Health" in observation["text"] + for _, action in COMMANDS[:6]: + observation, _, done, _ = env.step(action) + assert not done and "Agent_Last_Action_Info" in observation["text"] + print(f"Renderer probe {label}: passed six native decisions", flush=True) + except JSONDecodeError as error: + print(f"Renderer probe {label}: invalid JSON at {error.pos}, length {len(error.doc)}", flush=True) + except Exception as error: + print(f"Renderer probe {label}: {type(error).__name__}", flush=True) + finally: + if unity is not None and unity._loaded: + unity.close() + + class TowerMindNative(unittest.TestCase): def test_01_upstream_reference_matches_the_adapter_through_termination(self): config = instance() @@ -203,4 +243,7 @@ def test_public_service_keeps_native_result_on_a_budget_stop(self): if __name__ == "__main__": - unittest.main() + if sys.argv[1:] == ["--probe-renderers"]: + probe_renderers() + else: + unittest.main() diff --git a/game_first_exam/tests/towermind_windows_probe.py b/game_first_exam/tests/towermind_windows_probe.py deleted file mode 100644 index 03f0f32..0000000 --- a/game_first_exam/tests/towermind_windows_probe.py +++ /dev/null @@ -1,65 +0,0 @@ -"""Test the official Windows player under Wine on the Linux CI runner.""" -import json -import os -from pathlib import Path -import shlex -from tempfile import TemporaryDirectory -from zipfile import ZipFile - -import towermind_fixture -from mlagents_envs.side_channel.engine_configuration_channel import EngineConfigurationChannel -from native import LocalUnity, NO_OP, load_gym_bridge, load_source - - -def main(): - assets = Path("/opt/towermind") - wrappers = load_source("_towermind_windows_wrappers", assets / "wrappers.py") - with TemporaryDirectory() as directory, ZipFile(assets / "windows.zip") as package: - work = Path(directory) - package.extractall(work) - player = work / "windows/TowerDefence.exe" - config = player.parent / "TowerDefence_Data/StreamingAssets/Config" - path = config / "EnvConfig.json" - settings = json.loads(path.read_text(encoding="utf-8-sig")) - settings["RandomSeed"] = 42 - path.write_text(json.dumps(settings), encoding="utf-8") - (config / "FixedLevelsConfig.json").write_text('{"CurrentLevel":0}', encoding="utf-8") - os.environ["WINEPREFIX"] = str(work / "prefix") - os.environ["WINEDLLOVERRIDES"] = "mscoree,mshtml=" - os.environ["WINEDEBUG"] = "-all" - launcher = work / "launch.x86_64" - launcher.write_text(f'#!/bin/sh\nexec /usr/lib/wine/wine64 {shlex.quote(str(player))} "$@"\n') - launcher.chmod(0o700) - channel = EngineConfigurationChannel() - channel.set_configuration_parameters(target_frame_rate=-1, time_scale=20.0, capture_frame_rate=60) - log = work / "player.log" - unity = None - try: - unity = LocalUnity( - file_name=str(launcher), timeout_wait=90, side_channels=[channel], - additional_args=["-batchmode", "-force-d3d11", "-logFile", f"Z:{log}"], - ) - 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 - ) - game = wrappers.TowerMindActionMappingWrapper(observations) - observation = game.reset() - assert set(observation) == {"image", "text"} - for action in [NO_OP, (-1.5, 1.2, 2)] * 3: - observation, _, done, _ = game.step(action) - assert not done and "Agent_Last_Action_Info" in observation["text"] - print("Official TowerMind Windows player and JSON decoder ran six decisions under Wine.") - except json.JSONDecodeError as error: - raise ValueError(f"Windows player text decode failed at offset {error.pos}, length {len(error.doc)}") from None - finally: - if unity is not None and unity._loaded: - unity.close() - if log.is_file(): - for line in log.read_text(encoding="utf-8", errors="replace").splitlines(): - if line.strip().startswith(("Renderer:", "Direct3D:", "Forcing GfxDevice:")): - print(line.strip()) - - -if __name__ == "__main__": - main() From 1abedd4d3c4085ccbe9816fa684864a8c20e969f Mon Sep 17 00:00:00 2001 From: maomao868 <196136225+maomao868@users.noreply.github.com> Date: Sat, 21 Nov 2026 06:07:14 -0800 Subject: [PATCH 12/17] Preserve TowerMind JSON texture bytes in the isolated Linux player --- .github/workflows/games.yml | 5 - .../benchmarks/towermind/README.md | 2 +- .../benchmarks/towermind/native_assets.py | 11 +- .../images/towermind-files/FILES.json | 4 +- .../images/towermind-files/VERSION | 2 +- .../tests/envs/towermind.Dockerfile | 1 - .../tests/test_towermind_native.py | 135 ++---------------- game_first_exam/tests/towermind_probe.py | 5 +- 8 files changed, 29 insertions(+), 136 deletions(-) diff --git a/.github/workflows/games.yml b/.github/workflows/games.yml index 0e46b6d..1869623 100644 --- a/.github/workflows/games.yml +++ b/.github/workflows/games.yml @@ -39,11 +39,6 @@ jobs: 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: ${{ failure() && matrix.benchmark == 'towermind' }} - name: Diagnose the Linux renderer with the stock TowerMind wrapper - run: | - docker run --rm --init --network none -v "$PWD:/repo:ro" game-tests:towermind \ - xvfb-run -a -s "-screen 0 1400x900x24" python game_first_exam/tests/test_towermind_native.py --probe-renderers harbor: runs-on: ubuntu-latest timeout-minutes: 15 diff --git a/game_first_exam/benchmarks/towermind/README.md b/game_first_exam/benchmarks/towermind/README.md index 911ce39..2dc12fa 100644 --- a/game_first_exam/benchmarks/towermind/README.md +++ b/game_first_exam/benchmarks/towermind/README.md @@ -10,7 +10,7 @@ The development instance reports cumulative native reward as its primary metric. 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. 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. Its development instance is for integration tests. +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. Its development instance is for integration tests. Run from the repository root on a Linux Docker host. diff --git a/game_first_exam/benchmarks/towermind/native_assets.py b/game_first_exam/benchmarks/towermind/native_assets.py index 0eae060..379d0c9 100644 --- a/game_first_exam/benchmarks/towermind/native_assets.py +++ b/game_first_exam/benchmarks/towermind/native_assets.py @@ -51,7 +51,16 @@ def prepare_game(assets, workspace, instance): (configs / "FixedLevelsConfig.json").write_text( json.dumps({"CurrentLevel": instance["level_id"]}), encoding="utf-8" ) - return player + # 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__": diff --git a/game_first_exam/images/towermind-files/FILES.json b/game_first_exam/images/towermind-files/FILES.json index c631620..1afac26 100644 --- a/game_first_exam/images/towermind-files/FILES.json +++ b/game_first_exam/images/towermind-files/FILES.json @@ -1,12 +1,12 @@ { - "image": "ghcr.io/mll-lab-nu/efe:towermind-files-0.1.6@sha256:2a3795343de02eda0a5e1c3e10fb15b7b237b254571705b502c2385c3d912bdd", + "image": "ghcr.io/mll-lab-nu/efe:towermind-files-0.1.7@sha256:203a7dfd1ecbc1d85cb2277aca0c125ba6ca405b3e6d0e48fd1c938c59c11e59", "source": "game_first_exam/benchmarks/towermind", "files": { "adapter.py": "772157c6f86a927dcd4139936cb71766e26f426c69ab6e71c3d023caeaf8ef70", "instance_schema.py": "7ba5a1089c0a47770e92dda1e05effa177e99249c595821789aa6de2426a6b30", "metric_rules.py": "992513d482e4dc39edf5bb71c17c6acfe6fedd771d2692144538cf280b56ad47", "native.py": "4fc3cbdbf8d4b4ef411ab15e66117aff69d178071565afb2d170f6a994c2ade5", - "native_assets.py": "f1aec5a05ead72025554c1183a806409b23e61951cfb3bfb7f7467d381eee9d7", + "native_assets.py": "22fdc08da4222f5b76bf2f4d9448e29a04e412ef678e04e6d1e208bb46efb52f", "requirements.txt": "1dae4bbe8f73c36d8ef74c6b9fcd6eedc20a8a7ce239d8e247122ac01f54b43a", "SOURCE.json": "f1cd82c5b88d0095c0d3087ed5a7c5f76f2a8160414b199793d24ea378dad989" } diff --git a/game_first_exam/images/towermind-files/VERSION b/game_first_exam/images/towermind-files/VERSION index c946ee6..1180819 100644 --- a/game_first_exam/images/towermind-files/VERSION +++ b/game_first_exam/images/towermind-files/VERSION @@ -1 +1 @@ -0.1.6 +0.1.7 diff --git a/game_first_exam/tests/envs/towermind.Dockerfile b/game_first_exam/tests/envs/towermind.Dockerfile index d86025b..d09e609 100644 --- a/game_first_exam/tests/envs/towermind.Dockerfile +++ b/game_first_exam/tests/envs/towermind.Dockerfile @@ -15,7 +15,6 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ libxrender1 libvulkan1 mesa-vulkan-drivers xauth xvfb \ && rm -rf /var/lib/apt/lists/* ENV LIBGL_ALWAYS_SOFTWARE=1 HOME=/tmp -ENV MESA_EXTENSION_OVERRIDE="-GL_EXT_texture_filter_anisotropic -GL_ARB_texture_filter_anisotropic" 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 \ diff --git a/game_first_exam/tests/test_towermind_native.py b/game_first_exam/tests/test_towermind_native.py index cc2bc7e..777dd60 100644 --- a/game_first_exam/tests/test_towermind_native.py +++ b/game_first_exam/tests/test_towermind_native.py @@ -1,14 +1,12 @@ """Native equivalence and timing checks for the pinned TowerMind Linux player.""" -import json import os import socket -import sys -from unittest.mock import patch 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 @@ -26,130 +24,22 @@ MAX_REFERENCE_DECISIONS = 4096 -def report_texture_transport(player, wrappers): - # The native recorder writes the same payload before it goes through the - # texture transport. Enable it only in this disposable diagnostic copy. - config_path = player.parent / "td_Data/StreamingAssets/Config/EnvConfig.json" - config = json.loads(config_path.read_text(encoding="utf-8")) - records = player.parent / "diagnostic-records" - records.mkdir() - config.update(IsRecordingEnabled=1, RecordingPath=str(records)) - config_path.write_text(json.dumps(config), encoding="utf-8") - for args in ([], ["-force-gfx-direct"]): - label = args[0] if args else "default" - log_path = player.parent / f"diagnostic-{label}.log" - settings = EngineConfigurationChannel() - settings.set_configuration_parameters(target_frame_rate=-1, time_scale=20.0, capture_frame_rate=60) - try: - unity = UnityEnvironment(file_name=str(player), side_channels=[settings], timeout_wait=20, - additional_args=args + ["-logFile", str(log_path)], seed=42) - try: - bridge = load_gym_bridge()(unity, uint8_visual=True, allow_multiple_obs=True) - texture = bridge.reset()[1] - red = texture[0] - rows = np.count_nonzero(red, axis=1) - print(f"reference {label} nonzero texture pixels in first/last 20 rows: {rows[:20]}, {rows[-20:]}") - try: - wrappers.get_json_from_obs(texture) - except json.JSONDecodeError as error: - print(f"reference {label} stock decoder: length {len(error.doc)}, offset {error.pos}") - else: - print(f"reference {label} stock decoder: valid JSON") - paths = sorted(records.glob("*/game_internal_states/*"), key=lambda p: p.stat().st_mtime_ns) - if not paths: - print(f"reference {label} native diagnostic record absent") - continue - recorded = paths[-1].read_text(encoding="utf-8-sig") - try: - json.loads(recorded) - except json.JSONDecodeError as error: - print(f"reference {label} recorder: length {len(recorded)}, invalid JSON at {error.pos}") - else: - print(f"reference {label} recorder: length {len(recorded)}, valid JSON") - expected = np.array([ord(char) % 256 for char in recorded] + [64], dtype=np.uint8) - header = expected[:12].tobytes() - values = np.arange(256) / 255.0 - linear = np.where(values <= 0.04045, values / 12.92, ((values + 0.055) / 1.055) ** 2.4) - srgb = np.where(values <= 0.0031308, 12.92 * values, 1.055 * values ** (1 / 2.4) - 0.055) - for transfer, lut in (("identity", values), ("linear", linear), ("srgb", srgb)): - decoded = np.round(lut * 255).astype(np.uint8)[red] - actual = decoded[decoded != 0] - common = np.minimum(np.bincount(expected, minlength=256), np.bincount(actual, minlength=256)).sum() - print(f"reference {label} {transfer} byte overlap: {common}/{len(expected)}") - for rotation in range(4): - oriented = np.rot90(decoded, rotation) - for mirrored, plane in enumerate((oriented, oriented[:, ::-1])): - stream = plane.ravel().tobytes() - circular = stream + stream - start = circular.find(header) - end = circular.find(b"@", start) if start >= 0 else -1 - if 0 <= start < len(stream) and 0 <= end - start < len(stream): - try: - state = json.loads(circular[start:end]) - except (ValueError, UnicodeDecodeError): - continue - if isinstance(state, dict) and "Level_Current_Health" in state: - print(f"reference {label} valid JSON with {transfer}, " - f"rotation={rotation * 90}, mirrored={bool(mirrored)}, offset={start}") - finally: - unity.close() - except Exception as error: - print(f"reference {label} transport probe failed: {type(error).__name__}") - if log_path.exists(): - for line in log_path.read_text(encoding="utf-8", errors="replace").splitlines(): - if line.startswith(("Renderer:", "Vendor:", "Version:", "GfxDevice:", "OpenGL", "Vulkan")): - print(f"reference {label}: {line.strip()}") - - -def probe_renderers(): - wrappers = load_source("_towermind_render_probe", NATIVE_ASSETS / "wrappers.py") - for label, overrides in ( - ("anisotropy-off", {}), - ("stock", {"MESA_EXTENSION_OVERRIDE": ""}), - ("alternate-sampler", {"MESA_EXTENSION_OVERRIDE": "", "GALLIVM_PERF": "no_aos_sampling"}), - ("point-sampling", {"LP_PERF": "no_linear"}), - ("softpipe", {"GALLIUM_DRIVER": "softpipe"}), - ("zink", {"GALLIUM_DRIVER": "zink", "MESA_LOADER_DRIVER_OVERRIDE": "zink"}), - ): - print(f"Starting renderer probe {label}", flush=True) - with TemporaryDirectory() as directory, patch.dict(os.environ, overrides): - player = prepare_game(NATIVE_ASSETS, Path(directory), instance()) - channel = EngineConfigurationChannel() - channel.set_configuration_parameters(target_frame_rate=-1, time_scale=20.0, capture_frame_rate=60) - unity = None - try: - unity = UnityEnvironment(file_name=str(player), timeout_wait=25, side_channels=[channel], - log_folder=str(player.parent)) - bridge = load_gym_bridge()(unity, uint8_visual=True, allow_multiple_obs=True) - obs = wrappers.TowerMindMultiModalObsWrapper(bridge, use_image=True, use_text=True, use_state=False) - env = wrappers.TowerMindActionMappingWrapper(obs) - observation = env.reset() - assert "Level_Current_Health" in observation["text"] - for _, action in COMMANDS[:6]: - observation, _, done, _ = env.step(action) - assert not done and "Agent_Last_Action_Info" in observation["text"] - print(f"Renderer probe {label}: passed six native decisions", flush=True) - except JSONDecodeError as error: - print(f"Renderer probe {label}: invalid JSON at {error.pos}, length {len(error.doc)}", flush=True) - except Exception as error: - print(f"Renderer probe {label}: {type(error).__name__}", flush=True) - finally: - if unity is not None and unity._loaded: - unity.close() - - class TowerMindNative(unittest.TestCase): def test_01_upstream_reference_matches_the_adapter_through_termination(self): config = instance() with TemporaryDirectory() as workspace: - player = prepare_game(NATIVE_ASSETS, Path(workspace), config) + 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) - unity = UnityEnvironment(file_name=str(player), side_channels=[settings], - timeout_wait=60, log_folder=str(player.parent)) + # 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( @@ -160,8 +50,6 @@ def test_01_upstream_reference_matches_the_adapter_through_termination(self): initial = env.reset() except JSONDecodeError as error: specs = [(spec.name, spec.shape) for spec in bridge.group_spec.observation_specs] - unity.close() - report_texture_transport(player, wrappers) 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}" @@ -209,6 +97,7 @@ def test_01_upstream_reference_matches_the_adapter_through_termination(self): (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 @@ -218,6 +107,7 @@ def test_01_upstream_reference_matches_the_adapter_through_termination(self): 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: @@ -243,7 +133,4 @@ def test_public_service_keeps_native_result_on_a_budget_stop(self): if __name__ == "__main__": - if sys.argv[1:] == ["--probe-renderers"]: - probe_renderers() - else: - unittest.main() + unittest.main() diff --git a/game_first_exam/tests/towermind_probe.py b/game_first_exam/tests/towermind_probe.py index a9adf54..5c9c906 100644 --- a/game_first_exam/tests/towermind_probe.py +++ b/game_first_exam/tests/towermind_probe.py @@ -20,8 +20,11 @@ def main(): raise AssertionError("the simulator's loopback RPC port is reachable from the client") except (ConnectionRefusedError, TimeoutError): pass - for private_path in ("/opt/towermind", "/repo", "/srv", "/data"): + 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"} From dad7a7329296de58d2b8806aeba31e6caf1bd164 Mon Sep 17 00:00:00 2001 From: maomao868 <196136225+maomao868@users.noreply.github.com> Date: Sat, 21 Nov 2026 06:10:04 -0800 Subject: [PATCH 13/17] Register the TowerMind benchmark using a development-only validation fixture --- configs/game_benchmarks.toml | 3 ++ .../benchmarks/towermind/README.md | 4 +-- .../benchmarks/towermind/instance_schema.py | 5 +-- .../images/towermind-files/FILES.json | 4 +-- .../images/towermind-files/VERSION | 2 +- .../tests/envs/towermind.Dockerfile | 1 + .../tests/fixtures/towermind-instance.json | 34 +++++++++++++++++++ .../tests/test_game_configuration.py | 8 +++-- game_first_exam/tests/towermind_fixture.py | 17 ++-------- 9 files changed, 55 insertions(+), 23 deletions(-) create mode 100644 game_first_exam/tests/fixtures/towermind-instance.json 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 index 2dc12fa..750e28a 100644 --- a/game_first_exam/benchmarks/towermind/README.md +++ b/game_first_exam/benchmarks/towermind/README.md @@ -4,13 +4,13 @@ This development integration uses the upstream Unity Linux x86-64 player and bot 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 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 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. Its development instance is for integration tests. +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. diff --git a/game_first_exam/benchmarks/towermind/instance_schema.py b/game_first_exam/benchmarks/towermind/instance_schema.py index f8d15ba..40d588f 100644 --- a/game_first_exam/benchmarks/towermind/instance_schema.py +++ b/game_first_exam/benchmarks/towermind/instance_schema.py @@ -1,6 +1,5 @@ """Trusted adapter profile. Importable without simulator dependencies.""" from config_schema import validate_engine_versions -from contracts import Capabilities SCHEMA_VERSION = "1.0.0" @@ -9,7 +8,9 @@ METRICS = {"native_return"} PROFILES = {"player-rgb-v1"} REDUCERS = {("family_macro", "1.0.0")} -CAPABILITIES = Capabilities(images=True, action_mode="text", native_truncation=True).to_dict() +CAPABILITIES = { + "images": True, "action_mode": "text", "timing": "action-stepped", "native_truncation": True, +} ARCHIVE_SHA256 = "153f363150f5e33f4827599498e2d7bda504045a4ae258e013bb504ea4273e19" ENGINE_VERSIONS = { "mlagents-envs": "1.1.0", diff --git a/game_first_exam/images/towermind-files/FILES.json b/game_first_exam/images/towermind-files/FILES.json index 1afac26..bd37f39 100644 --- a/game_first_exam/images/towermind-files/FILES.json +++ b/game_first_exam/images/towermind-files/FILES.json @@ -1,9 +1,9 @@ { - "image": "ghcr.io/mll-lab-nu/efe:towermind-files-0.1.7@sha256:203a7dfd1ecbc1d85cb2277aca0c125ba6ca405b3e6d0e48fd1c938c59c11e59", + "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": "7ba5a1089c0a47770e92dda1e05effa177e99249c595821789aa6de2426a6b30", + "instance_schema.py": "5839f40497a13cc4a074258db508419e99fc73dcffc0b07c5d6c31e7193cf8c5", "metric_rules.py": "992513d482e4dc39edf5bb71c17c6acfe6fedd771d2692144538cf280b56ad47", "native.py": "4fc3cbdbf8d4b4ef411ab15e66117aff69d178071565afb2d170f6a994c2ade5", "native_assets.py": "22fdc08da4222f5b76bf2f4d9448e29a04e412ef678e04e6d1e208bb46efb52f", diff --git a/game_first_exam/images/towermind-files/VERSION b/game_first_exam/images/towermind-files/VERSION index 1180819..699c6c6 100644 --- a/game_first_exam/images/towermind-files/VERSION +++ b/game_first_exam/images/towermind-files/VERSION @@ -1 +1 @@ -0.1.7 +0.1.8 diff --git a/game_first_exam/tests/envs/towermind.Dockerfile b/game_first_exam/tests/envs/towermind.Dockerfile index d09e609..460d43b 100644 --- a/game_first_exam/tests/envs/towermind.Dockerfile +++ b/game_first_exam/tests/envs/towermind.Dockerfile @@ -22,6 +22,7 @@ RUN pip install --no-cache-dir --no-deps setuptools==84.2.1 wheel==0.45.1 \ && 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 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/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/towermind_fixture.py b/game_first_exam/tests/towermind_fixture.py index 968f680..1f65e93 100644 --- a/game_first_exam/tests/towermind_fixture.py +++ b/game_first_exam/tests/towermind_fixture.py @@ -1,4 +1,5 @@ """Development instance for tests only. No task or suite registration.""" +import json from pathlib import Path import sys @@ -9,26 +10,14 @@ sys.path[:0] = [str(RUNTIME), str(BENCHMARK)] import instance_schema -from config_schema import PROTOCOL, INSTANCE_SCHEMA, register_instance_schema +from config_schema import register_instance_schema register_instance_schema(instance_schema) def instance(): - return { - "schema_version": INSTANCE_SCHEMA, "protocol": PROTOCOL, "adapter_version": "1.0.0", - "capabilities": dict(instance_schema.CAPABILITIES), - "benchmark": "towermind", "env_id": "TowerMind-Level-0", "family": "development", - "level_id": 0, "seed": 42, "max_steps": None, "initial_state_sha256": "0" * 64, - "engine_versions": dict(instance_schema.ENGINE_VERSIONS), - "engine_archive_sha256": instance_schema.ARCHIVE_SHA256, - "observation_profile": "player-rgb-v1", - "metric_spec": { - "primary": "native_return", "success_label": "native_level_completed", - "reducer": "family_macro", "reducer_version": "1.0.0", - }, - } + return json.loads((Path(__file__).parent / "fixtures/towermind-instance.json").read_text()) def serve(): From c714e4d2e142f957cbbcaf2c1340ae735a5d84dd Mon Sep 17 00:00:00 2001 From: maomao868 <196136225+maomao868@users.noreply.github.com> Date: Sat, 21 Nov 2026 21:01:36 -0800 Subject: [PATCH 14/17] Verify TowerMind isolation with a disposable Harbor trial --- .github/workflows/games.yml | 8 + .../tests/check_towermind_harbor.py | 183 ++++++++++++++++++ 2 files changed, 191 insertions(+) create mode 100644 game_first_exam/tests/check_towermind_harbor.py diff --git a/.github/workflows/games.yml b/.github/workflows/games.yml index 1869623..da7ab75 100644 --- a/.github/workflows/games.yml +++ b/.github/workflows/games.yml @@ -39,6 +39,14 @@ jobs: 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/game_first_exam/tests/check_towermind_harbor.py b/game_first_exam/tests/check_towermind_harbor.py new file mode 100644 index 0000000..138ecb6 --- /dev/null +++ b/game_first_exam/tests/check_towermind_harbor.py @@ -0,0 +1,183 @@ +"""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 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): + 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 + """) + 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 + CMD ["xvfb-run", "-a", "-s", "-screen 0 1400x900x24", "python", "/srv/server.py"] + """) + write(task / "environment/sim/instance.json", instance) + write(task / "solution/solve.sh", """ + #!/bin/bash + set -euo pipefail + PYTHONPATH=/app python - <<'PY' + from pathlib import Path + + from towermind_probe import main + + 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}" + + main() + Path("/app/agent-marker").write_text("agent-only filesystem change") + print("Harbor agent container isolation passed.") + PY + """) + write(task / "tests/instance.json", instance) + 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 + python /tests/check_isolation.py + python /tests/grade.py + """) + write(task / "tests/check_isolation.py", """ + import json + from pathlib import Path + import socket + + assert {name for _, name in socket.if_nameindex()} == {"lo"}, "verifier has a network interface" + assert not Path("/app/agent-marker").exists(), "verifier inherited the agent filesystem" + 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" + stage_task(task, freeze_instance()) + job = jobs / "towermind-isolation" + 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/test-stdout.txt", + "*/verifier/test-stderr.txt", "*/trial.log"): + for log in job.glob(pattern): + print(f"{log.name}: {log.read_text(encoding='utf-8', errors='replace')[-3000:]}", flush=True) + run.check_returncode() + marker, = job.glob("*/verifier/isolation.txt") + 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()) From 0c3db1616b85e8dc39a81bae78012673b2d8e24e Mon Sep 17 00:00:00 2001 From: maomao868 <196136225+maomao868@users.noreply.github.com> Date: Sat, 21 Nov 2026 21:04:37 -0800 Subject: [PATCH 15/17] Check Harbor network policy and clear shared verifier logs before grading --- .../benchmarks/towermind/README.md | 2 + .../tests/check_towermind_harbor.py | 42 +++++++++++++++---- 2 files changed, 36 insertions(+), 8 deletions(-) diff --git a/game_first_exam/benchmarks/towermind/README.md b/game_first_exam/benchmarks/towermind/README.md index 750e28a..58f37a9 100644 --- a/game_first_exam/benchmarks/towermind/README.md +++ b/game_first_exam/benchmarks/towermind/README.md @@ -8,6 +8,8 @@ The public `player-rgb-v1` profile exposes one cached 512脳512 RGB player frame 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, sim evidence collection, and a separate verifier with a blocked network connection. 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. diff --git a/game_first_exam/tests/check_towermind_harbor.py b/game_first_exam/tests/check_towermind_harbor.py index 138ecb6..a296896 100644 --- a/game_first_exam/tests/check_towermind_harbor.py +++ b/game_first_exam/tests/check_towermind_harbor.py @@ -3,6 +3,7 @@ from pathlib import Path import re from shutil import copy2 +import socket import subprocess import sys from textwrap import dedent @@ -47,7 +48,7 @@ def freeze_instance(): return json.dumps(config, indent=2) + "\n" -def stage_task(task, instance): +def stage_task(task, instance, endpoint): write(task / "instruction.md", """ # TowerMind isolation smoke test @@ -108,18 +109,28 @@ def stage_task(task, instance): CMD ["xvfb-run", "-a", "-s", "-screen 0 1400x900x24", "python", "/srv/server.py"] """) 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 python - <<'PY' + 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.") main() Path("/app/agent-marker").write_text("agent-only filesystem change") print("Harbor agent container isolation passed.") @@ -134,6 +145,8 @@ def stage_task(task, instance): 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 python /tests/grade.py """) @@ -142,7 +155,15 @@ def stage_task(task, instance): from pathlib import Path import socket - assert {name for _, name in socket.if_nameindex()} == {"lo"}, "verifier has a network interface" + from canary import ADDRESS + + 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" evidence = json.loads(Path("/data/final.json").read_text()) assert evidence["benchmark"] == "towermind" and evidence["result_valid"] is True @@ -160,12 +181,17 @@ def stage_task(task, instance): def main(workdir): task = workdir / "towermind-isolation" jobs = workdir / "jobs" - stage_task(task, freeze_instance()) + instance = freeze_instance() job = jobs / "towermind-isolation" - run = subprocess.run([ - "harbor", "run", "-p", str(task), "-c", str(ROOT / "configs/harbor/oracle.json"), - "--jobs-dir", str(jobs), "--job-name", job.name, "-y", - ]) + 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/test-stdout.txt", "*/verifier/test-stderr.txt", "*/trial.log"): for log in job.glob(pattern): From c8b8de6f3287f83fad3b75294ffc632d8f771ac1 Mon Sep 17 00:00:00 2001 From: maomao868 <196136225+maomao868@users.noreply.github.com> Date: Sat, 21 Nov 2026 21:13:34 -0800 Subject: [PATCH 16/17] Wait for the Harbor TowerMind sidecar to serve its public interface --- .../tests/check_towermind_harbor.py | 34 ++++++++++++++----- 1 file changed, 25 insertions(+), 9 deletions(-) diff --git a/game_first_exam/tests/check_towermind_harbor.py b/game_first_exam/tests/check_towermind_harbor.py index a296896..33e020c 100644 --- a/game_first_exam/tests/check_towermind_harbor.py +++ b/game_first_exam/tests/check_towermind_harbor.py @@ -92,6 +92,13 @@ def stage_task(task, instance, endpoint): 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} @@ -106,7 +113,6 @@ def stage_task(task, instance, endpoint): COPY instance.json /srv/instance.json USER 65534:65534 WORKDIR /srv - CMD ["xvfb-run", "-a", "-s", "-screen 0 1400x900x24", "python", "/srv/server.py"] """) write(task / "environment/sim/instance.json", instance) for directory in ("solution", "tests"): @@ -147,8 +153,8 @@ def stage_task(task, instance, endpoint): 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 - python /tests/grade.py + 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 @@ -190,14 +196,24 @@ def main(workdir): 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", + "--jobs-dir", str(jobs), "--job-name", job.name, "--ek", "keep_containers=true", "-y", ]) - for pattern in ("*/agent/oracle.txt", "*/verifier/isolation.txt", "*/verifier/test-stdout.txt", - "*/verifier/test-stderr.txt", "*/trial.log"): + for pattern in ("*/agent/oracle.txt", "*/verifier/isolation.txt", "*/verifier/*-error.log", "*/trial.log"): for log in job.glob(pattern): - print(f"{log.name}: {log.read_text(encoding='utf-8', errors='replace')[-3000:]}", flush=True) - run.check_returncode() - marker, = job.glob("*/verifier/isolation.txt") + 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(): + containers = subprocess.check_output([ + "docker", "ps", "-aq", "--filter", "label=com.docker.compose.service=sim", + "--filter", f"label=com.docker.compose.project.working_dir={task / 'environment'}", + ], text=True).split() + for container in containers: + subprocess.run(["docker", "inspect", "--format", "{{.Path}} {{json .Args}} {{json .State}}", container]) + subprocess.run(["docker", "logs", "--tail", "50", container]) + run.check_returncode() + raise RuntimeError("the isolated verifier did not generate a grade") + marker = markers[0] 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 From 35bb40aa9f1271b2e9dd32eac55321e74608a68b Mon Sep 17 00:00:00 2001 From: maomao868 <196136225+maomao868@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:34:55 -0800 Subject: [PATCH 17/17] Disable Docker networking for the TowerMind verification container --- .../benchmarks/towermind/README.md | 2 +- .../tests/check_towermind_harbor.py | 20 +++++++++++-------- 2 files changed, 13 insertions(+), 9 deletions(-) diff --git a/game_first_exam/benchmarks/towermind/README.md b/game_first_exam/benchmarks/towermind/README.md index 58f37a9..6e434a0 100644 --- a/game_first_exam/benchmarks/towermind/README.md +++ b/game_first_exam/benchmarks/towermind/README.md @@ -8,7 +8,7 @@ The public `player-rgb-v1` profile exposes one cached 512脳512 RGB player frame 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, sim evidence collection, and a separate verifier with a blocked network connection. 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 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. diff --git a/game_first_exam/tests/check_towermind_harbor.py b/game_first_exam/tests/check_towermind_harbor.py index 33e020c..15004cd 100644 --- a/game_first_exam/tests/check_towermind_harbor.py +++ b/game_first_exam/tests/check_towermind_harbor.py @@ -137,12 +137,19 @@ def stage_task(task, instance, endpoint): 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/ @@ -163,6 +170,7 @@ def stage_task(task, instance, endpoint): 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: @@ -171,6 +179,7 @@ def stage_task(task, instance, endpoint): 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" @@ -196,7 +205,7 @@ def main(workdir): 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, "--ek", "keep_containers=true", "-y", + "--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): @@ -204,16 +213,11 @@ def main(workdir): 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(): - containers = subprocess.check_output([ - "docker", "ps", "-aq", "--filter", "label=com.docker.compose.service=sim", - "--filter", f"label=com.docker.compose.project.working_dir={task / 'environment'}", - ], text=True).split() - for container in containers: - subprocess.run(["docker", "inspect", "--format", "{{.Path}} {{json .Args}} {{json .State}}", container]) - subprocess.run(["docker", "logs", "--tail", "50", container]) 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