From da679d53d86be2c85be696f04701abd408909c92 Mon Sep 17 00:00:00 2001 From: lyh <2641805259@qq.com> Date: Fri, 27 Nov 2026 11:32:28 +0800 Subject: [PATCH 1/2] Add FightingICE benchmark, model duel, and MCTS speedrun --- .github/workflows/games.yml | 2 +- README.md | 17 +- UPSTREAM.md | 7 +- configs/game_benchmarks.toml | 3 + configs/game_suites/fightingice.toml | 15 + docs/VALIDATION.md | 169 +++++++ docs/game_framework.md | 2 +- docs/protocol/running.md | 9 + .../benchmarks/fightingice/LICENSE-pyftg | 21 + .../benchmarks/fightingice/README.md | 172 +++++++ .../benchmarks/fightingice/SOURCE.json | 13 + .../benchmarks/fightingice/adapter.py | 163 +++++++ .../benchmarks/fightingice/bridge.py | 127 +++++ .../fightingice/competition.Dockerfile | 8 + .../benchmarks/fightingice/competition.md | 185 +++++++ .../benchmarks/fightingice/competition.py | 454 ++++++++++++++++++ .../fightingice/competition_author.md | 33 ++ .../fightingice/competition_match.py | 151 ++++++ .../fightingice/competition_results.py | 198 ++++++++ .../fightingice/competition_wire.py | 101 ++++ .../benchmarks/fightingice/install_native.py | 79 +++ .../benchmarks/fightingice/instance_schema.py | 32 ++ .../benchmarks/fightingice/metric_rules.py | 44 ++ .../benchmarks/fightingice/requirements.txt | 9 + .../images/fightingice-files/FILES.json | 14 + .../images/fightingice-files/README.md | 6 + .../images/fightingice-files/VERSION | 1 + game_first_exam/tasks/fightingice/README.md | 12 + .../DIGEST | 1 + .../README.md | 40 ++ .../environment/Dockerfile | 11 + .../environment/docker-compose.yaml | 44 ++ .../environment/rcb_monitor/limits.json | 26 + .../environment/sim/Dockerfile | 14 + .../environment/sim/instance.json | 32 ++ .../instruction.md | 80 +++ .../solution/control.py | 18 + .../solution/solve.sh | 4 + .../task.toml | 58 +++ .../tests/Dockerfile | 8 + .../tests/instance.json | 32 ++ .../tests/rcb_limits.json | 26 + .../tests/test.sh | 6 + .../DIGEST | 1 + .../README.md | 40 ++ .../environment/Dockerfile | 11 + .../environment/docker-compose.yaml | 44 ++ .../environment/rcb_monitor/limits.json | 26 + .../environment/sim/Dockerfile | 14 + .../environment/sim/instance.json | 32 ++ .../instruction.md | 80 +++ .../solution/control.py | 18 + .../solution/solve.sh | 4 + .../task.toml | 58 +++ .../tests/Dockerfile | 8 + .../tests/instance.json | 32 ++ .../tests/rcb_limits.json | 26 + .../tests/test.sh | 6 + .../benchmarks/fightingice/exported.toml | 12 + .../tests/check_fightingice_result.py | 59 +++ .../tests/envs/fightingice.Dockerfile | 10 + .../tests/envs/locks/fightingice.txt | 9 + game_first_exam/tests/run.sh | 5 + game_first_exam/tests/test_fightingice.py | 253 ++++++++++ .../tests/test_fightingice_competition.py | 323 +++++++++++++ .../tests/test_game_configuration.py | 2 +- game_first_exam/tests/test_game_harbor.py | 4 +- scripts/task_conventions.py | 2 + scripts/task_resources.toml | 6 + 69 files changed, 3521 insertions(+), 11 deletions(-) create mode 100644 configs/game_suites/fightingice.toml create mode 100644 game_first_exam/benchmarks/fightingice/LICENSE-pyftg create mode 100644 game_first_exam/benchmarks/fightingice/README.md create mode 100644 game_first_exam/benchmarks/fightingice/SOURCE.json create mode 100644 game_first_exam/benchmarks/fightingice/adapter.py create mode 100644 game_first_exam/benchmarks/fightingice/bridge.py create mode 100644 game_first_exam/benchmarks/fightingice/competition.Dockerfile create mode 100644 game_first_exam/benchmarks/fightingice/competition.md create mode 100644 game_first_exam/benchmarks/fightingice/competition.py create mode 100644 game_first_exam/benchmarks/fightingice/competition_author.md create mode 100644 game_first_exam/benchmarks/fightingice/competition_match.py create mode 100644 game_first_exam/benchmarks/fightingice/competition_results.py create mode 100644 game_first_exam/benchmarks/fightingice/competition_wire.py create mode 100644 game_first_exam/benchmarks/fightingice/install_native.py create mode 100644 game_first_exam/benchmarks/fightingice/instance_schema.py create mode 100644 game_first_exam/benchmarks/fightingice/metric_rules.py create mode 100644 game_first_exam/benchmarks/fightingice/requirements.txt create mode 100644 game_first_exam/images/fightingice-files/FILES.json create mode 100644 game_first_exam/images/fightingice-files/README.md create mode 100644 game_first_exam/images/fightingice-files/VERSION create mode 100644 game_first_exam/tasks/fightingice/README.md create mode 100644 game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/DIGEST create mode 100644 game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/README.md create mode 100644 game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/environment/Dockerfile create mode 100644 game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/environment/docker-compose.yaml create mode 100644 game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/environment/rcb_monitor/limits.json create mode 100644 game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/environment/sim/Dockerfile create mode 100644 game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/environment/sim/instance.json create mode 100644 game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/instruction.md create mode 100644 game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/solution/control.py create mode 100755 game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/solution/solve.sh create mode 100644 game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/task.toml create mode 100644 game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/tests/Dockerfile create mode 100644 game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/tests/instance.json create mode 100644 game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/tests/rcb_limits.json create mode 100755 game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/tests/test.sh create mode 100644 game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/DIGEST create mode 100644 game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/README.md create mode 100644 game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/environment/Dockerfile create mode 100644 game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/environment/docker-compose.yaml create mode 100644 game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/environment/rcb_monitor/limits.json create mode 100644 game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/environment/sim/Dockerfile create mode 100644 game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/environment/sim/instance.json create mode 100644 game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/instruction.md create mode 100644 game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/solution/control.py create mode 100755 game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/solution/solve.sh create mode 100644 game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/task.toml create mode 100644 game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/tests/Dockerfile create mode 100644 game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/tests/instance.json create mode 100644 game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/tests/rcb_limits.json create mode 100755 game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/tests/test.sh create mode 100644 game_first_exam/tests/benchmarks/fightingice/exported.toml create mode 100644 game_first_exam/tests/check_fightingice_result.py create mode 100644 game_first_exam/tests/envs/fightingice.Dockerfile create mode 100644 game_first_exam/tests/envs/locks/fightingice.txt create mode 100644 game_first_exam/tests/test_fightingice.py create mode 100644 game_first_exam/tests/test_fightingice_competition.py diff --git a/.github/workflows/games.yml b/.github/workflows/games.yml index ebee4f6..a6a37a8 100644 --- a/.github/workflows/games.yml +++ b/.github/workflows/games.yml @@ -25,7 +25,7 @@ jobs: strategy: fail-fast: false matrix: - benchmark: [common, minigrid, crafter, textworld, babaisai, minihack] + benchmark: [common, minigrid, crafter, textworld, babaisai, minihack, fightingice] steps: - uses: actions/checkout@v4 with: {persist-credentials: false} diff --git a/README.md b/README.md index 5e00e1f..4e1ac5d 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ Game Exam 基于 [Embodied First Exam](https://github.com/mll-lab-nu/embodied-fi ## 已接入的游戏 -当前共有 **5 个 benchmark、42 个 standard 任务配置,另外有 1 个 privileged 和 1 个 realtime 配置,共 44 个任务目录**。同一原生任务的不同模式单独计数。 +当前共有 **6 个 benchmark、44 个 standard 任务配置,另外有 1 个 privileged 和 1 个 realtime 配置,共 46 个任务目录**。同一原生任务的不同模式单独计数。 | Benchmark | standard | 其他模式 | 主要内容 | 说明 | |---|---:|---|---|---| @@ -33,6 +33,7 @@ Game Exam 基于 [Embodied First Exam](https://github.com/mll-lab-nu/embodied-fi | TextWorld | 9 | — | 文字探索、寻宝、烹饪 | 冻结 `.z8` 游戏,通过原生引擎执行 | | Baba Is AI | 2 | — | 移动文字、改变规则、解谜 | 基础关卡与复合关卡的最小 smoke 验证 | | MiniHack | 10 | 1 privileged | Room、River、导航、战斗、Quest、Boxoban | 原生 MiniHack/NLE 环境;Room 另有 privileged 版本 | +| FightingICE | 2 | — | 双人格斗、动作时序、对手策略 | ZEN 对固定 KickAI,分别控制 P1/P2;原生 Harbor oracle/nop 与隔离验证通过 | 套件由 [configs/game_suites/](configs/game_suites/) 定义,可以重叠,数量不能直接相加: @@ -46,12 +47,17 @@ Game Exam 基于 [Embodied First Exam](https://github.com/mll-lab-nu/embodied-fi | `babaisai` | 2 | Baba Is AI smoke | | `minihack` | 3 | Room/River standard + Room privileged | | `minihack-balrog` | 8 | 参考 BALROG 选取的原生 MiniHack 任务 | -| `all` | 44 | 所有套件去重后的任务;汇总时应选择一种模式 | +| `fightingice` | 2 | 延迟 FrameData、同步 standard;原生三回合 smoke | +| `all` | 46 | 所有套件去重后的任务;汇总时应选择一种模式 | `minihack-balrog` 包含 MazeWalk 9×9、MazeWalk 15×15、Corridor R3、CorridorBattle Dark、Quest Easy、Quest Medium、Boxoban Medium、Boxoban Hard。**使用相同原生环境名称不意味着与 BALROG 的 LLM 输入、prompt、agent、seed 和预算完全相同**,成绩不能直接当作 BALROG 排行榜成绩。 每个游戏的原生版本、观测、冻结参数与已知差异,见对应 [benchmark README](game_first_exam/tasks/);具体实例以任务的 `tests/instance.json`、`task.toml` 和 `instruction.md` 为准。 +FightingICE 另有[双模型对决](game_first_exam/benchmarks/fightingice/competition.md#two-model-duel):两份 Harbor 模型配置分别生成控制器,冻结程序后用原生 7.1 引擎换边对战,按标准赛规则计分。它独立于上表的 7.0 smoke 套件。 + +7.1 赛事工具也提供 [Rushdown 和 Zoning 的 MCTS 速通模式](game_first_exam/benchmarks/fightingice/competition.md#mcts-speedrun)。每条赛道用一份 Harbor 模型配置生成控制器,或直接接收已经冻结的控制器。每份控制器与固定基准换边打 10 场,按全部回合的平均计分帧数排名。 + ## 安装与第一次运行 ### 1. 准备运行环境 @@ -153,7 +159,7 @@ harbor run --game-suite minihack --standard --family room \ | 模式 | 执行方式 | 当前覆盖 | |---|---|---| -| `standard` | agent 通过客户端操作可信模拟器,按动作推进;对 live episode 评分 | 5 个游戏、42 个配置 | +| `standard` | agent 通过客户端操作可信模拟器,按动作推进;对 live episode 评分 | 6 个游戏、44 个配置 | | `privileged` | agent 可本地探索和规划;最终动作序列由独立 verifier 重新执行 | MiniHack Room | | `realtime` | 首次有效动作计划启动固定 tick;程序与模型思考期间游戏继续推进 | Crafter survival i01 | @@ -247,6 +253,7 @@ harbor view jobs | TextWorld | 原生 score / max_score | 原生得分、胜负、步数 | | MiniHack | 完成 100,未完成 0 | 原生 return、end status、动作数;100 是分数,不是 100 步 | | Crafter | 单局成就比例;跨局另计算成就成功率的 Crafter score | 22 个成就、原生 return、存活状态;木镐是辅助目标 | +| FightingICE | 原生获胜回合数 / 3 × 100 | 每回合 HP、帧数、胜负平;同步条件不等于官方实时竞赛 | 普通 reducer 按任务族汇总,Crafter 使用独立、带版本的成就 reducer。缺失局、重复局、环境故障和有效失败分开处理;模型未完成应计为有效失败,不能随意删掉。单局成就比例不是官方完整评测集的总分。 @@ -326,12 +333,12 @@ docker build -f game_first_exam/tests/envs/common.Dockerfile -t game-tests:commo docker run --rm -v "$PWD:/repo:ro" game-tests:common \ bash game_first_exam/tests/run.sh common -# 将 common 换成 minigrid / crafter / textworld / babaisai / minihack +# 将 common 换成 minigrid / crafter / textworld / babaisai / minihack / fightingice # Harbor 选择、配置合并、锁定和报告测试: python game_first_exam/tests/test_game_harbor.py ``` -GitHub Actions 执行静态检查、公共测试、5 个原生 adapter 环境及 Harbor 集成测试;不调用真实模型,不部署网站,不发布 PyPI 包或镜像。 +GitHub Actions 执行静态检查、公共测试、6 个原生 adapter 环境及 Harbor 集成测试;不调用真实模型,不部署网站,不发布 PyPI 包或镜像。 - **`harbor` 不识别 `--game-suite`:**确认当前环境执行过 `pip install -e .`,并检查 `which harbor`。也可用 `game-exam run ...`;单独安装 Harbor 不包含本仓库选择逻辑。 - **选不到任务:**先 `--list`;只有 Room 有 MiniHack privileged,只有 Crafter i01 有 realtime。模式不匹配会拒绝启动。 diff --git a/UPSTREAM.md b/UPSTREAM.md index 5c66109..00daee3 100644 --- a/UPSTREAM.md +++ b/UPSTREAM.md @@ -8,6 +8,11 @@ Retained and adapted shared components include Harbor task selection, normalizat The distribution excludes robot task trees, robot adapters/services/images/assets, RoboTwin submodules, upstream paper/site assets, website frontend/command-builder source, local evaluation records, credentials and the legacy MiniGrid i00 prototype. Shared runtime infrastructure remains because games depend on it. Historical task IDs and OCI image references remain as compatibility identifiers; this is not a mirror of upstream's full embodied benchmark. -Native environments are MiniGrid, Crafter, TextWorld/Jericho, Baba Is AI and MiniHack/NLE. Pinned dependencies and source provenance live under `game_first_exam/benchmarks/`, task README files and Docker recipes. Preserve included third-party license notices and inspect the upstream terms before redistributing additional assets. Package/source downloads are not bundled or relicensed merely because the integration code is MIT. +Native environments are MiniGrid, Crafter, TextWorld/Jericho, Baba Is AI, MiniHack/NLE and FightingICE. Pinned dependencies and source provenance live under `game_first_exam/benchmarks/`, task README files and Docker recipes. Preserve included third-party license notices and inspect the upstream terms before redistributing additional assets. Package/source downloads are not bundled or relicensed merely because the integration code is MIT. + +The FightingICE opponent callback adapts the MIT-licensed TeamFightingICE pyftg +KickAI example; its notice is retained in `game_first_exam/benchmarks/fightingice/LICENSE-pyftg`. +DareFightingICE game binaries and Dimps resources are downloaded separately and +are not included in this checkout. Their redistribution scope has not been established. The website is maintained in a separate private repository. This public repository includes no site frontend, deployment configuration, private website history or personal experiment logs. diff --git a/configs/game_benchmarks.toml b/configs/game_benchmarks.toml index 8f77b59..b6a67f2 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.fightingice] +schema = "game_first_exam/benchmarks/fightingice/instance_schema.py" diff --git a/configs/game_suites/fightingice.toml b/configs/game_suites/fightingice.toml new file mode 100644 index 0000000..270781b --- /dev/null +++ b/configs/game_suites/fightingice.toml @@ -0,0 +1,15 @@ +schema_version = "game-suite/2.1" +version = "0.1.0" +tier = "smoke" +name = "games-fightingice-native-smoke-v0.1.0" +files_images = ["connection-files", "game-files", "fightingice-files"] + +[[tasks]] +name = "fightingice-zen-kick-p1-i01-standard" +benchmark = "fightingice" +family = "zen-kick" + +[[tasks]] +name = "fightingice-zen-kick-p2-i01-standard" +benchmark = "fightingice" +family = "zen-kick" diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md index 18909da..b5e15ee 100644 --- a/docs/VALIDATION.md +++ b/docs/VALIDATION.md @@ -17,3 +17,172 @@ Local execution used macOS ARM64 with Linux containers and cached fixed adapter Changes beyond file removal are limited to game-only discovery/packaging and documentation/metadata: the shared connection source moved unchanged; the Crafter realtime generated cutoff paragraph now agrees with its existing first-request service budget; partial Crafter references explicitly describe their evidence; Room's README names its existing privileged twin. Native engine code, instances, actions, rewards and scores were not changed by this publication cleanup. Robot implementations/assets, old MiniGrid prototype, website source, editor settings, credentials and local jobs are absent from the public file list. The original MIT notice and bundled native-source license notices are retained. + +## FightingICE container checks - 2026-11-17 + +These checks were performed on branch `feat/fightingice-standard`, separately +from the publication validation above. No paid model calls were made. + +- Docker Desktop 29.9.3, Compose 5.7.0, Linux AMD64, containerd image store; + the daemon started with no images. The current shell's stale docker-group + membership was handled with a new group session, without changing socket modes. +- Native, agent and verifier images built from frozen sources. Java 21.0.2, + Python 3.12.10 and pyftg 2.3 were used inside the native test image. +- Common tests: 55 passed inside the pinned common container. FightingICE tests: + 8 passed inside its pinned container under 1 CPU, 1 GiB and 128 PIDs (423.250 s). + Host Harbor configuration/integration tests: 17 passed. All 46 task directories + passed suite preflight, file-image digests, normalization and isolation checks. +- In the actual Harbor agent container, public HTTP and the declared delayed + observation worked; the random native control port was blocked. Engine and + verifier files were absent. The base agent image had no reference solution. +- `fightingice-oracle-03` executed both three-round matches, each with 10800 + inputs and a trusted native final showing three round wins. `fightingice-nop-01` + collected valid zero-action unfinished finals for both sides. +- Both native Harbor jobs failed at separate-verifier setup: WSL kernel + `5.15.167.4-microsoft-standard-WSL2` lacks `CONFIG_NFT_FIB_INET`; Harbor 0.23.0's + kernel probe returned False and refused `network_mode='no-network'`. + Native trial exceptions and incomplete reports were retained. A zero Harbor + CLI exit status did not imply that any trial had been graded successfully. +- Supplemental validation ran the unchanged task `tests/test.sh`, including the + resource verifier, in disconnected Docker containers (`--network none`, only + loopback present) against collected read-only evidence. Scores: oracle P1/P2 + 100/100, nop P1/P2 0/0, with no sim/infra error in these supplemental verifier + results. None of the native Harbor result/reward files was overwritten. +- All four audit videos decoded completely and had nonblank last-frame images. + They are labelled native-state transcripts, not native game pixels. Sealed + resource records were present: `resource_monitor_missing=0`, + `resource_enforced=0`; do not report monitor enforcement as enabled. +- Initial HTTP Debian package downloads timed out/returned 503. The new task + agent Dockerfiles now use official Debian HTTPS URLs and bounded retries; + dependency selection, combat rules and observation permissions were preserved. + Earlier failed/cancelled jobs were retained for diagnosis during this check. + +Initial evidence was outside the public checkout under +`/tmp/opencode/fightingice-docker-20261117/`: native jobs and frozen task copies, +`isolation.json`, and `supplemental-verification.json`. Supplemental grading is +not a substitute for complete native Harbor records. That temporary directory +was cleared by the subsequent WSL restart. At this stage full Harbor validation +was blocked; the historical findings remain above, while the fresh native rerun +below resolves the blocker. + +## FightingICE native Harbor rerun - 2026-11-17 + +- WSL 3.0.5.0, daemon kernel `6.18.58.1-microsoft-standard-WSL2`, Docker Desktop + 29.9.3. CONFIG_NFT_FIB_INET=m; the unchanged Harbor 0.23.0 kernel probe returned + True. The deleted temporary Python environment was reinstalled from this + checkout and new frozen copies were prepared from the existing task configs. +- Native job `fightingice-oracle-kernel618-01`: both player-side trials completed + all three rounds, with 10800 accepted inputs and primary_score=100 each. +- Native job `fightingice-nop-kernel618-01`: both trials completed with valid + zero-action unfinished failures, primary_score=0, success=0 and no sim error. +- All four trials had exception_info=null and infra_error=0. Their native + independent verifiers ran under Harbor's unchanged no-network policy and + generated their own reward.json. No external verifier output was substituted. + Both jobs passed `game_first_exam/tests/check_fightingice_result.py`, including + complete game provenance, runtime-images and derived summary checks. +- A live cross-container probe confirmed distinct main/sim network namespaces, + public GameClient access, reset_budget=0, absent engine/verifier files and an + unreachable actual native control port. The native network-control sidecar + was enabled for the separate verifier, not the public agent environment. +- All four audit videos decoded completely and last frames were nonblank. + Monitor records were present in all native verifier outputs: + resource_monitor_missing=0, resource_enforced=0. The Docker CPU/memory/PID caps + were captured in runtime-images.json; monitor enforcement is not claimed. +- Common container tests: 55 passed again. Harbor configuration tests: 17 + passed again. All 46 tasks passed preflight, file-image digest, normalization, + protocol, isolation and resource checks. The native adapter and task policies + were not changed for this rerun. No paid model calls were made. + +Fresh evidence is in `/tmp/opencode/fightingice-rerun-20261117/`, including +`prepared.tasks/`, the two jobs and `isolation.json`. A second copy is retained +outside the checkout in Docker volume +`game-exam-fightingice-validation-20261117-kernel618-01`, under +`/fightingice-rerun-20261117`; `/manifest.json` records SHA256 hashes for all 144 +files. The backup was checked against the source byte for byte and survives +WSL /tmp cleanup. Native config, lock and result paths were not rewritten. + +## DareFightingICE 2026 archive-based workflow + +This workflow is separate from the frozen 7.0 smoke tasks above. + +- Both official 7.1 release archives matched the published SHA256 hashes. + Their resource bundle contains `MctsAi23i` and `MctsAiZoning`. No archived + entrant code or model weights were run or republished. +- Archive compatibility checks parsed 90 Standard matches and 160 + entrant-vs-baseline Style matches in each of GARNET Rushdown and NEZ Zoning + (500 paired point/style records). The Standard archive totals 270 round + points per track, including half-points on each side of a draw. Per-controller + Standard points, remaining HP and game counts, and Style speed frames and + game counts, matched the reviewed archive calculation functions. +- A fresh Harbor 0.23.0 authoring task completed with a reward of 1 for a + local oracle controller fixture and 0 for `nop`, both with zero exceptions. + These are artifact checks only, not match scores. No model API was used. +- That same hash-checked controller artifact completed four stock 7.1 matches: + both sides against `MctsAi23i` in Rushdown and both against `MctsAiZoning` + in Zoning. All four passed the separate offline verifier, including native + CSV/callback agreement. The no-op fixture scored zero round points in both + tracks; each MCTS scored six. The active workers' Docker configuration was + checked for disabled networking, read-only root and contestant mounts, and + no access to the engine or results. The two outputs are under + `/tmp/opencode/ftg-rush-final` and `/tmp/opencode/ftg-zone-final`. These were + MCTS-only match tests, not full native Style or two-baseline series. +- The competition image built locally. Six focused regression tests passed + (including socket filtering, archive calculations, ties, and rejection of + inconsistent callback/CSV evidence); the 46-task preflight, 55 common + tests, 8 existing native FightingICE tests, and 17 Harbor configuration + tests also passed. +- The archive does not identify the exact event engine build, include the + organizer baseline bundle, or provide a complete combined Style ranking + routine. The official generative sound pipeline is not recreated. The + implemented profile is therefore archive-based, not an exact reproduction + of the official leaderboard. + +## FightingICE two-model duel + +- An end-to-end Rushdown check used two native Harbor Oracle jobs with the same + local controller fixture. Both authoring checks passed. The frozen controllers + played two stock 7.1 matches with sides reversed; both matches passed the + separate verifier. Each side earned 3 points and 1050 total remaining HP, + sharing rank 1. `summarize` reproduced the saved result. +- Both workers had separate sockets, no network, and read-only submission + mounts. The controller fixture explicitly rejected audio, screen, and + undelayed-state callbacks. The `nop` empty-submission check stopped before + any match and created no report. +- The 46-task static check, 55 common tests, 17 Harbor configuration tests, + and 8 FightingICE competition tests passed. This local check did not call + a model API. + +## FightingICE MCTS speedrun + +- The 46-task static check, 55 common tests, 17 Harbor 0.23.0 configuration + tests, 8 native FightingICE tests, and 11 focused competition tests passed. + The new tests cover both tracks' schedules, per-round penalties, shared + ranks, and rejection of incomplete or inconsistent match evidence. +- A local no-op controller completed all ten native Rushdown matches against + `MctsAi23i`, five on each side. All 30 losses received the 4,200-frame penalty + for an average of 4,200 scored frames (70 game seconds). All ten matches + passed the independent verifier and produced native replays. The saved + `league-report.json` matched `summarize`, and an earlier check on the + incomplete run emitted no standings. The evidence is under + `/tmp/opencode/ftg-speedrun-rushdown-01/`. This run used no model API. + +## FightingICE model-to-match workflow + +- The speedrun `--model` entry point stages a track-specific prompt, runs + one 600-second Harbor authoring trial with zero retries, and freezes the + verified controller. An empty `nop` submission completed its separate + authoring verifier with reward 0 and produced no match or league report. +- Local Harbor Oracle jobs generated an isolation-check controller for each + speedrun track. Rushdown and Zoning each completed ten verified matches + and 30 rounds, with five matches on each side. The fixture lost all rounds + on both tracks and averaged 4,200 scored frames in each. Both reports + matched `summarize` and had ten native replay files. +- Two local Harbor Oracle jobs using the same no-op fixture completed the + two-match Rushdown duel. Each side scored 3 points and 2,400 total remaining + HP. `summarize` reproduced the saved standings. +- Live Docker inspection confirmed no network access, read-only roots and + submission mounts, and one private socket per external controller. The + fixture checked for a loopback-only network and rejected audio, screen, + and undelayed-state callbacks. Local Oracle jobs made no model API calls. +- The 46-task static check, 55 common tests, 17 Harbor configuration tests, + 8 native FightingICE tests, and 12 competition tests passed. diff --git a/docs/game_framework.md b/docs/game_framework.md index 62e80fb..a68c23c 100644 --- a/docs/game_framework.md +++ b/docs/game_framework.md @@ -30,7 +30,7 @@ instruction.md → Harbor 原生 coding agent → agent 写的程序 - `game_first_exam/runtime/`:游戏公共协议、预算、错误类型、评分、录像和 reducer。 - `game_first_exam/runtime/modes/`:独立的 privileged 和 realtime 执行方式。 -- `game_first_exam/benchmarks/`:五个原生环境的薄适配器、专属 schema、指标和依赖。 +- `game_first_exam/benchmarks/`:六个原生环境的薄适配器、专属 schema、指标和依赖。 - `game_first_exam/tasks/`:自包含冻结任务;运行不依赖宿主源码路径。 - `shared/connection/`:从上游原样保留的就绪等待、地址选择和连接处理。 - `images/connection-files/`、`images/monitor/`:共用连接镜像与资源监控。 diff --git a/docs/protocol/running.md b/docs/protocol/running.md index 1142c87..45335cf 100644 --- a/docs/protocol/running.md +++ b/docs/protocol/running.md @@ -12,6 +12,15 @@ TextWorld 的冻结游戏经原生 Jericho 执行;不调用异构 wheel 中的游戏生成程序。MiniHack 使用固定 NLE/MiniHack 和模拟器日历设置,详情见游戏 README。 +Harbor 0.23.0 的 `no-network`/allowlist 能力还取决于 Docker 服务端内核。 +当 `/proc/config.gz` 可读时,其探针要求 `CONFIG_NFT_FIB_INET=y` 或 `m`。 +旧版 WSL 内核 `5.15.167.4` 未包含此功能:容器和游戏可以启动,但独立 verifier +会因 `network_mode='no-network' is not supported` 被拒绝。需要更新 WSL 并重启 +Docker Desktop,或使用支持该能力的 Linux Docker 服务端;不能将 verifier 改为 +public 来绕过。`docker version` 成功不等于 Harbor 网络隔离已可用。 +本机更新至 `6.18.58.1` 后,该配置为 `m`,Harbor 探针及 FightingICE 的独立 +verifier 已通过实际运行验证;其他主机仍需检查自己的服务端内核。 + ## 时间、网络与资源 Harbor 的 agent 超时包括模型调用和工具执行;服务预算不延长外层截止。标准模式由动作推进。Crafter realtime 首次请求开始服务计时、首次计划开始游戏时钟,后台控制程序在工具调用结束后应持续运行。 diff --git a/game_first_exam/benchmarks/fightingice/LICENSE-pyftg b/game_first_exam/benchmarks/fightingice/LICENSE-pyftg new file mode 100644 index 0000000..5a9a28e --- /dev/null +++ b/game_first_exam/benchmarks/fightingice/LICENSE-pyftg @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 TeamFightingICE + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/game_first_exam/benchmarks/fightingice/README.md b/game_first_exam/benchmarks/fightingice/README.md new file mode 100644 index 0000000..a9c8bb4 --- /dev/null +++ b/game_first_exam/benchmarks/fightingice/README.md @@ -0,0 +1,172 @@ +# FightingICE standard integration + +The existing `fightingice` suite below is the frozen 7.0 smoke suite. For the +separate 2026 archive-based controller-authoring and league runner, see +[Competition workflow](competition.md). Its scores are not smoke-suite scores. + +This integration evaluates Harbor coding agents controlling DareFightingICE 7.0 +through its native Python player interface (pyftg 2.3). The selected observation +is the native delayed FrameData plus is_control, not pixels and not the +non-delay audit state. Native public structured fields are retained, including +positions, actions, remaining frames and projectiles. JSON is only the wire +representation of the native Python data. + +The initial scope is ZEN versus the deterministic B-button KickAI example, +with a separate task for each player side. These are smoke configurations, not +the official tournament or a claim of competitive difficulty. The upstream +example is https://github.com/TeamFightingICE/pyftg/blob/e18af08769b02b021bb823fba01f15850aa88c05/examples/KickAI.py. + +The native --input-sync option pauses the simulator until both players return +their keys. One public action sends one native Key; observations never release +the waiting player. There is one match, three rounds, 400 initial HP per side, +and the native 3600-frame round limit. Automatic round transitions are native; +the agent cannot reset or launch a second match. Initialization preserves the +native empty delayed observations rather than advancing through them silently. + +## Isolation and scoring + +The engine and both Python player callbacks run in the trusted sim. SERVER_HOST +is explicitly 127.0.0.1: the native launch, player, spectator and close channels +must not be reachable from the agent container. Only the common HTTP service is +public. The agent image contains neither engine resources nor verifier files. +Raw non-delay state is used only for audit fingerprints and score evidence. + +The primary score is 100 times native round wins divided by three. Native round +outcomes compare remaining HP, including a native timeout. Unfinished rounds +give no win credit; success additionally requires a completed match with more +wins than losses. The engine has no scalar Gym reward: adapter Transition reward +is zero, explicitly not a native return. Frame fingerprints cover available +native state, callbacks and counters, not a complete JVM checkpoint or proof of +trajectory replay. No native seed API is claimed; the frozen seed identifies +the configuration, and the first opponent has no RNG. + +The native engine assigns random UUIDs to attacks, including initial attacks. +Public observations preserve those native identifiers. Internal fingerprints +canonicalize identifiers by first occurrence within each snapshot, retaining +alias relationships but not claiming byte-identical raw observations across +runs. UUID generation is not a seeded gameplay randomization API. + +## Native differences and packaging + +The clock is synchronous, not the official wall-clock competition. No external +LLM runner, model gateway, fine-tuned model or generative sound agent is used. +The profile is structured-state-only; lightweight mode disables graphics and +audio generation without changing native combat. Audit frames are a labelled +state transcript, not native game pixels or an additional agent observation. +Original frame delay, commands, combat dynamics and round transitions are kept. + +The release and installed files are hash pinned by install_native.py/SOURCE.json. +Downloads and extracted game binaries stay outside this public checkout. pyftg +is MIT; the game resources retain their upstream terms (Dimps assets). No game +binary or art is vendored and no registry publication is implied. Redistribution +permissions for upstream resources remain to be confirmed before publication. + +## Local verification + +With Python 3.12 and Java 21 installed, install requirements.txt into a separate +environment. Native binaries and downloaded archives belong outside the checkout: + +```sh +python game_first_exam/benchmarks/fightingice/install_native.py /tmp/fightingice-native +FIGHTINGICE_HOME=/tmp/fightingice-native python game_first_exam/tests/test_fightingice.py --native +harbor run --game-suite fightingice --standard --list +``` + +The installer also accepts --engine-archive, --resources-archive or +--resources-dir to reuse local upstream downloads. It checks the release hash +and each installed ZEN resource, and runtime verifies the installed files again. +The resource archive includes unused graphics/audio and can be slow to download. +Only the two pinned ZEN parameter files are installed for this profile. + +Docker/Harbor execution requires a daemon kernel supported by Harbor's network +isolation. In Harbor 0.23.0 the kernel probe requires CONFIG_NFT_FIB_INET=y/m +when /proc/config.gz exists. A working `docker version` alone is insufficient. + +The frozen 7.0 task requests the same container limits on every host. Both +`main` and `sim` request 1 CPU and 1 GiB of memory, with process limits of +256 and 128 respectively. The host's resource quotas and concurrent load +determine how much capacity the containers actually get. After moving to a +server, run the smoke check there and inspect `runtime-images.json` for the +CPU, memory, and PID settings Docker applied. See the +[7.1 competition limits](competition.md#local-usage) for duel and speedrun. + +With a supported kernel: + +```sh +harbor run --game-suite fightingice --standard -c configs/harbor/oracle.json \ + --plugin game_harbor:GameRecords --job-name fightingice-oracle +harbor run --game-suite fightingice --standard -c configs/harbor/nop.json \ + --plugin game_harbor:GameRecords --job-name fightingice-nop +python game_first_exam/tests/check_fightingice_result.py jobs/fightingice-oracle oracle +python game_first_exam/tests/check_fightingice_result.py jobs/fightingice-nop nop +``` + +## Initial container validation (2026-11-17) + +Docker Desktop 29.9.3 with containerd storage built the frozen native, agent and +verifier images. The common container tests (55) and native FightingICE tests +(8) passed; the native tests used 1 CPU, 1 GiB and a 128-process limit. The +runtime used the pinned Java 21.0.2, Python 3.12.10 and pyftg 2.3. + +A probe inside the real Harbor agent container confirmed that public HTTP and +the declared observation work while the actual random native engine port is +unreachable. Engine/verifier files were absent; the base agent image also had +no reference controller. No public reset was available. + +The initial Harbor runs executed both oracle matches (10800 inputs each) and +both zero-input nop controls and collected trusted finals, recordings and +monitor records. The original WSL kernel 5.15.167.4 lacked CONFIG_NFT_FIB_INET. +Harbor correctly rejected the separate verifier's no-network policy: those +four trials were infrastructure failures, not completed scored trials. + +As a supplemental check, the collected evidence was graded using the unchanged +tests/test.sh in separate `docker run --network none` verifier containers. Oracle +scores were 100/100 and nop scores 0/0. All four recordings decoded and their last +frames were nonblank audit transcripts. Resource records were present, with +resource_monitor_missing=0 and resource_enforced=0. These checks do not replace +Harbor's missing native verifier results or establish resource enforcement. + +The strict check_fightingice_result.py rejected those incomplete jobs. Their +temporary /tmp evidence was subsequently cleared by the WSL restart; the +historical findings above are retained. The complete native rerun below resolves +the original host limitation. See [validation notes](../../../docs/VALIDATION.md). + +The two agent Dockerfiles use the official Debian HTTPS endpoints and bounded +download retries after local HTTP package downloads returned timeouts/503s. +The collector artifact declaration is normalization-idempotent and contains one +monitor artifact. No model calls or image publication were performed. + +## Complete native Harbor rerun (2026-11-17) + +After upgrading to WSL 3.0.5.0 / kernel 6.18.58.1, CONFIG_NFT_FIB_INET=m and +Harbor 0.23.0's kernel probe returned True. Fresh frozen copies were prepared +from the same task configurations; no network policy was relaxed. + +| Job | P1 score | P2 score | Inputs per trial | +|---|---|---|---| +| fightingice-oracle-kernel618-01 | 100 | 100 | 10800 | +| fightingice-nop-kernel618-01 | 0 | 0 | 0 | + +All four native Harbor trials finished with no exception or infrastructure +error. The independent native verifiers produced their own reward.json files; +check_fightingice_result.py passed for both jobs, including complete provenance, +actual runtime-image capture and derived game reports. Nop outcomes are valid +unfinished failures, not simulator faults. No supplemental grading replaced +these native results. + +The live agent/sim probe again confirmed separate network namespaces, public +HTTP access, no reset, no hidden engine/verifier files and an unreachable native +control port. Harbor applied its own no-network policy to the separate verifier +through the native egress sidecar. All four videos decoded completely and had +nonblank audit-transcript last frames. Resource records were present in all +trials (resource_monitor_missing=0); resource_enforced remained 0. Docker's +configured CPU/memory/PID limits were captured separately in runtime-images.json. + +The new records and frozen task copies are under +`/tmp/opencode/fightingice-rerun-20261117/`. A hash-verified 144-file backup is in +Docker volume `game-exam-fightingice-validation-20261117-kernel618-01`, directory +`/fightingice-rerun-20261117`, with `/manifest.json` listing file hashes. This +backup survives WSL /tmp cleanup; native records are preserved without rewriting +their original paths. Common container tests (55), Harbor configuration tests +(17) and static checks for all 46 tasks passed again after the upgrade. These +are reference/no-op checks, not model benchmark scores; no model was called. diff --git a/game_first_exam/benchmarks/fightingice/SOURCE.json b/game_first_exam/benchmarks/fightingice/SOURCE.json new file mode 100644 index 0000000..0e4fdd4 --- /dev/null +++ b/game_first_exam/benchmarks/fightingice/SOURCE.json @@ -0,0 +1,13 @@ +{ + "engine_version": "7.0", + "engine_commit": "3780b5efa3f5ecf142369e567a43a8c292013a58", + "engine_url": "https://github.com/TeamFightingICE/FightingICE/releases/download/v7.0/DareFightingICE-7.0.zip", + "engine_sha256": "d14ce73530b190686abe787416f178fe03400b8c48b328497a57a4978a8e2e9a", + "resources_url": "https://github.com/TeamFightingICE/FightingICE/releases/download/v6.3/resources-6.3.zip", + "resources": { + "data/characters/ZEN/gSetting.txt": "bae5b37d64ddd80c149eeae969903c9a97a0b262ff635263275b3ae31bc2c30a", + "data/characters/ZEN/Motion.csv": "9a7260d3429d50e021b76b4e10b4889a5c6f0ca5e4c2cc41c7bb4f212d1e755f" + }, + "opponent_source": "https://github.com/TeamFightingICE/pyftg/blob/e18af08769b02b021bb823fba01f15850aa88c05/examples/KickAI.py", + "license_note": "pyftg is MIT. Engine and Dimps resources retain upstream terms; redistribution not established." +} diff --git a/game_first_exam/benchmarks/fightingice/adapter.py b/game_first_exam/benchmarks/fightingice/adapter.py new file mode 100644 index 0000000..3457708 --- /dev/null +++ b/game_first_exam/benchmarks/fightingice/adapter.py @@ -0,0 +1,163 @@ +"""Native FightingICE match behind the shared synchronous game contract.""" +import copy +import importlib.metadata +import os +from pathlib import Path +import shutil +import socket +import subprocess +import tempfile +import time + +from bridge import Session +from contracts import Capabilities, Transition +from encoding import state_hash +from install_native import verify +from pyftg import Key +from pyftg.models.enums.int_action import IntAction +from pyftg.models.enums.int_state import IntState + +KEYS = 'ABCDLRU' +ACTIONS = ['noop'] + [''.join(key for bit, key in enumerate(KEYS) if mask & (1 << bit)) + for mask in range(1, 128)] + + +class Adapter: + def __init__(self, instance, assets=None): + if importlib.metadata.version('pyftg') != instance['engine_versions']['pyftg']: + raise ValueError('pyftg version mismatch') + self.instance = copy.deepcopy(instance) + self.player = instance['player'] + self.steps, self.rounds, self.done = 0, [], False + self.data, self.audit, self.is_control = None, None, False + self.session = self.process = None + self.workspace = tempfile.TemporaryDirectory(prefix='fightingice-') + self.log = None + try: + native = Path(os.environ.get('FIGHTINGICE_HOME', '/opt/fightingice')) + verify(native) + shutil.copytree(native, self.workspace.name, dirs_exist_ok=True) + with socket.socket() as sock: + sock.bind(('127.0.0.1', 0)) + port = sock.getsockname()[1] + self.log = open(Path(self.workspace.name) / 'engine.log', 'wb') + self.process = subprocess.Popen([ + 'java', '-Xmx512m', '-XX:ActiveProcessorCount=1', '-cp', + 'FightingICE.jar:lib/*:lib/grpc/*:lib/lwjgl/*', 'Main', + '--lightweight-mode', '--input-sync', '--limithp', '400', '400', + '--pyftg-mode', '--port', str(port)], cwd=self.workspace.name, + env={**os.environ, 'SERVER_HOST': '127.0.0.1'}, stdout=self.log, stderr=subprocess.STDOUT) + deadline = time.monotonic() + 15 + while True: + if self.process.poll() is not None: + raise RuntimeError('FightingICE exited during startup') + # An empty TCP probe can kill the native accept thread. Wait for + # its own ready marker without sending a partial player packet. + if 'Waiting to launch a game' in (Path(self.workspace.name) / 'engine.log').read_text(): + break + if time.monotonic() >= deadline: + raise RuntimeError('FightingICE socket did not become ready') + time.sleep(.05) + self.session = Session(port, self.player) + self._advance() + except Exception as exc: + detail = (Path(self.workspace.name) / 'engine.log').read_text() if self.log else '' + self.close() + raise RuntimeError(f'{exc}\n{detail[-4000:]}') from exc + + def _advance(self): + while True: + event = self.session.next() + if event[0] == 'frame': + _, self.data, self.is_control, self.audit = event + return + if event[0] == 'round': + self.rounds.append(event[1]) + elif event[0] == 'end': + self.done = True + return + else: + raise RuntimeError('unknown native callback') + + def spec(self): + return {'adapter_version': '1.0.0', + 'capabilities': Capabilities(images=False, action_mode='enum').to_dict(), + 'action_schema': {'type': 'string', 'enum': ACTIONS}, + 'observation': 'native delayed FrameData; native is_control; zero-based player index', + 'keys': {'A': 'attack A', 'B': 'attack B', 'C': 'attack C', 'D': 'down', + 'L': 'left', 'R': 'right', 'U': 'up', 'noop': 'release all keys'}, + 'frames_per_action': 1, 'native_fps': 60, + 'native_action_ids': {name: int(value) for name, value in IntAction.__members__.items()}, + 'native_state_ids': {name: int(value) for name, value in IntState.__members__.items()}, + 'game_data': copy.deepcopy(self.session.game_data)} + + def observe(self): + return {'player': self.player, 'frame_data': copy.deepcopy(self.data), 'is_control': self.is_control} + + def step(self, action): + if action not in ACTIONS or self.done: + raise ValueError('invalid native key or closed match') + key = Key() + for name in (() if action == 'noop' else action): + setattr(key, name, True) + self.session.actions.put(key) + self._advance() + self.steps += 1 + return Transition(0.0, terminated=self.done) + + def metrics(self): + wins = sum(r['remaining_hps'][self.player] > r['remaining_hps'][1-self.player] for r in self.rounds) + losses = sum(r['remaining_hps'][self.player] < r['remaining_hps'][1-self.player] for r in self.rounds) + return {'rounds': copy.deepcopy(self.rounds), 'wins': wins, 'losses': losses, + 'draws': len(self.rounds)-wins-losses, 'completed_rounds': len(self.rounds), + 'round_win_score': 100*wins/3, 'native_steps': self.steps} + + def success(self): + metrics = self.metrics() + return self.done and metrics['wins'] > metrics['losses'] + + def fingerprint(self): + identifiers = {} + + def canonical(value): + if isinstance(value, dict): + result = {} + for key, item in value.items(): + if key == 'identifier' and item: + item = identifiers.setdefault(item, len(identifiers)) + result[key] = canonical(item) + return result + if isinstance(value, list): + return [canonical(item) for item in value] + return value + + # Native UUIDs identify attacks but have random bytes. Keep within-state + # identity relationships in the audit hash without changing observations. + return state_hash(canonical({'frame': self.audit, 'delayed_frame': self.data, 'rounds': self.rounds, + 'steps': self.steps, 'done': self.done, 'player': self.player})) + + def frame(self): + import numpy as np + from PIL import Image, ImageDraw + image = Image.new('RGB', (640, 200), '#202020') + draw = ImageDraw.Draw(image) + draw.text((12, 12), 'FightingICE native-state transcript (not game pixels)', fill='white') + draw.text((12, 32), f'Controlled P{self.player+1}; input {self.steps}; rounds {len(self.rounds)}/3', fill='white') + frame = self.audit or self.data or {} + for index, character in enumerate(frame.get('character_data', [])): + if character: + draw.text((12, 60+index*55), f'P{index+1}: HP {character["hp"]}; {character["action"]}', fill='white') + return np.asarray(image) + + def close(self): + if self.process is not None: + if self.process.poll() is None: + self.process.kill() + self.process.wait(timeout=5) + try: + if self.session is not None: + self.session.close() + finally: + if self.log is not None: + self.log.close() + self.workspace.cleanup() diff --git a/game_first_exam/benchmarks/fightingice/bridge.py b/game_first_exam/benchmarks/fightingice/bridge.py new file mode 100644 index 0000000..0226fa4 --- /dev/null +++ b/game_first_exam/benchmarks/fightingice/bridge.py @@ -0,0 +1,127 @@ +"""Trusted native player callbacks. Only the controlled player waits for HTTP input.""" +import asyncio +import queue +import threading + +from pyftg import AIInterface, CommandCenter, Key +from pyftg.socket.aio.gateway import Gateway + + +class Player(AIInterface): + def __init__(self, session, controlled): + self.session, self.controlled = session, controlled + self.key = Key() + self.audit = None + + def name(self): + return 'GameExam' if self.controlled else 'KickAI' + + def is_blind(self): + return not self.controlled + + def initialize(self, game_data, player_number): + self.player = player_number + self.cc = CommandCenter() + if self.controlled: + self.session.game_data = game_data.to_dict() + + def get_information(self, frame_data, is_control): + self.data, self.is_control = frame_data, is_control + self.cc.set_frame_data(frame_data, self.player) + + def get_non_delay_frame_data(self, frame_data): + if self.controlled: + self.audit = frame_data.to_dict() + + def get_screen_data(self, screen_data): + pass + + def get_audio_data(self, audio_data): + pass + + def processing(self): + if self.controlled: + if self.session.closed: + self.key = Key() + return + self.session.events.put(('frame', self.data.to_dict(), self.is_control, self.audit)) + self.key = self.session.actions.get() + elif not self.data.empty_flag and self.data.current_frame_number > 0: + # Same key timing as the upstream pyftg KickAI example. + if self.cc.get_skill_flag(): + self.key = self.cc.get_skill_key() + else: + self.key.empty() + self.cc.skill_cancel() + self.cc.command_call('B') + + def input(self): + return self.key + + def round_end(self, result): + if self.controlled: + self.session.events.put(('round', result.to_dict())) + + def game_end(self): + if self.controlled: + self.session.events.put(('end',)) + + def close(self): + pass + + +class Session: + def __init__(self, port, player): + self.events, self.actions = queue.Queue(), queue.Queue() + self.game_data = None + self.loop = None + self.task = None + self.closed = False + self.thread = threading.Thread(target=self.run, args=(port, player), daemon=True) + self.thread.start() + + def run(self, port, player): + async def play(): + gateway = Gateway(port=port) + names = [] + for index in range(2): + ai = Player(self, index == player) + gateway.register_ai(ai.name(), ai) + names.append(ai.name()) + await gateway.run_game(['ZEN', 'ZEN'], names, 1) + if not self.closed: + self.events.put(('error', 'native gateway ended before match was consumed')) + self.loop = asyncio.new_event_loop() + asyncio.set_event_loop(self.loop) + try: + self.task = self.loop.create_task(play()) + self.loop.run_until_complete(self.task) + except BaseException as exc: + if not self.closed: + self.events.put(('error', repr(exc))) + finally: + tasks = asyncio.all_tasks(self.loop) + for task in tasks: + task.cancel() + self.loop.run_until_complete(asyncio.gather(*tasks, return_exceptions=True)) + self.loop.run_until_complete(self.loop.shutdown_default_executor()) + self.loop.close() + + def next(self, timeout=10): + try: + event = self.events.get(timeout=timeout) + except queue.Empty as exc: + raise RuntimeError('native frame handshake timed out') from exc + if event[0] == 'error': + raise RuntimeError(event[1]) + return event + + def close(self): + self.closed = True + self.actions.put(Key()) + if self.loop and not self.loop.is_closed(): + if self.task: + self.loop.call_soon_threadsafe(self.task.cancel) + self.thread.join(timeout=5) + if self.thread.is_alive(): + raise RuntimeError('native Python callbacks did not stop') diff --git a/game_first_exam/benchmarks/fightingice/competition.Dockerfile b/game_first_exam/benchmarks/fightingice/competition.Dockerfile new file mode 100644 index 0000000..7db4faf --- /dev/null +++ b/game_first_exam/benchmarks/fightingice/competition.Dockerfile @@ -0,0 +1,8 @@ +FROM docker.io/library/python:3.12.10-slim-bookworm@sha256:fd95fa221297a88e1cf49c55ec1828edd7c5a428187e67b5d1805692d11588db +RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates fontconfig libstdc++6 libasound2 && rm -rf /var/lib/apt/lists/* +ADD --checksum=sha256:51141204fe01a9f9dd74eab621d5eca7511eac67315c9975dbde5f2625bdca55 https://github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.2%2B13/OpenJDK21U-jre_x64_linux_hotspot_21.0.2_13.tar.gz /tmp/java.tar.gz +RUN mkdir /opt/java && tar -xzf /tmp/java.tar.gz -C /opt/java --strip-components=1 && rm /tmp/java.tar.gz +COPY requirements.txt /bridge/requirements.txt +RUN pip install --no-cache-dir --no-deps -r /bridge/requirements.txt && pip check +COPY competition_results.py competition_wire.py competition_match.py /bridge/ +ENV JAVA_HOME=/opt/java PATH=/opt/java/bin:$PATH PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1 ALSOFT_DRIVERS=null diff --git a/game_first_exam/benchmarks/fightingice/competition.md b/game_first_exam/benchmarks/fightingice/competition.md new file mode 100644 index 0000000..e54a8fe --- /dev/null +++ b/game_first_exam/benchmarks/fightingice/competition.md @@ -0,0 +1,185 @@ +# DareFightingICE 2026 competition workflow + +This is an archive-based **prototype**, separate from the frozen 7.0 KickAI +smoke suite. Harbor writes a controller once; isolated Docker workers run that +frozen code in subsequent matches. The stock engine owns its clock, rounds, +physics and native point/style logs. This is not an official-leaderboard result +and is not registered under `harbor run --game-suite fightingice`. + +## Two-model duel + +Supply two [single-agent Harbor profiles](../../../configs/harbor/) as JSON. +Each profile runs a separate Harbor job to write one controller with the same +600-second authoring limit and the same generated instruction. Each job makes +one authoring attempt with zero automatic retries. Set credentials in the +environment. Real model profiles can incur API charges. + +```bash +FTG=game_first_exam/benchmarks/fightingice +python "$FTG/competition.py" duel \ + --model-a /path/to/model-a.json --model-b /path/to/model-b.json \ + --track rushdown --pairs 1 \ + --release /path/to/DareFightingICE-7.1.zip \ + --resources /path/to/resource-7.1.zip \ + --output /tmp/opencode/ftg-duel-01 +``` + +Run from the repository root with Harbor 0.23.0 installed and Docker running. +The command builds the runtime locally from this checkout. Use a new output +directory on each run. Profiles accept `agents` with exactly one native +agent (`name`, `model_name`, and optional `kwargs`); they cannot override the +task, timeout, verifier, or retry policy. + +One pair means two matches with P1/P2 reversed, three rounds per match. +`--pairs N` adds matches without regenerating either controller. The duel +has no MCTS opponent, screen, or audio input: policies receive native +delayed FrameData, control flags, and lifecycle events. The native clock +keeps running. Only the authoring jobs call a model. + +`duel-report.json` records per-match and per-round results, total round +points, remaining HP, and standings. A round win earns 1, a draw earns 0.5 +per side, and remaining HP breaks points ties; exact ties are shared. +`author-jobs/` retains both Harbor records, and `provenance.json` contains +the two frozen controller hashes. `competition.py summarize RUN_DIR` +rechecks the stored result. A missing controller, failed trial, or invalid +match does not produce standings. Use a separate run for Zoning; do not +combine the tracks or compare these scores to the archived league standings. + +## MCTS speedrun + +Supply `--model` with a single-agent Harbor profile for an end-to-end model +evaluation. Harbor provides the track-specific instruction and native character +tables. The instruction describes the preferred style and the timed scoring +objective. The model gets one 600-second attempt to write `controller.py`. +The runner snapshots the verified submission once and uses it in all ten +matches. A failed authoring trial stops the run before any match and keeps the +Harbor records. The same command accepts frozen `NAME=CONTROLLER_DIRECTORY` +entries in place of `--model`. + +```bash +FTG=game_first_exam/benchmarks/fightingice +python "$FTG/competition.py" run --track rushdown --league speedrun \ + --model /path/to/model-profile.json \ + --release /path/to/DareFightingICE-7.1.zip \ + --resources /path/to/resource-7.1.zip \ + --output /tmp/opencode/ftg-speedrun-rushdown +python "$FTG/competition.py" summarize /tmp/opencode/ftg-speedrun-rushdown +``` + +Use `--track zoning` with a new output directory for Zoning. Run `plan` +with `entry=/path/to/controller` to preview the frozen schedule. Model +runs retain the rendered `instruction.md`, its SHA256 and the native +`author-jobs/` records. Controllers use delayed FrameData and the native +control flag. The runner builds the current bridge locally and runs controllers +offline with screen and audio omitted. + +Each entry plays five three-round matches on each side against `MctsAi23i` +in GARNET Rushdown or `MctsAiZoning` in NEZ Zoning. Run the tracks separately. +Wins and draws by remaining HP count their elapsed game frames, including +rounds decided on timeout. Each loss counts 4,200 frames. For example, a +900-frame win, a 3,600-frame draw, and a loss count 8,700 frames and average +2,900 frames. Ranking uses the average across all 30 rounds. Exact ties share +a rank. + +`league-report.json` records standings, wins, draws, losses, penalty rounds, +per-round HP and frames, and average scored frames and seconds. The seconds +are calculated at 60 game frames per second. The output includes native +replays, the frozen schedule and controller hashes. The profile +`speedrun-mcts-framedata-v1` uses the archive's speed arithmetic with a single +track-specific baseline. These are Game Exam scores under this profile. +`summarize` independently checks the native evidence and requires all ten +matches per entry. + +## What is preserved + +Sources: [published rules](https://github.com/TeamFightingICE/FightingICE/blob/v7.1/DareFightingICE/AI/README.md), +[results archive](https://www.ice.ci.ritsumei.ac.jp/~ftgaic/index-R.html), +and [7.1 release](https://github.com/TeamFightingICE/FightingICE/releases/tag/v7.1). +The archive's `2026AI/log/point-style/com_calc.py` has SHA256 +`29887c5a8ede9d294f1d698b5d5a833a96b3fc8161475350559d290eedb52390`. +The archive contains result CSVs, replays and entrant archives, not an exact +engine bundle or an organizer controller. Entrant code is not executed by this +workflow unless explicitly provided by the operator in a controller bundle. + +| Item | Coverage | +|---|---| +| Engine | Stock 7.1 release/assets are SHA256-pinned; no Java patches. The rules list 7.0 but require NEZ, added in 7.1. Archive CSV headers match 7.1 style logging; exact event binary is unverified. | +| Tracks and clock | GARNET Rushdown and NEZ Zoning, 400 HP, three rounds, original real-time clock (no `--input-sync`). Headless mode, separate container transport and resource/timeout limits are Game Exam choices. | +| Standard League | Round-robin among supplied entries and baselines, two matches per pair with sides reversed. Archive scorer awards one point for higher remaining HP (also on timeout) and half for a tie, then compares total remaining HP. The published rules' prose mentions KO; the archive arithmetic is used instead. Exact ties remain ties; display order is alphabetical. | +| Style stage | Ten matches per entrant per opponent, five on each side. The archive used both organizer and the track MCTS baseline; the published summary names MCTS. Archive-only baseline calibration games are not replayed for scoring new entrants. | +| Style metrics and speed | Native per-frame trackers produce the style CSV; the report averages native columns separately. The archive records elapsed frames for wins/draws and charges 4200 frames for a loss in the speed calculation. No final weighted Style ranking or Formula One league-points formula is asserted: the archive does not supply a reproducible combination, including the treatment of exact ranking ties. | +| Official baselines | `MctsAi23i.jar` and `MctsAiZoning.jar` are in the pinned official resource archive. Full mode requires the operator-supplied `organizer` bundle; provenance records its hash, not an assertion of authenticity. `--mcts-only` is an explicitly partial schedule. | +| Controller API | Native `pyftg` objects, round/game callbacks and native `Key`/`CommandCenter`. Delay and `is_control` come from the engine. The bridge forwards native `AudioData` when present but does not recreate the official generative sound setup or offer visual input. Undelayed state, spectator and match-management messages stay private. | +| Coding Agent | Harbor checks the entry artifact, not a league score. No LLM or model API runs inside the official match phase. Sources are copied and hashed before the first match. The program is read-only and offline during each match. | + +Every contestant gets its own network-disabled container and a point-to-point +Unix socket, with a read-only root filesystem and submission mount. The native +management socket is bound to loopback in the trusted engine container. The +engine receives player inputs through the bridge. It writes native logs and +result evidence to mounts outside the contestant containers. A separate +network-disabled verifier reads the engine's CSV and callback evidence +read-only before a match enters the league report. A controller +disconnect, bridge timeout, missing native evidence, or callback/CSV mismatch +fails the league run instead of publishing an invented score. + +The authoring container can reach the configured model provider over the +network. Harbor collects the submission and compiles it in a separate +network-disabled verifier before the runner prepares the offline matches. + +## Local usage + +From the repository root, use Python 3.12+ and Docker on Linux/AMD64. +Build the runtime image locally. Download `DareFightingICE-7.1.zip` and +`resource-7.1.zip` from the official release into a directory outside the +repository. The runner verifies both archive hashes before use; neither is +bundled or republished. + +The 7.1 runner requests 1 CPU, 1 GiB of memory, and a 128-process limit for +each engine, controller, and match-verifier container. The same requests +apply on a server. Host quotas and concurrent load can affect how quickly +controllers respond to the real-time engine. Check the effective Docker +limits on the server and keep the resource settings and concurrency +consistent across runs you plan to compare. + +```bash +FTG=game_first_exam/benchmarks/fightingice +docker build -f "$FTG/competition.Dockerfile" \ + -t game-exam:fightingice-competition "$FTG" + +python "$FTG/competition.py" author /tmp/opencode/fightingice-author \ + --resources /path/to/resource-7.1.zip +# With an existing Harbor agent profile: +harbor run -c /tmp/opencode/fightingice-author/author-job.json -c /path/to/agent-profile.json \ + --jobs-dir /tmp/opencode/fightingice-author-jobs --job-name author-01 +``` + +The author artifact is the trial's `artifacts/app/output/` directory with +`controller.py` and its modules. You may use a locally written controller +directory instead. To inspect the exact match list before running: + +```bash +python "$FTG/competition.py" plan --track rushdown --league standard \ + --mcts-only entry=/path/to/artifacts/app/output + +python "$FTG/competition.py" run --track rushdown --league standard \ + --mcts-only --release /path/to/DareFightingICE-7.1.zip \ + --resources /path/to/resource-7.1.zip --output /tmp/opencode/ftg-match-01 \ + entry=/path/to/artifacts/app/output +``` + +Run `--track zoning` separately. Use `--league style` for repeated P1/P2 +matches. Add other `NAME=DIRECTORY` entries for a round-robin; use +`--organizer /path/to/organizer` **instead of** `--mcts-only` for the +two-baseline schedule. A real-time match can take over three minutes. + +The run directory preserves the full schedule, image and controller hashes, +per-match native evidence, and `league-report.json` for a complete schedule. +`python "$FTG/competition.py" summarize RUN_DIR` rechecks the native CSVs against +the verified match records. Partial MCTS-only results stay explicitly marked. + +## Verification + +The focused regression is `python game_first_exam/tests/test_fightingice_competition.py` +in a Python 3.12 environment with the benchmark's pinned requirements. Status +of actual launch and evidence verification is recorded in the repository +validation notes. diff --git a/game_first_exam/benchmarks/fightingice/competition.py b/game_first_exam/benchmarks/fightingice/competition.py new file mode 100644 index 0000000..d87ccf9 --- /dev/null +++ b/game_first_exam/benchmarks/fightingice/competition.py @@ -0,0 +1,454 @@ +"""Orchestrate the separately isolated, archive-based FightingICE league prototype.""" +import argparse +from contextlib import ExitStack +import hashlib +import json +import os +from pathlib import Path +import shutil +import stat +import subprocess +import sys +import tempfile +import uuid +import zipfile + +from competition_results import ( + DUEL_PLAYERS, SPEEDRUN_LOSS_FRAMES, SPEEDRUN_PROFILE, TRACKS, duel_report, duel_schedule, + schedule, speedrun_report, summarize, verify_evidence, +) + + +HERE = Path(__file__).resolve().parent +REPO = HERE.parents[2] +RELEASES = [ + ("DareFightingICE-7.1.zip", "510752a69a097b767677d3911b1407d6a08a721dad4faf2cb5b7a19b988f1c62"), + ("resource-7.1.zip", "386fd713f901db00583054528ccfbce315953c157dc16231c4367416d86dce53"), +] +LIMIT = 64 * 1024 * 1024 +BASE = "docker.io/library/python:3.12.10-slim-bookworm@sha256:fd95fa221297a88e1cf49c55ec1828edd7c5a428187e67b5d1805692d11588db" +ARCHIVE_PROFILE = "archive-based-v7.1-prototype" +DUEL_PROFILE = "duel-framedata-v1" + + +def sha(path): + with path.open("rb") as stream: + return hashlib.file_digest(stream, "sha256").hexdigest() + + +def outside_checkout(path): + path = path.resolve() + if path.is_relative_to(REPO): + raise ValueError("place generated contexts and results outside the repository") + return path + + +def install(destination, archives): + for path, (name, digest) in zip(archives, RELEASES, strict=True): + if sha(path) != digest: + raise ValueError(f"official {name} SHA256 mismatch") + destination.mkdir() + for path, prefix in zip(archives, ("FightingICE7.1", ""), strict=True): + with zipfile.ZipFile(path) as bundle: + for member in bundle.infolist(): + relative = Path(member.filename) + if relative.is_absolute() or ".." in relative.parts or stat.S_ISLNK(member.external_attr >> 16): + raise ValueError("unsupported member in pinned archive") + if prefix: + relative = relative.relative_to(prefix) + if member.is_dir(): + continue + if not relative.parts or relative.parts[0] not in {"data", "lib", "FightingICE.jar"}: + continue + target = destination / relative + target.parent.mkdir(parents=True, exist_ok=True) + with target.open("xb") as out, bundle.open(member) as source: + shutil.copyfileobj(source, out) + + +def snapshot(source, target): + """Stage plain source files, never mount the original submission directory.""" + if source.is_symlink() or not source.is_dir(): + raise ValueError("expected a controller directory, not a symlink") + hashes, total = {}, 0 + target.mkdir() + for folder, dirs, files in source.walk(): + if any((folder / name).is_symlink() for name in dirs): + raise ValueError("symlinks are not permitted in a controller bundle") + for name in sorted(files): + path = folder / name + info = path.lstat() + if not stat.S_ISREG(info.st_mode): + raise ValueError("controller bundles may contain only regular files") + total += info.st_size + if total > LIMIT or len(hashes) >= 1024: + raise ValueError("controller exceeds the Game Exam artifact limit") + relative = path.relative_to(source) + output = target / relative + output.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(path, output) + hashes[relative.as_posix()] = sha(output) + if "controller.py" not in hashes: + raise ValueError("missing controller.py") + return hashes + + +def public_tables(resources, destination): + if sha(resources) != RELEASES[1][1]: + raise ValueError("official resource-7.1.zip SHA256 mismatch") + with zipfile.ZipFile(resources) as bundle: + for character, _, _ in TRACKS.values(): + character_dir = destination / character + character_dir.mkdir(parents=True) + for name in ("Motion.csv", "gSetting.txt"): + (character_dir / name).write_bytes(bundle.read(f"data/characters/{character}/{name}")) + + +def dump(path, data): + path.write_text(json.dumps(data, indent=2) + "\n") + + +def mount(source, target, readonly=True): + if "," in str(source): + raise ValueError("Docker bind paths may not contain commas") + return ["--mount", f"type=bind,src={source},dst={target}" + (",readonly" if readonly else "")] + + +def docker(*args, **kwargs): + return subprocess.run(["docker", *args], check=True, **kwargs) + + +def run_match(output, setup, engine, public, image, match, *, audio=True): + output.mkdir() + prefix = "game-exam-ftg-" + uuid.uuid4().hex[:12] + isolated = ["--network", "none", "--cap-drop", "ALL", "--security-opt", "no-new-privileges", + "--user", f"{os.getuid()}:{os.getgid()}", "--read-only", + "--pids-limit", "128", "--memory", "1g", "--cpus", "1", + "--log-driver", "local", "--log-opt", "max-size=2m", "--log-opt", "max-file=2"] + trusted_mounts = mount(engine, "/install") + mount(output, "/evidence", False) + (output / "engine").mkdir() + trusted_mounts += mount(output / "engine", "/engine", False) + bridges = {} + with tempfile.TemporaryDirectory(prefix="ftg-wire-") as temp, ExitStack() as cleanup: + for side, name in enumerate((match["p1"], match["p2"]), 1): + if name not in setup: + continue + directory = Path(temp) / str(side) + directory.mkdir() + bridges[side] = f"/p{side}/play.sock" + trusted_mounts += mount(directory, f"/p{side}", False) + worker = f"{prefix}-p{side}" + cleanup.callback(subprocess.run, ["docker", "rm", "-f", worker], + check=False, capture_output=True, timeout=15) + docker("run", "-d", "--name", worker, *isolated, "--tmpfs", "/tmp:rw,nosuid,nodev,noexec", + *mount(directory, "/wire"), + *mount(setup[name], "/submission"), *mount(public, "/app/moves"), "-e", "PYTHONPATH=/submission", + image, "python", "/bridge/competition_wire.py", "/wire/play.sock", str(side), + stdout=subprocess.DEVNULL, timeout=30) + trusted = f"{prefix}-engine" + cleanup.callback(subprocess.run, ["docker", "rm", "-f", trusted], + check=False, capture_output=True, timeout=15) + try: + docker("run", "--name", trusted, *isolated, "--tmpfs", "/tmp:rw,nosuid,nodev,exec", + "-e", "HOME=/tmp", "-e", "XDG_CACHE_HOME=/tmp/cache", *trusted_mounts, image, "python", + "/bridge/competition_match.py", + json.dumps(dict(match=match, bridges=bridges, audio=audio)), timeout=340) + for side in bridges: + if int(docker("wait", f"{prefix}-p{side}", capture_output=True, timeout=5).stdout) != 0: + raise ValueError(f"player {side} controller failed") + finally: + for side in bridges: + with (output / f"p{side}-controller.log").open("wb") as log: + docker("logs", f"{prefix}-p{side}", stdout=log, stderr=subprocess.STDOUT, timeout=15) + assessed = docker("run", "--rm", *isolated, *mount(output, "/evidence"), image, + "python", "/bridge/competition_results.py", "/evidence", json.dumps(match), + capture_output=True, text=True, timeout=30) + return json.loads(assessed.stdout) + + +def stage_author(output, resources=None, *, track=None, league="standard"): + output.mkdir(parents=True) + (output / "environment").mkdir() + (output / "tests").mkdir() + instruction = (HERE / "competition_author.md").read_text() + role = "Your controller should play both sides as GARNET (Rushdown) or NEZ (Zoning)." + audio = ("Native `AudioData` is forwarded when the selected engine produces it; this task does " + "not provide the tournament's generative sound setup.") + scoring = ("Win a round by finishing with more remaining HP. A win earns one point, a draw earns " + "half a point, and a loss earns zero. Total remaining HP breaks points ties.") + if track: + character, baseline, _ = TRACKS[track] + role = f"Write one controller to play both sides as {character} ({track})." + audio = "This task does not provide audio or screen callbacks." + if league == "speedrun": + style = "close-range pressure" if track == "rushdown" else "distance control" + role += f" The opponent uses the same character and is controlled by {baseline}. Favor {style}." + scoring = ("Minimize average scored frames across 30 rounds, playing five matches on each side. " + "A win or draw by remaining HP counts the native elapsed frames. " + f"A loss counts {SPEEDRUN_LOSS_FRAMES} frames. The ranking uses only the average scored frames.") + (output / "instruction.md").write_text( + instruction.replace("{{ROLE}}", role).replace("{{AUDIO}}", audio).replace("{{SCORING}}", scoring)) + shutil.copyfile(HERE / "requirements.txt", output / "environment/requirements.txt") + if resources: + public_tables(resources, output / "environment/moves") + (output / "task.toml").write_text( + 'schema_version = "1.3"\nartifacts = ["/app/output/"]\n' + '[task]\nname = "embodied-first-exam/fightingice-controller-authoring"\n' + '[metadata]\ntask_type = "policy"\n' + '[agent]\ntimeout_sec = 600\nnetwork_mode = "public"\n' + '[verifier]\nenvironment_mode = "separate"\nnetwork_mode = "no-network"\n') + (output / "environment/Dockerfile").write_text( + f"FROM {BASE}\n" + "RUN sed -i 's|http://deb.debian.org|https://deb.debian.org|g' /etc/apt/sources.list.d/debian.sources" + " && apt-get -o Acquire::Retries=3 update && apt-get -o Acquire::Retries=3 install" + " -y --no-install-recommends bash curl git nodejs npm ca-certificates && rm -rf /var/lib/apt/lists/*\n" + "COPY requirements.txt /tmp/requirements.txt\n" + "RUN pip install --timeout 90 --retries 5 --no-deps -r /tmp/requirements.txt && pip check && mkdir -p /app/output\n" + + ("COPY moves /app/moves\n" if resources else "") + "WORKDIR /app\n") + (output / "tests/Dockerfile").write_text(f"FROM {BASE}\nCOPY test.sh /tests/test.sh\n") + verifier = output / "tests/test.sh" + verifier.write_text( + '#!/bin/bash\nset -eu\n' + 'if test -f /app/output/controller.py && test ! -L /app/output/controller.py' + ' && PYTHONPYCACHEPREFIX=/tmp/author-cache python -m py_compile /app/output/controller.py; then\n' + ' echo 1 > /logs/verifier/reward.txt\nelse\n echo 0 > /logs/verifier/reward.txt\nfi\n') + verifier.chmod(0o755) + dump(output / "author-job.json", {"tasks": [{"path": str(output.resolve())}], + "n_attempts": 1, "n_concurrent_trials": 1, + "retry": {"max_retries": 0}}) + + +def load_model_profile(path): + profile = json.loads(path.read_text()) + if (not isinstance(profile, dict) or set(profile) - {"agents", "n_attempts", "n_concurrent_trials", "retry"} + or profile.get("n_attempts", 1) != 1 or profile.get("n_concurrent_trials", 1) != 1 + or profile.get("retry", {"max_retries": 0}) != {"max_retries": 0}): + raise ValueError(f"{path}: expected a single-agent profile with no job overrides or retries") + agents = profile.get("agents") + if not isinstance(agents, list) or len(agents) != 1 or not isinstance(agents[0], dict): + raise ValueError(f"{path}: expected exactly one Harbor agent") + agent = agents[0] + if (set(agent) - {"name", "model_name", "kwargs"} or not agent.get("name") + or not isinstance(agent["name"], str) or not isinstance(agent.get("kwargs", {}), dict) + or not isinstance(agent.get("model_name", ""), str)): + raise ValueError(f"{path}: use a native Harbor agent with name, model_name and optional kwargs") + return {"agents": [agent]} + + +def load_native_profile(path): + from harbor.agents.factory import AgentFactory + + profile = load_model_profile(path) + if profile["agents"][0]["name"] not in AgentFactory.registered_names(): + raise ValueError(f"{path}: expected a built-in Harbor agent name") + return profile + + +def author_controller(harbor, task, jobs, side, profile): + with tempfile.TemporaryDirectory(prefix="ftg-profile-") as temp: + config = Path(temp) / "agent.json" + dump(config, profile) + subprocess.run([harbor, "run", "-c", str(task / "author-job.json"), "-c", str(config), + "--jobs-dir", str(jobs), "--job-name", side, "-y", "--quiet"], check=True) + job = jobs / side + trials = list(job.glob("*/result.json")) + if len(trials) != 1: + raise ValueError(f"{side}: expected one Harbor trial; see {job}") + result = json.loads(trials[0].read_text()) + agent = result.get("agent_info") or {} + rewards = (result.get("verifier_result") or {}).get("rewards", {}) + if (result.get("exception_info") is not None or not result.get("finished_at") + or result.get("verifier_environment_mode") != "separate" or rewards.get("reward") != 1 + or agent.get("name") != profile["agents"][0]["name"]): + raise ValueError(f"{side}: Harbor did not produce a verified controller; see {job}") + options = profile["agents"][0] + return trials[0].parent / "artifacts/app/output", { + "agent": agent["name"], "agent_version": agent.get("version"), + "model_name": options.get("model_name"), + "reasoning_effort": options.get("kwargs", {}).get("reasoning_effort"), + "trial": str(trials[0].relative_to(jobs.parent)), + } + + +def build_report(rows, results, provenance): + profile = provenance["profile"] + if profile == DUEL_PROFILE: + return duel_report(rows, results, provenance["models"]) + if profile == SPEEDRUN_PROFILE: + return speedrun_report(rows, results, provenance.get("models")) + if profile == ARCHIVE_PROFILE: + return {"partial_mcts_only": provenance["partial_mcts_only"], **summarize(rows, results)} + raise ValueError("unknown competition profile") + + +def run_series(args, output, rows, sources, profiles=None): + duel = args.command == "duel" + speedrun = rows[0]["league"] == "speedrun" + output.mkdir(parents=True) + dump(output / "schedule.json", rows) + bundle_dir = output / "controllers" + bundle_dir.mkdir() + if profiles: + harbor = shutil.which("harbor") or str(Path(sys.executable).with_name("harbor")) + if not Path(harbor).is_file(): + raise ValueError("install the repository's pinned Harbor dependency and activate its environment") + if duel or speedrun: + # Build from this checkout so a stale bridge image cannot forward audio. + image = docker("build", "--quiet", "-f", str(HERE / "competition.Dockerfile"), str(HERE), + capture_output=True, text=True, timeout=900).stdout.strip() + else: + image = docker("image", "inspect", "--format", "{{.Id}}", args.image or "game-exam:fightingice-competition", + capture_output=True, text=True, timeout=30).stdout.strip() + results = [] + with tempfile.TemporaryDirectory(prefix="ftg-engine-") as temp, ExitStack() as cleanup: + pinned = "game-exam-ftg-run:" + uuid.uuid4().hex + docker("image", "tag", image, pinned, timeout=30) + cleanup.callback(subprocess.run, ["docker", "image", "rm", pinned], + check=False, capture_output=True, timeout=15) + engine = Path(temp) / "engine" + install(engine, [args.release, args.resources]) + public = Path(temp) / "moves" + public_tables(args.resources, public) + models, hashes, setup = {}, {}, {} + if profiles: + task = output / "author-task" + stage_author(task, args.resources, track=args.track, league=rows[0]["league"]) + for side, profile in profiles.items(): + print(f"Authoring {side} with Harbor", flush=True) + source, models[side] = author_controller(harbor, task, output / "author-jobs", side, profile) + setup[side] = bundle_dir / side + hashes[side] = snapshot(source, setup[side]) + else: + setup = {name: bundle_dir / name for name in sources} + hashes = {name: snapshot(Path(path), setup[name]) for name, path in sources.items()} + provenance = {"release_sha256": dict(RELEASES), "image": image, "controller_sha256": hashes} + if profiles: + provenance["author_instruction_sha256"] = sha(task / "instruction.md") + provenance["models"] = models + if duel: + provenance.update(profile=DUEL_PROFILE, track=args.track, pairs=args.pairs) + elif speedrun: + provenance.update(profile=SPEEDRUN_PROFILE, track=args.track, baseline=TRACKS[args.track][1]) + else: + provenance.update(profile=ARCHIVE_PROFILE, partial_mcts_only=args.mcts_only, + organizer_source="operator-supplied; not authenticated" if args.organizer else None) + dump(output / "provenance.json", provenance) + for i, row in enumerate(rows, 1): + match_dir = output / f"{i:04d}" + if duel or speedrun: + print(f"Match {i}/{len(rows)}: {row['p1']} (P1) vs {row['p2']} (P2)", flush=True) + results.append(run_match(match_dir, setup, engine, public, pinned, row, audio=not (duel or speedrun))) + dump(match_dir / "verified.json", results[-1]) + report = build_report(rows, results, provenance) + report_path = output / ("duel-report.json" if duel else "league-report.json") + dump(report_path, report) + if duel or speedrun: + print(json.dumps({"standings": report["standings"], "report": str(report_path)}, indent=2)) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + sub = parser.add_subparsers(dest="command", required=True) + author = sub.add_parser("author") + author.add_argument("output", type=Path) + author.add_argument("--resources", type=Path) + duel = sub.add_parser("duel", help="author two frozen controllers with Harbor, then play side-swapped matches") + duel.add_argument("--model-a", type=Path, required=True, metavar="PROFILE.json") + duel.add_argument("--model-b", type=Path, required=True, metavar="PROFILE.json") + duel.add_argument("--track", choices=TRACKS, default="rushdown") + duel.add_argument("--pairs", type=int, default=1, help="P1/P2 swap pairs (two matches per pair)") + duel.add_argument("--release", type=Path, required=True) + duel.add_argument("--resources", type=Path, required=True) + duel.add_argument("--output", type=Path, required=True) + for verb in ("plan", "run", "summarize"): + cmd = sub.add_parser(verb) + if verb == "summarize": + cmd.add_argument("output", type=Path) + continue + cmd.add_argument("--track", choices=TRACKS, required=True) + cmd.add_argument("--league", choices=("standard", "style", "speedrun"), required=True) + cmd.add_argument("--mcts-only", action="store_true") + cmd.add_argument("entries", nargs="+" if verb == "plan" else "*", metavar="NAME=CONTROLLER_DIRECTORY") + if verb == "run": + cmd.add_argument("--model", type=Path, metavar="PROFILE.json", + help="author one speedrun controller with a native Harbor agent") + cmd.add_argument("--release", type=Path, required=True) + cmd.add_argument("--resources", type=Path, required=True) + cmd.add_argument("--organizer", type=Path) + cmd.add_argument("--image", help="runtime image for Standard and Style (default: game-exam:fightingice-competition)") + cmd.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + if args.command == "author": + stage_author(outside_checkout(args.output), args.resources) + return + if args.command == "duel": + try: + rows = duel_schedule(args.track, args.pairs) + profiles = {name: load_native_profile(path) + for name, path in zip(DUEL_PLAYERS, (args.model_a, args.model_b), strict=True)} + except (ValueError, OSError) as error: + duel.error(str(error)) + run_series(args, outside_checkout(args.output), rows, {}, profiles) + return + if args.command == "summarize": + rows = json.loads((args.output / "schedule.json").read_text()) + provenance = json.loads((args.output / "provenance.json").read_text()) + profile = provenance["profile"] + if profile == DUEL_PROFILE: + expected = duel_schedule(provenance["track"], provenance["pairs"]) + elif profile == SPEEDRUN_PROFILE: + track = provenance["track"] + if provenance["baseline"] != TRACKS[track][1]: + raise ValueError("stored speedrun baseline does not match the track") + expected = schedule(track, provenance["controller_sha256"], "speedrun") + elif profile == ARCHIVE_PROFILE: + if not rows or rows[0]["league"] not in ("standard", "style"): + raise ValueError("stored league does not match the archive profile") + names = [name for name in provenance["controller_sha256"] if name != "organizer"] + expected = schedule(rows[0]["track"], names, rows[0]["league"], provenance["partial_mcts_only"]) + else: + raise ValueError("unknown competition profile") + if not rows or rows != expected: + raise ValueError("stored match matrix does not match the frozen roster") + results = [] + for i, row in enumerate(expected, 1): + folder = args.output / f"{i:04d}" + verified = folder / "verified.json" + if not verified.is_file(): + raise ValueError(f"{folder.name}: missing verified match") + parsed = verify_evidence(folder, row) + if json.loads(verified.read_text()) != json.loads(json.dumps(parsed)): + raise ValueError(f"{folder.name}: native CSV and verified result differ") + results.append(parsed) + print(json.dumps(build_report(rows, results, provenance), indent=2)) + return + model = getattr(args, "model", None) + if model and (args.league != "speedrun" or args.entries): + parser.error("--model requires --league speedrun and replaces NAME=CONTROLLER_DIRECTORY") + if not model and not args.entries: + parser.error("supply a controller directory or a speedrun --model profile") + if any("=" not in value or not value.split("=", 1)[1] for value in args.entries): + parser.error("entries must be NAME=CONTROLLER_DIRECTORY") + assignments = [value.split("=", 1) for value in args.entries] + rows = schedule(args.track, ["entry"] if model else [name for name, _ in assignments], + args.league, args.mcts_only) + if args.command == "plan": + print(json.dumps(rows, indent=2)) + return + if args.league == "speedrun": + if args.organizer is not None or args.image is not None: + parser.error("speedrun uses the track's MCTS and builds its runtime image from this checkout") + elif (args.organizer is None) != args.mcts_only: + parser.error("two-baseline schedule needs an operator-supplied --organizer controller; --mcts-only is explicitly partial") + sources = dict(assignments) + if args.organizer: + sources["organizer"] = args.organizer + try: + profiles = {"entry": load_native_profile(model)} if model else None + except (ValueError, OSError) as error: + parser.error(str(error)) + run_series(args, outside_checkout(args.output), rows, sources, profiles) + + +if __name__ == "__main__": + main() diff --git a/game_first_exam/benchmarks/fightingice/competition_author.md b/game_first_exam/benchmarks/fightingice/competition_author.md new file mode 100644 index 0000000..51cf14a --- /dev/null +++ b/game_first_exam/benchmarks/fightingice/competition_author.md @@ -0,0 +1,33 @@ +# Write a DareFightingICE controller + +Write a Python controller under `/app/output/`. `controller.py` must export +`AI`, a no-argument subclass of `pyftg.AIInterface`. Put any helper modules +there as well. The evaluation runs your frozen source in a fresh container +without internet access or dependency installation. Python's standard library +and `pyftg` 2.3 are available. Keep the bundle to regular files under 64 MiB. +Native `Motion.csv` and `gSetting.txt` for GARNET/NEZ are available under +`/app/moves/` in matches and during authoring when staged with `--resources`. + +{{ROLE}} +Use `initialize(game_data, player_number)` to identify the character and side +(`True` for P1). `get_information(frame_data, is_control)` receives the +engine's delayed `FrameData`, which can be empty at round start, and the native +control flag. The published standard data path is available; no undelayed +state, spectator stream, or engine management calls are provided. {{AUDIO}} +`processing()` updates +your chosen `pyftg.Key`, and `input()` returns it. You can use +`pyftg.CommandCenter` to construct native key sequences where appropriate. The +remaining native callbacks cover initialization, round/match end and cleanup. +Inspect the installed `AIInterface` signatures and types before writing code. + +The match clock continues while the controller runs. Each round starts with +400 HP and lasts at most 3600 native frames. {{SCORING}} + +Write and compile a working submission within the 600-second authoring +budget. Save a working version before spending time on refinements. Do not +connect to private game services, download ready-made entries, or rely on +network calls during a match. + +This Harbor task checks only that the controller entry file exists and +compiles. It does not play a match or assign a league score; that happens +after authoring with the separate native match runner. diff --git a/game_first_exam/benchmarks/fightingice/competition_match.py b/game_first_exam/benchmarks/fightingice/competition_match.py new file mode 100644 index 0000000..b67ecfc --- /dev/null +++ b/game_first_exam/benchmarks/fightingice/competition_match.py @@ -0,0 +1,151 @@ +"""Trusted runner for one native match. Never imports a submitted controller.""" +from concurrent.futures import ThreadPoolExecutor +import json +import os +from pathlib import Path +import socket +import subprocess +import sys +import time +from contextlib import ExitStack + +from competition_results import TRACKS, read_match +from competition_wire import packet, public_state, receive, send + + +PORT = 31415 + + +def relay(native, player, *, audio=True): + from google.protobuf.message import DecodeError + from pyftg.models.enums.flag import Flag + from pyftg.protoc.message_pb2 import GrpcKey + from pyftg.protoc.service_pb2 import PlayerGameState + + callbacks = 0 + round_results = [] + while True: + tag = receive(native, 1) + if tag == b"\0": + if player is not None: + try: + player.sendall(tag) + except OSError: + player = None + return {"callbacks": callbacks, "controller_disconnected": player is None, + "round_results": round_results} + if tag != b"\1": + raise ValueError("unexpected native player message") + flag, state = public_state(PlayerGameState.FromString(packet(native)), audio=audio) + if flag == Flag.INITIALIZE: + round_results = [] + if flag in (Flag.ROUND_END, Flag.GAME_END): + result = state.round_result + round_results.append([result.current_round, *result.remaining_hps, result.elapsed_frame]) + key = GrpcKey() + if player is not None: + try: + player.sendall(tag) + send(player, state.SerializeToString()) + if flag == Flag.PROCESSING: + key.ParseFromString(packet(player, 128)) + key.DiscardUnknownFields() + except (OSError, EOFError, ValueError, DecodeError): + # The engine clock keeps running. Seal this failure independently of the native outcome. + player = None + if flag == Flag.PROCESSING: + callbacks += 1 + send(native, key.SerializeToString()) + + +def play(root, evidence, match, bridges, *, audio): + from pyftg.protoc.service_pb2 import InitializeRequest, RunGameRequest, RunGameResponse + + character, baseline, _ = TRACKS[match["track"]] + names = [match["p1"], match["p2"]] + for side, name in enumerate(names, 1): + if side not in bridges and name != baseline: + raise ValueError("only the track's native MCTS baseline may run inside the engine") + with ExitStack() as stack: + listeners = {} + for side, path in bridges.items(): + listener = stack.enter_context(socket.socket(socket.AF_UNIX)) + listener.bind(path) + os.chmod(path, 0o666) + listener.listen(1) + listener.settimeout(60) + listeners[side] = listener + players = {side: stack.enter_context(listener.accept()[0]) for side, listener in listeners.items()} + for player in players.values(): + player.settimeout(1) + log = stack.enter_context((evidence / "engine.log").open("wb")) + proc = subprocess.Popen( + ["java", "-cp", "FightingICE.jar:lib/*:lib/lwjgl/*:lib/lwjgl/natives/linux/amd64/*", + "Main", "--headless-mode", "--limithp", "400", "400", "--pyftg-mode"], + cwd=root, stdout=log, stderr=subprocess.STDOUT, + env={**os.environ, "SERVER_HOST": "127.0.0.1"}) + try: + until = time.monotonic() + 30 + while "Waiting to launch a game" not in (evidence / "engine.log").read_text(errors="replace"): + if proc.poll() is not None or time.monotonic() >= until: + raise RuntimeError("native startup failed; inspect engine.log") + time.sleep(.05) + connections = {} + for side, player in players.items(): + native = stack.enter_context(socket.create_connection(("127.0.0.1", PORT), timeout=20)) + native.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) + native.sendall(b"\1") + request = InitializeRequest(player_number=side == 1, player_name=names[side-1], is_blind=False) + send(native, request.SerializeToString()) + connections[side] = (native, player) + control = stack.enter_context(socket.create_connection(("127.0.0.1", PORT), timeout=10)) + control.sendall(b"\2") + request = RunGameRequest(character_1=character, character_2=character, + player_1=names[0], player_2=names[1], game_number=1) + send(control, request.SerializeToString()) + reply = RunGameResponse.FromString(packet(control)) + if reply.status_code != 0: + raise RuntimeError(f"native match rejected: {reply.response_message}") + with ThreadPoolExecutor() as threads: + futures = {side: threads.submit(relay, *pair, audio=audio) for side, pair in connections.items()} + try: + control.settimeout(2) + until = time.monotonic() + 280 + while True: + try: + if receive(control, 1) != b"\0": + raise RuntimeError("unexpected completion message") + break + except TimeoutError: + if (proc.poll() is not None or time.monotonic() >= until + or 'Exception in thread "main"' in + (evidence / "engine.log").read_text(errors="replace")): + raise RuntimeError("native match failed or timed out; inspect engine.log") + callbacks = {side: future.result(timeout=25) for side, future in futures.items()} + finally: + # Release blocking relays before joining their threads on a broken game. + for side, future in futures.items(): + if not future.done(): + connections[side][0].shutdown(socket.SHUT_RDWR) + finally: + if proc.poll() is None: + proc.terminate() + try: + proc.wait(timeout=5) + except subprocess.TimeoutExpired: + proc.kill() + proc.wait() + points, = (root / "log/point").glob("*.csv") + style, = (root / "log/style").glob("*.csv") + native = read_match(match["track"], points, style) + (evidence / "match-result.json").write_text(json.dumps({**native, "callbacks": callbacks}, indent=2)) + + +if __name__ == "__main__": + spec = json.loads(sys.argv[1]) + root = Path("/engine") + for name in ("FightingICE.jar", "lib", "data"): + (root / name).symlink_to(Path("/install") / name) + play(Path("/engine"), Path("/evidence"), spec["match"], + {int(side): path for side, path in spec["bridges"].items()}, + audio=spec["audio"]) diff --git a/game_first_exam/benchmarks/fightingice/competition_results.py b/game_first_exam/benchmarks/fightingice/competition_results.py new file mode 100644 index 0000000..a6cd6a3 --- /dev/null +++ b/game_first_exam/benchmarks/fightingice/competition_results.py @@ -0,0 +1,198 @@ +"""2026 archive schedule and result columns, without executing archive code.""" +import csv +from itertools import combinations, groupby +import json +import math +from pathlib import Path +import re +from statistics import mean +import sys + + +TRACKS = { + "rushdown": ("GARNET", "MctsAi23i", ("comboCount", "ProximityScore", "corneredFrames")), + "zoning": ("NEZ", "MctsAiZoning", ("ProjectileScore", "ProximityScore", "AntiAirCount")), +} +DUEL_PLAYERS = ("model-a", "model-b") +SPEEDRUN_PROFILE = "speedrun-mcts-framedata-v1" +SPEEDRUN_LOSS_FRAMES = 4200 + + +def duel_schedule(track, pairs): + if type(pairs) is not int or pairs < 1: + raise ValueError("side-swapped pair count must be a positive integer") + a, b = DUEL_PLAYERS + return [ + dict(track=track, league="standard", character=TRACKS[track][0], p1=p1, p2=p2, game=i) + for i in range(1, pairs + 1) for p1, p2 in ((a, b), (b, a)) + ] + + +def round_points(hp, other): + return 1 if hp > other else .5 if hp == other else 0 + + +def schedule(track, entries, league, mcts_only=False): + character, mcts, _ = TRACKS[track] + names = list(entries) + if (not names or len(set(names)) != len(names) + or any(not re.fullmatch(r"[a-z][a-z0-9-]{0,31}", n) or n == "organizer" for n in names)): + raise ValueError("use distinct lowercase controller names, excluding official baselines") + opponents = [mcts] if mcts_only or league == "speedrun" else [mcts, "organizer"] + if league == "standard": + pairs, count = combinations([*names, *opponents], 2), 1 + elif league in ("style", "speedrun"): + pairs, count = ((entry, foe) for entry in names for foe in opponents), 5 + else: + raise ValueError("unknown league") + return [ + dict(track=track, league=league, character=character, p1=a, p2=b, game=i) + for p1, p2 in pairs for a, b in ((p1, p2), (p2, p1)) for i in range(1, count + 1) + ] + + +def read_match(track, point_file, style_file): + with point_file.open(newline="") as stream: + points = [tuple(map(int, row)) for row in csv.reader(stream)] + if len(points) != 3 or any(len(row) != 4 or row[0] != i or not 1 <= row[3] <= 3600 + or max(row[1:3]) > 400 for i, row in enumerate(points, 1)): + raise ValueError("invalid three-round native point CSV") + fields = [f"P{side}_{field}" for side in (1, 2) for field in TRACKS[track][2]] + with style_file.open(newline="") as stream: + reader = csv.DictReader(stream) + if reader.fieldnames != fields: + raise ValueError("unexpected native style columns") + style = [{key: float(row[key]) for key in fields} for row in reader] + if len(style) != 3 or not all(math.isfinite(n) for row in style for n in row.values()): + raise ValueError("invalid three-round native style CSV") + return {"points": points, "style": style} + + +def summarize(schedule_rows, results): + """Return archive-derived metrics. Never invent a combined style ranking.""" + if not schedule_rows or len(results) != len(schedule_rows): + raise ValueError("incomplete match matrix") + league, track = schedule_rows[0]["league"], schedule_rows[0]["track"] + _, mcts, fields = TRACKS[track] + baselines = {mcts, "organizer"} + totals = {} + for match, result in zip(schedule_rows, results, strict=True): + if match["track"] != track or match["league"] != league: + raise ValueError("report one track and league at a time") + p1, p2 = match["p1"], match["p2"] + for side, name, foe in ((1, p1, p2), (2, p2, p1)): + if league == "style" and name in baselines: + continue + row = totals.setdefault(name, dict(games=0, round_points=0, remaining_hp=0, + speed_frames=0, style={field: [] for field in fields})) + row["games"] += 1 + for (_, hp1, hp2, frames), values in zip(result["points"], result["style"], strict=True): + hp, other = (hp1, hp2) if side == 1 else (hp2, hp1) + row["round_points"] += round_points(hp, other) + row["remaining_hp"] += hp + if league == "style" and foe in baselines: + row["speed_frames"] += frames if hp >= other else SPEEDRUN_LOSS_FRAMES + for field in fields: + row["style"][field].append(values[f"P{side}_{field}"]) + for row in totals.values(): + row["style"] = {field: mean(values) for field, values in row["style"].items()} + if league == "standard": + del row["speed_frames"] + report = {"track": track, "league": league, "controllers": totals} + if league == "standard": + ordered = sorted(totals, key=lambda name: (-totals[name]["round_points"], + -totals[name]["remaining_hp"], name)) + standings, previous = [], None + for index, name in enumerate(ordered, 1): + score = totals[name]["round_points"], totals[name]["remaining_hp"] + if score != previous: + standings.append({"rank": index, "controllers": []}) + previous = score + standings[-1]["controllers"].append(name) + report["standings"] = standings + return report + + +def duel_report(rows, results, models): + report = summarize(rows, results) + report.update(mode="duel", models=models, pairs=len(rows) // 2, audio=False, matches=[ + {**match, "rounds": result["points"], + "round_points": {match["p1"]: sum(round_points(hp1, hp2) for _, hp1, hp2, _ in result["points"]), + match["p2"]: sum(round_points(hp2, hp1) for _, hp1, hp2, _ in result["points"])}} + for match, result in zip(rows, results, strict=True) + ]) + return report + + +def speedrun_report(rows, results, models=None): + if not rows or len(rows) != len(results): + raise ValueError("incomplete speedrun match matrix") + track = rows[0]["track"] + _, baseline, _ = TRACKS[track] + entries = dict.fromkeys(name for match in rows for name in (match["p1"], match["p2"]) if name != baseline) + if rows != schedule(track, entries, "speedrun"): + raise ValueError("speedrun requires five matches on each side against the track's MCTS") + totals = {entry: dict(games=0, wins=0, draws=0, losses=0, speed_frames=0) for entry in entries} + matches = [] + for match, result in zip(rows, results, strict=True): + entry_is_p1 = match["p2"] == baseline + entry = match["p1"] if entry_is_p1 else match["p2"] + total = totals[entry] + total["games"] += 1 + points = result["points"] + if len(points) != 3: + raise ValueError("incomplete speedrun rounds") + rounds = [] + for number, hp1, hp2, frames in points: + hp, other = (hp1, hp2) if entry_is_p1 else (hp2, hp1) + outcome = "loss" if hp < other else "win" if hp > other else "draw" + scored = SPEEDRUN_LOSS_FRAMES if outcome == "loss" else frames + total[{"win": "wins", "draw": "draws", "loss": "losses"}[outcome]] += 1 + total["speed_frames"] += scored + rounds.append(dict(round=number, p1_hp=hp1, p2_hp=hp2, elapsed_frames=frames, + scored_frames=scored, outcome=outcome)) + matches.append({**match, "entry": entry, "rounds": rounds}) + for total in totals.values(): + total["rounds"] = total["games"] * 3 + total["penalty_rounds"] = total["losses"] + total["average_frames"] = total["speed_frames"] / total["rounds"] + total["average_seconds"] = total["average_frames"] / 60 + + def score(entry): + # Every entry plays the same number of rounds, so compare integer totals. + return totals[entry]["speed_frames"] + + standings, rank = [], 1 + for _, group in groupby(sorted(entries, key=lambda entry: (score(entry), entry)), key=score): + controllers = list(group) + standings.append(dict(rank=rank, controllers=controllers)) + rank += len(controllers) + report = dict(profile=SPEEDRUN_PROFILE, league="speedrun", track=track, baseline=baseline, audio=False, + controllers=totals, standings=standings, matches=matches) + if models: + report["models"] = models + return report + + +def verify_evidence(folder, match): + points, = (folder / "engine/log/point").glob("*.csv") + style, = (folder / "engine/log/style").glob("*.csv") + native = read_match(match["track"], points, style) + recorded = json.loads((folder / "match-result.json").read_text()) + callbacks = recorded.pop("callbacks") + points = [list(row) for row in native["points"]] + if recorded != {"points": points, "style": native["style"]}: + raise ValueError("engine result disagrees with native CSVs") + expected = {str(side) for side, name in enumerate((match["p1"], match["p2"]), 1) + if name != TRACKS[match["track"]][1]} + if set(callbacks) != expected: + raise ValueError("missing or unknown callback evidence") + for record in callbacks.values(): + if (record["controller_disconnected"] is not False or record["round_results"] != points + or type(record["callbacks"]) is not int or record["callbacks"] < 1): + raise ValueError("controller failed or native round callbacks disagree with the point CSV") + return native + + +if __name__ == "__main__": + print(json.dumps(verify_evidence(Path(sys.argv[1]), json.loads(sys.argv[2])))) diff --git a/game_first_exam/benchmarks/fightingice/competition_wire.py b/game_first_exam/benchmarks/fightingice/competition_wire.py new file mode 100644 index 0000000..177abbc --- /dev/null +++ b/game_first_exam/benchmarks/fightingice/competition_wire.py @@ -0,0 +1,101 @@ +"""Native player packets over a player-only Unix socket; no engine control RPCs.""" +import argparse +import socket +import time + + +def receive(sock, size): + data = bytearray() + while len(data) < size: + chunk = sock.recv(size - len(data)) + if not chunk: + raise EOFError("player socket closed") + data.extend(chunk) + return bytes(data) + + +def packet(sock, maximum=2**22): + size = int.from_bytes(receive(sock, 4), "little") + if size > maximum: + raise ValueError("oversized player packet") + return receive(sock, size) + + +def send(sock, payload): + sock.sendall(len(payload).to_bytes(4, "little") + payload) + + +def public_state(native, *, audio=True): + from pyftg.models.enums.flag import Flag + from pyftg.protoc.service_pb2 import PlayerGameState + + allowed = { + Flag.INITIALIZE: ("game_data",), + Flag.PROCESSING: ("frame_data", "audio_data") if audio else ("frame_data",), + Flag.ROUND_END: ("round_result",), + Flag.GAME_END: ("round_result",), + } + flag = Flag(native.state_flag) + state = PlayerGameState(state_flag=flag.value) + for field in allowed[flag]: + if native.HasField(field): + getattr(state, field).CopyFrom(getattr(native, field)) + if flag == Flag.PROCESSING: + state.is_control = native.is_control + # Rebuild rather than forwarding extra top-level fields or protobuf unknowns. + state.DiscardUnknownFields() + return flag, state + + +def controller(path, side): + from controller import AI + from pyftg import AudioData, FrameData, GameData, Key, RoundResult + from pyftg.models.enums.flag import Flag + from pyftg.protoc.service_pb2 import PlayerGameState + from pyftg.utils.protobuf import convert_key_to_proto + + ai = AI() + with socket.socket(socket.AF_UNIX) as sock: + until = time.monotonic() + 45 + while True: + try: + sock.connect(path) + break + except (FileNotFoundError, ConnectionRefusedError): + if time.monotonic() >= until: + raise + time.sleep(.05) + try: + while True: + tag = receive(sock, 1) + if tag == b"\0": + break + if tag != b"\1": + raise ValueError("unknown player event") + state = PlayerGameState.FromString(packet(sock)) + flag = Flag(state.state_flag) + if flag == Flag.INITIALIZE: + ai.initialize(GameData.from_proto(state.game_data), side == 1) + elif flag == Flag.PROCESSING: + ai.get_information(FrameData.from_proto(state.frame_data), state.is_control) + if state.HasField("audio_data"): + ai.get_audio_data(AudioData.from_proto(state.audio_data)) + ai.processing() + key = ai.input() + if not isinstance(key, Key): + raise TypeError("AI.input() must return pyftg.Key") + send(sock, convert_key_to_proto(key).SerializeToString()) + else: + ai.round_end(RoundResult.from_proto(state.round_result)) + if flag == Flag.GAME_END: + ai.game_end() + finally: + ai.close() + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("socket") + parser.add_argument("side", type=int, choices=(1, 2)) + args = parser.parse_args() + controller(args.socket, args.side) diff --git a/game_first_exam/benchmarks/fightingice/install_native.py b/game_first_exam/benchmarks/fightingice/install_native.py new file mode 100644 index 0000000..3b4ea69 --- /dev/null +++ b/game_first_exam/benchmarks/fightingice/install_native.py @@ -0,0 +1,79 @@ +"""Install a hash-checked native release outside the task source tree; stdlib only.""" +import argparse +import hashlib +import json +from pathlib import Path +import shutil +import tempfile +import urllib.request +import zipfile + + +def checked(data, expected): + if hashlib.sha256(data).hexdigest() != expected: + raise ValueError('upstream file digest mismatch') + return data + + +def verify(destination): + destination = Path(destination) + installed = json.loads((destination / 'installation.json').read_text()) + source = json.loads(Path(__file__).with_name('SOURCE.json').read_text()) + if installed['source'] != source or 'FightingICE.jar' not in installed['files']: + raise ValueError('native installation does not match the frozen source') + for name, digest in installed['files'].items(): + checked((destination / name).read_bytes(), digest) + for name, digest in source['resources'].items(): + checked((destination / name).read_bytes(), digest) + + +def install(destination, engine_archive=None, resources_archive=None, resources_dir=None): + source = json.loads(Path(__file__).with_name('SOURCE.json').read_text()) + destination = Path(destination) + if destination.exists(): + raise ValueError('choose a new native installation directory') + with tempfile.TemporaryDirectory() as temporary: + def archive(supplied, url, name): + if supplied: + return Path(supplied) + target = Path(temporary) / name + with urllib.request.urlopen(url, timeout=120) as response, target.open('wb') as stream: + shutil.copyfileobj(response, stream) + return target + + engine = archive(engine_archive, source['engine_url'], 'engine.zip') + checked(engine.read_bytes(), source['engine_sha256']) + selected = {} + with zipfile.ZipFile(engine) as bundle: + for info in bundle.infolist(): + relative = Path(*Path(info.filename).parts[1:]) + if info.is_dir() or relative.is_absolute() or '..' in relative.parts: + continue + if str(relative) == 'FightingICE.jar' or (relative.parts[0] == 'lib' and relative.suffix == '.jar'): + selected[str(relative)] = bundle.read(info) + if resources_dir: + for name, digest in source['resources'].items(): + selected[name] = checked((Path(resources_dir) / name).read_bytes(), digest) + else: + resources = archive(resources_archive, source['resources_url'], 'resources.zip') + with zipfile.ZipFile(resources) as bundle: + for name, digest in source['resources'].items(): + selected[name] = checked(bundle.read(name), digest) + for name, data in selected.items(): + path = destination / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(data) + (destination / 'data/ai').mkdir(parents=True) + (destination / 'installation.json').write_text(json.dumps({ + 'source': source, 'files': {name: hashlib.sha256(data).hexdigest() for name, data in selected.items()} + }, indent=2) + '\n') + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('destination', type=Path) + parser.add_argument('--engine-archive', type=Path) + parser.add_argument('--resources-archive', type=Path) + parser.add_argument('--resources-dir', type=Path) + args = parser.parse_args() + install(args.destination, args.engine_archive, args.resources_archive, args.resources_dir) diff --git a/game_first_exam/benchmarks/fightingice/instance_schema.py b/game_first_exam/benchmarks/fightingice/instance_schema.py new file mode 100644 index 0000000..1784caf --- /dev/null +++ b/game_first_exam/benchmarks/fightingice/instance_schema.py @@ -0,0 +1,32 @@ +"""Frozen native match conditions, validated without importing Java or pyftg.""" +from config_schema import validate_engine_versions + +SCHEMA_VERSION = '1.0.0' +BENCHMARK = 'fightingice' +FIELDS = {'engine_versions', 'player', 'characters', 'opponent', 'rounds', 'round_frames', 'initial_hp', 'native_seed_policy'} +METRICS = {'round_win_score'} +PROFILES = {'native-delayed-framedata-v1'} +REDUCERS = {('family_macro', '1.0.0')} + + +def validate(value): + validate_engine_versions(value['engine_versions'], {'fightingice': '7.0', 'pyftg': '2.3'}) + if type(value['player']) is not int or value['player'] not in (0, 1): + raise ValueError('player must be the native zero-based side') + if value['characters'] != ['ZEN', 'ZEN'] or value['opponent'] != 'pyftg-kick-b-v1': + raise ValueError('unsupported frozen character/opponent') + for name, expected in [('rounds', 3), ('round_frames', 3600), ('initial_hp', 400)]: + if type(value[name]) is not int or value[name] != expected: + raise ValueError('preserve native match limits: ' + name) + if value['env_id'] != 'DareFightingICE-ZEN-KickAI-v7.0' or value['family'] != 'zen-kick': + raise ValueError('unknown native match') + if value['seed'] != 0 or value['native_seed_policy'] != 'no-native-seed;deterministic-opponent': + raise ValueError('no native reset seed API is claimed') + if value['max_steps'] is not None: + raise ValueError('use native round limits, not a new public action cap') + if value['metric_spec'] != {'primary': 'round_win_score', 'reducer': 'family_macro', + 'reducer_version': '1.0.0', 'success_label': 'match_won'}: + raise ValueError('unsupported FightingICE scoring profile') + if value['capabilities'] != {'images': False, 'action_mode': 'enum', + 'timing': 'action-stepped', 'native_truncation': False}: + raise ValueError('unsupported FightingICE capabilities') diff --git a/game_first_exam/benchmarks/fightingice/metric_rules.py b/game_first_exam/benchmarks/fightingice/metric_rules.py new file mode 100644 index 0000000..1fcfe4b --- /dev/null +++ b/game_first_exam/benchmarks/fightingice/metric_rules.py @@ -0,0 +1,44 @@ +"""Validate native rounds and fixed-denominator match scores in the verifier.""" +import math + + +def validate_metrics(final, instance): + metrics = final['metrics'] + required = {'rounds', 'wins', 'losses', 'draws', 'completed_rounds', 'round_win_score', 'native_steps'} + if not isinstance(metrics, dict) or set(metrics) != required: + raise ValueError('unexpected FightingICE metrics') + rounds = metrics['rounds'] + if not isinstance(rounds, list) or len(rounds) > instance['rounds']: + raise ValueError('invalid native round count') + wins = losses = 0 + for index, result in enumerate(rounds, 1): + if not isinstance(result, dict) or set(result) != {'current_round', 'remaining_hps', 'elapsed_frame'}: + raise ValueError('malformed native round result') + if type(result['current_round']) is not int or result['current_round'] != index: + raise ValueError('native rounds must be complete and consecutive') + hp, elapsed = result['remaining_hps'], result['elapsed_frame'] + if not isinstance(hp, list) or len(hp) != 2 or any(type(x) is not int or not -400 <= x <= 400 for x in hp): + raise ValueError('invalid native remaining HP') + if type(elapsed) is not int or not 1 <= elapsed <= instance['round_frames']: + raise ValueError('invalid native elapsed frames') + if min(hp) > 0 and elapsed != instance['round_frames']: + raise ValueError('round ended without KO or the native frame limit') + wins += hp[instance['player']] > hp[1-instance['player']] + losses += hp[instance['player']] < hp[1-instance['player']] + expected = {'wins': wins, 'losses': losses, 'draws': len(rounds)-wins-losses, + 'completed_rounds': len(rounds), 'native_steps': final['steps']} + if any(type(metrics[key]) is not int or metrics[key] != value for key, value in expected.items()): + raise ValueError('inconsistent native match counters') + score = metrics['round_win_score'] + if type(score) not in (int, float) or not math.isfinite(score) or not math.isclose(score, 100*wins/3, abs_tol=1e-9): + raise ValueError('inconsistent fixed-denominator score') + completed = len(rounds) == instance['rounds'] + if final['terminated'] != completed or final['truncated'] or final['return'] != 0: + raise ValueError('inconsistent native match ending or invented scalar reward') + if final['success'] != (completed and wins > losses): + raise ValueError('inconsistent match success') + elapsed = sum(result['elapsed_frame'] for result in rounds) + if (final['steps'] < elapsed or final['steps'] > instance['rounds']*instance['round_frames'] + or (completed and final['steps'] != elapsed) + or (not completed and final['steps'] >= elapsed + instance['round_frames'])): + raise ValueError('native frames disagree with action count') diff --git a/game_first_exam/benchmarks/fightingice/requirements.txt b/game_first_exam/benchmarks/fightingice/requirements.txt new file mode 100644 index 0000000..f41beba --- /dev/null +++ b/game_first_exam/benchmarks/fightingice/requirements.txt @@ -0,0 +1,9 @@ +grpcio==1.62.3 +grpcio-tools==1.62.3 +imageio==2.37.0 +imageio-ffmpeg==0.6.0 +numpy==1.26.4 +pillow==10.4.0 +protobuf==4.25.9 +pyftg==2.3 +setuptools==84.2.1 diff --git a/game_first_exam/images/fightingice-files/FILES.json b/game_first_exam/images/fightingice-files/FILES.json new file mode 100644 index 0000000..0971b52 --- /dev/null +++ b/game_first_exam/images/fightingice-files/FILES.json @@ -0,0 +1,14 @@ +{ + "source": "game_first_exam/benchmarks/fightingice", + "files": { + "LICENSE-pyftg": "5b81f7cd430181999f4024883eb3c6f3f1c00367862c1bbc3d2d853505f6276e", + "SOURCE.json": "68da0606b71159110c2f6345bbc3b75904c3e14cc5b2c10b743845a75af41ecd", + "adapter.py": "93c85825cf47d3cc11464d40db1fbb8a280fc0309460723f04e85065625c06b5", + "bridge.py": "3fd3cc218baedcc11dda25a0390e18d7fe60e3e1260ace188c633b8cc2148960", + "install_native.py": "aee6d873e297ed30a7bf46afb9ac129343220921c4a0e3224288b3197aa242a7", + "instance_schema.py": "dd507778a2623b320e10351ef34f8478dd9bb3de30b4bb2324de30e51e6d4aae", + "metric_rules.py": "5046ddb1669ecb66f610a315cb74ae5fbf980d394cf152acf61424867390995f", + "requirements.txt": "5b1b1fa3de3a50f041fe4d5158436e53bb2be83026ffa4d6c543be67ff2ba11a" + }, + "image": "ghcr.io/mll-lab-nu/efe:fightingice-files-0.1.0@sha256:20832c27e23b258cb2a489c6614e531e35b535d83c662bb5e99ab2db47830e71" +} diff --git a/game_first_exam/images/fightingice-files/README.md b/game_first_exam/images/fightingice-files/README.md new file mode 100644 index 0000000..4111670 --- /dev/null +++ b/game_first_exam/images/fightingice-files/README.md @@ -0,0 +1,6 @@ +# FightingICE files + +Files-only payload for the native FightingICE adapter, configuration validation, +trusted Python callbacks and installer. The installer downloads hash-checked +upstream resources during image construction; no game binaries or art are +vendored. This image is assembled locally, not published by this change. diff --git a/game_first_exam/images/fightingice-files/VERSION b/game_first_exam/images/fightingice-files/VERSION new file mode 100644 index 0000000..6e8bf73 --- /dev/null +++ b/game_first_exam/images/fightingice-files/VERSION @@ -0,0 +1 @@ +0.1.0 diff --git a/game_first_exam/tasks/fightingice/README.md b/game_first_exam/tasks/fightingice/README.md new file mode 100644 index 0000000..250ab70 --- /dev/null +++ b/game_first_exam/tasks/fightingice/README.md @@ -0,0 +1,12 @@ +# FightingICE frozen tasks + +Two standard smoke configurations use DareFightingICE 7.0, ZEN versus the pyftg +KickAI B-button example, switching the controlled player side. Native interface, +observation permissions, scoring, packaging and deviations are documented in +[the benchmark README](../../benchmarks/fightingice/README.md). + +Run `harbor run --game-suite fightingice --standard --list` to validate the suite. +Run with `-c configs/harbor/oracle.json` for the reference controller, or with +`-c configs/harbor/nop.json` for a valid unfinished-match failure. Neither calls +a model. A complete no-key match is a separate native regression, not the nop +agent (which exits without playing). diff --git a/game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/DIGEST b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/DIGEST new file mode 100644 index 0000000..8fbefd7 --- /dev/null +++ b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/DIGEST @@ -0,0 +1 @@ +sha256:dd33b6e8ab0dcacbb126fe6496c458ea9ab2e0330b6656b019c8e3c2f6e87f11 diff --git a/game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/README.md b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/README.md new file mode 100644 index 0000000..836e601 --- /dev/null +++ b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/README.md @@ -0,0 +1,40 @@ +# fightingice-zen-kick-p1-i01-standard + +| | | +|---|---| +| Benchmark | FightingICE | +| Mode | standard (`game-standard/2.2`) | +| Twin | — (none: native match is isolated; no privileged replay task is implemented) | +| Simulator / robot | `fightingice` / `game-agent` | +| Family / instance | `zen-kick` / seed 0 | +| Oracle | `full` | +| Agent time budget | 600 s; tokens: protocol default (docs/protocol/running.md "Official runs") | +| Base image | `docker.io/library/python:3.12.10-slim-bookworm@sha256:fd95fa221297a88e1cf49c55ec1828edd7c5a428187e67b5d1805692d11588db` | + +## Task +Control P1 ZEN against the frozen KickAI in one native three-round match. The +profile is delayed structured FrameData. No reset, no wall-clock realtime. +Versioned conditions and differences are in the benchmark README. + +## Difficulty +Minimal native combat and program-control smoke coverage, not tournament difficulty. + +## Reference solution +The offline controller wins the three native rounds by remaining outside the +opponent's short attack range. It is confined to solution/, not the agent image. + +## Verification +The separate verifier checks trusted native rounds, fixed-denominator score, +ending flags and action counts. Internal frame hashes and the audit transcript +are not public observations. The transcript is not a native gameplay recording. + +## Resources +Caps per container (PROTOCOL §6). + +| Container | CPUs | Memory | Processes | GPU memory | Disk | +|---|---|---|---|---|---| +| `main` (the agent's) | 1 | 1 GiB | 256 | no GPU | 2 GiB | +| `sim` | 1 | 1 GiB | 128 | no GPU | — | +| verifier (as `main`) | 1 | 1 GiB | no cap | no GPU | 2 GiB | + +- GPU: not needed. diff --git a/game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/environment/Dockerfile b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/environment/Dockerfile new file mode 100644 index 0000000..07818c0 --- /dev/null +++ b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/environment/Dockerfile @@ -0,0 +1,11 @@ +FROM docker.io/library/python:3.12.10-slim-bookworm@sha256:fd95fa221297a88e1cf49c55ec1828edd7c5a428187e67b5d1805692d11588db +RUN python3 -c "from pathlib import Path; p = Path('/etc/apt/sources.list.d/debian.sources'); p.write_text(p.read_text().replace('http://deb.debian.org', 'https://deb.debian.org'))" \ + && apt-get -o Acquire::Retries=3 -o Acquire::https::Timeout=30 update \ + && apt-get -o Acquire::Retries=3 -o Acquire::https::Timeout=30 install -y --no-install-recommends bash curl git nodejs npm ca-certificates \ + && rm -rf /var/lib/apt/lists/* +RUN npm install -g @openai/codex@0.167.1 && npm cache clean --force +COPY --from=ghcr.io/mll-lab-nu/efe:game-files-0.6.0@sha256:bfb708928954d5cc194a614ab772a65b1e56f381b49dfeb2227c3d609e5f2ecc /game_client.py /app/game_client.py +COPY --from=ghcr.io/mll-lab-nu/efe:connection-files-0.1.0@sha256:6d1002dea6ca507b4148d3196e233838e645b33bcfa9a27ae4a43027ae519999 /service_connection.py /app/service_connection.py +ENV PYTHONUNBUFFERED=1 PYTHONPATH=/app +RUN mkdir -p /app/output +WORKDIR /app diff --git a/game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/environment/docker-compose.yaml b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/environment/docker-compose.yaml new file mode 100644 index 0000000..2709827 --- /dev/null +++ b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/environment/docker-compose.yaml @@ -0,0 +1,44 @@ +services: + main: + pids_limit: 256 # rcb-monitor + volumes: # rcb-monitor + - rcb_limits:/run/rcb-limits:ro # rcb-monitor + depends_on: [sim] + sim: + cpus: 1 # rcb-monitor + mem_limit: 1024m # rcb-monitor + pids_limit: 128 # rcb-monitor + volumes: # rcb-monitor + - rcb_observe:/run/rcb-observe:ro # rcb-monitor + build: + context: sim + dockerfile: Dockerfile + working_dir: /srv + command: python3 /srv/server.py + environment: + RCB_WALL_CLOCK_S: "600" + SERVER_HOST: "127.0.0.1" + # >>> rcb_monitor (resource monitor, PROTOCOL §6; generated by images/monitor/rcb_monitor/inject.py) + rcb_monitor: + image: ghcr.io/mll-lab-nu/efe:monitor-0.5.0@sha256:ecc5f24f1516ca11711d7c2d3ac07c89f79cd9220812c1244498ec71e352402a + pid: host + cgroup: host + network_mode: none + cap_add: [SYS_PTRACE] + cpus: 0.5 + mem_limit: 256m + pids_limit: 64 + restart: on-failure + working_dir: /var/rcb-monitor + volumes: + - ./rcb_monitor/limits.json:/opt/rcb_monitor/limits.json:ro + - rcb_limits:/run/rcb-limits + - rcb_observe:/run/rcb-observe + environment: + RCB_LIMITS_ENFORCE: ${RCB_LIMITS_ENFORCE:-0} + RCB_LIMITS_TOLERANCE: ${RCB_LIMITS_TOLERANCE:-0.05} + command: ["python3", "/opt/rcb_monitor/monitor.py", "run"] + # <<< rcb_monitor +volumes: # rcb-monitor + rcb_limits: # rcb-monitor + rcb_observe: # rcb-monitor diff --git a/game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/environment/rcb_monitor/limits.json b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/environment/rcb_monitor/limits.json new file mode 100644 index 0000000..490c5fa --- /dev/null +++ b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/environment/rcb_monitor/limits.json @@ -0,0 +1,26 @@ +{ + "agent_timeout_sec": 600, + "caps": { + "main": { + "cpus": 1.0, + "disk_gb": 2.0, + "memory_gb": 1.0, + "pids": 256 + }, + "sim": { + "cpus": 1.0, + "memory_gb": 1.0, + "pids": 128 + } + }, + "disk_gb": 2.0, + "disk_tick_sec": 60, + "format": "rcb-limits/2", + "gpu": false, + "mode": "standard", + "scope_services": [ + "main" + ], + "task": "fightingice-zen-kick-p1-i01-standard", + "tick_sec": 5 +} diff --git a/game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/environment/sim/Dockerfile b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/environment/sim/Dockerfile new file mode 100644 index 0000000..12749e0 --- /dev/null +++ b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/environment/sim/Dockerfile @@ -0,0 +1,14 @@ +FROM docker.io/library/python:3.12.10-slim-bookworm@sha256:fd95fa221297a88e1cf49c55ec1828edd7c5a428187e67b5d1805692d11588db +RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates fontconfig libstdc++6 && rm -rf /var/lib/apt/lists/* +ADD --checksum=sha256:51141204fe01a9f9dd74eab621d5eca7511eac67315c9975dbde5f2625bdca55 https://github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.2%2B13/OpenJDK21U-jre_x64_linux_hotspot_21.0.2_13.tar.gz /tmp/java.tar.gz +RUN mkdir /opt/java && tar -xzf /tmp/java.tar.gz -C /opt/java --strip-components=1 && rm /tmp/java.tar.gz +ENV JAVA_HOME=/opt/java PATH=/opt/java/bin:$PATH FIGHTINGICE_HOME=/opt/fightingice PYTHONUNBUFFERED=1 SERVER_HOST=127.0.0.1 +COPY --from=ghcr.io/mll-lab-nu/efe:fightingice-files-0.1.0@sha256:20832c27e23b258cb2a489c6614e531e35b535d83c662bb5e99ab2db47830e71 /requirements.txt /srv/requirements.txt +RUN pip install --no-cache-dir --no-deps -r /srv/requirements.txt && pip check +COPY --from=ghcr.io/mll-lab-nu/efe:fightingice-files-0.1.0@sha256:20832c27e23b258cb2a489c6614e531e35b535d83c662bb5e99ab2db47830e71 /install_native.py /SOURCE.json /LICENSE-pyftg /srv/ +RUN python3 /srv/install_native.py /opt/fightingice +COPY --from=ghcr.io/mll-lab-nu/efe:game-files-0.6.0@sha256:bfb708928954d5cc194a614ab772a65b1e56f381b49dfeb2227c3d609e5f2ecc /server.py /contracts.py /config_schema.py /reducers.py /encoding.py /recording.py /srv/ +COPY --from=ghcr.io/mll-lab-nu/efe:fightingice-files-0.1.0@sha256:20832c27e23b258cb2a489c6614e531e35b535d83c662bb5e99ab2db47830e71 /adapter.py /bridge.py /instance_schema.py /srv/ +COPY instance.json /srv/instance.json +WORKDIR /srv +CMD ["python3", "/srv/server.py"] diff --git a/game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/environment/sim/instance.json b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/environment/sim/instance.json new file mode 100644 index 0000000..8afe063 --- /dev/null +++ b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/environment/sim/instance.json @@ -0,0 +1,32 @@ +{ + "schema_version": "game-instance/2.2", + "protocol": "game-standard/2.2", + "adapter_version": "1.0.0", + "capabilities": { + "images": false, + "action_mode": "enum", + "timing": "action-stepped", + "native_truncation": false + }, + "benchmark": "fightingice", + "env_id": "DareFightingICE-ZEN-KickAI-v7.0", + "family": "zen-kick", + "seed": 0, + "max_steps": null, + "initial_state_sha256": "d7a1da601ec87b08cd36a1c994d836bf71f85661fdc091ad0389459acfed116a", + "observation_profile": "native-delayed-framedata-v1", + "metric_spec": { + "primary": "round_win_score", + "reducer": "family_macro", + "reducer_version": "1.0.0", + "success_label": "match_won" + }, + "engine_versions": {"fightingice": "7.0", "pyftg": "2.3"}, + "player": 0, + "characters": ["ZEN", "ZEN"], + "opponent": "pyftg-kick-b-v1", + "rounds": 3, + "round_frames": 3600, + "initial_hp": 400, + "native_seed_policy": "no-native-seed;deterministic-opponent" +} diff --git a/game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/instruction.md b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/instruction.md new file mode 100644 index 0000000..dadb7a3 --- /dev/null +++ b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/instruction.md @@ -0,0 +1,80 @@ +# FightingICE: ZEN versus KickAI + +You control P1 ZEN in a two-player fighting game. The other player is controlled +by a fixed opponent. Use the Python client to observe the fight and execute +directional and attack inputs. Play one match of three rounds. + +## Rules +- Write and run a controller using the public client. Your program may execute many actions in a loop, and you may inspect feedback and revise it during the same match. Keep your main controller at `/app/output/gen.py`. +- There is no reset, undo, character change or second match. Automatic resets between rounds are part of the game. Stop sending actions when `done` is true. +- Use only the observations returned by the client. Do not connect to internal game interfaces or read hidden state. +- The game waits between actions. Each accepted key combination advances one native input frame. A round ends at a KO or after 3600 native frames. Each player starts each round with 400 HP. +- Observations are returned to your program; print or inspect the parts you need. They are not automatically displayed to the model. + +## Scoring +Each native round is won by the player with greater remaining HP; equal HP is +a draw. You earn `100 * rounds_won / 3` points. Draws and unfinished rounds give +no win credit. Winning the match requires completing all three rounds with +more wins than losses. `done` can also mean that a budget or agent session ended. + +## Client +```python +from game_client import GameClient + +game = GameClient() +spec = game.spec() +print(spec["action_schema"]["enum"]) # legal strings: noop, A, B, ..., BDR, ... +print(spec["native_action_ids"]) # numeric action IDs in FrameData +print(spec["native_state_ids"]) # numeric state IDs in FrameData +reply = game.observe() # read without advancing the fight +data = reply["observation"] +player = data["player"] # 0 for P1, 1 for P2 +frame = data["frame_data"] +if not frame["empty_flag"]: + me, opponent = frame["character_data"][player], frame["character_data"][1-player] + print(me["hp"], me["x"], opponent["hp"], opponent["x"]) +if not reply["done"]: + reply = game.step("noop", expected_step=reply["step"]) # release every key for one frame + print(reply["step"], reply["done"]) +``` + +### Observations +`frame_data` is the native delayed structured observation, not a screenshot. +It contains `empty_flag`, `current_frame_number`, `current_round`, `front`, +`character_data` and `projectile_data`. The two character entries are always +ordered P1 then P2. Positions use native stage coordinates: x increases right, +y increases down. The stage is 960 by 640. + +Character entries include HP, energy, position/bounds, velocity, numeric action +and state, facing direction, remaining action frames and native attack data. +`spec()` supplies the numeric ID tables and static `game_data`. `is_control` +is the native callback flag indicating whether your character can be controlled. +The nominal FrameData delay is 15 frames. At round starts, empty observations +have no character entries; check `empty_flag` before indexing. The callback's +own control flag need not refer to the delayed observation's frame. + +### Actions and feedback +`A`, `B`, `C` are attack buttons; `D`, `L`, `R`, `U` are down, left, right and up. +Combine letters once each, in the order `ABCDLRU`, to hold them simultaneously +for one input frame. For example, `AR` means right and A; `noop` releases all +keys. Directions are absolute, not relative to facing. Native input recognition +determines which move executes; sending a key does not guarantee an attack. + +`step()` returns the same snapshot fields as `observe()`: `step`, `done`, +`observation`, `steps_remaining` and `time_left_s`. `step` counts accepted input +frames across the match; the delayed native frame counter restarts each round. +`steps_remaining` is null because only the native round limits apply. Invalid +keys and stale step numbers raise `ValueError` without advancing. If a reply is +lost, read the current observation before selecting the next action. + +## External material +You may install packages and use public tools. Note external resources used. +Do not obtain a ready-made solution to this exact task. Network access is open. + +## Resources +Your container: **1 CPUs**, **1 GiB of memory**, **256 processes and threads** and **2 GiB** of disk (new files under `/app`, `/tmp` and `/root`). Your container has no GPU. The simulator runs in its own container and does not count against these. CPU only slows you down; a process that goes over any other cap can be killed. Usage and caps: `/run/rcb-limits/usage.json`. + +## Time limit +You have 600 seconds to complete this task. Do not cheat by using online solutions or hints specific to this task. + +The wall-clock budget starts with your session and includes service startup, waiting and tool execution. At the cutoff, the episode is graded as it stands. Use `deadline_utc` and `time_left_s` in `/run/rcb-limits/usage.json` to plan around the agent deadline. The client's `time_left_s` counts from the first `observe()` or accepted action, whichever comes first. `spec()` does not start that clock. diff --git a/game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/solution/control.py b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/solution/control.py new file mode 100644 index 0000000..3a65214 --- /dev/null +++ b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/solution/control.py @@ -0,0 +1,18 @@ +"""Offline smoke reference; excluded from the agent image.""" +def choose(observation): + frame = observation['frame_data'] + if frame['empty_flag']: + return 'noop' + player = observation['player'] + me, other = frame['character_data'][player], frame['character_data'][1-player] + forward = 'R' if me['x'] < other['x'] else 'L' + return forward if abs(me['x']-other['x']) > 260 else 'BD' + forward + + +if __name__ == '__main__': + from game_client import GameClient + client = GameClient() + reply = client.observe() + while not reply['done']: + reply = client.step(choose(reply['observation']), reply['step']) + print('Match completed:', reply['step'], 'input frames') diff --git a/game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/solution/solve.sh b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/solution/solve.sh new file mode 100755 index 0000000..4cda490 --- /dev/null +++ b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -euo pipefail +cp /solution/control.py /app/output/gen.py +python3 /app/output/gen.py diff --git a/game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/task.toml b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/task.toml new file mode 100644 index 0000000..44535c0 --- /dev/null +++ b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/task.toml @@ -0,0 +1,58 @@ +schema_version = "1.3" +artifacts = [{ source = "/var/rcb-monitor/", service = "rcb_monitor" }, { source = "/data/final.json", service = "sim" }, + { source = "/data/episode.jsonl", service = "sim" }, + { source = "/data/recording.json", service = "sim" }, + { source = "/data/replay.mp4", service = "sim" }, + { source = "/data/replay.last.png", service = "sim" }, + "/app/output/", +] + +[task] +name = "embodied-first-exam/fightingice-zen-kick-p1-i01-standard" +description = "Control P1 ZEN in one native three-round FightingICE match." +keywords = ["game", "fightingice", "combat", "standard-mode"] + +[metadata] +task_type = "trajectory" +simulator = "fightingice" +robot = "game-agent" +family = "zen-kick" +dynamics = "dynamic" +protocol = "game-standard/2.2" +oracle = "full" +instance_seed = 0 +expert_time_estimate_hours = 0.5 + +[verifier] +timeout_sec = 120.0 +environment_mode = "separate" +network_mode = "no-network" + +# Resources (PROTOCOL §6): seal the monitor's record first. +[[verifier.collect]] +service = "rcb_monitor" +command = "python3 /opt/rcb_monitor/monitor.py seal --wait 90" +timeout_sec = 120 + +[[verifier.collect]] +service = "main" +command = "kill -9 -1 2>/dev/null; exit 0" +timeout_sec = 30 + +[[verifier.collect]] +service = "sim" +command = "kill -USR1 $(cat /data/server.pid); i=0; while [ ! -f /data/collection.ready ] && [ $i -lt 30 ]; do sleep 1; i=$((i+1)); done; test -f /data/collection.ready && test -f /data/final.json" +timeout_sec = 40 + +[agent] +timeout_sec = 600.0 +network_mode = "public" + +[environment] +build_timeout_sec = 1800.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 + +[verifier.env] +RCB_LIMITS_ENFORCE = "${RCB_LIMITS_ENFORCE:-0}" diff --git a/game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/tests/Dockerfile b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/tests/Dockerfile new file mode 100644 index 0000000..56b5240 --- /dev/null +++ b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/tests/Dockerfile @@ -0,0 +1,8 @@ +FROM docker.io/library/python:3.12.10-slim-bookworm@sha256:fd95fa221297a88e1cf49c55ec1828edd7c5a428187e67b5d1805692d11588db +COPY test.sh instance.json /tests/ +COPY --from=ghcr.io/mll-lab-nu/efe:game-files-0.6.0@sha256:bfb708928954d5cc194a614ab772a65b1e56f381b49dfeb2227c3d609e5f2ecc /grade.py /config_schema.py /reducers.py /tests/ +COPY --from=ghcr.io/mll-lab-nu/efe:fightingice-files-0.1.0@sha256:20832c27e23b258cb2a489c6614e531e35b535d83c662bb5e99ab2db47830e71 /instance_schema.py /metric_rules.py /tests/ +RUN chmod +x /tests/test.sh +# resources (PROTOCOL §6) # rcb-monitor +COPY --from=ghcr.io/mll-lab-nu/efe:monitor-0.5.0@sha256:ecc5f24f1516ca11711d7c2d3ac07c89f79cd9220812c1244498ec71e352402a /opt/rcb_monitor/rcb_limits.py /tests/rcb_limits.py +COPY rcb_limits.json /tests/rcb_limits.json diff --git a/game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/tests/instance.json b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/tests/instance.json new file mode 100644 index 0000000..8afe063 --- /dev/null +++ b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/tests/instance.json @@ -0,0 +1,32 @@ +{ + "schema_version": "game-instance/2.2", + "protocol": "game-standard/2.2", + "adapter_version": "1.0.0", + "capabilities": { + "images": false, + "action_mode": "enum", + "timing": "action-stepped", + "native_truncation": false + }, + "benchmark": "fightingice", + "env_id": "DareFightingICE-ZEN-KickAI-v7.0", + "family": "zen-kick", + "seed": 0, + "max_steps": null, + "initial_state_sha256": "d7a1da601ec87b08cd36a1c994d836bf71f85661fdc091ad0389459acfed116a", + "observation_profile": "native-delayed-framedata-v1", + "metric_spec": { + "primary": "round_win_score", + "reducer": "family_macro", + "reducer_version": "1.0.0", + "success_label": "match_won" + }, + "engine_versions": {"fightingice": "7.0", "pyftg": "2.3"}, + "player": 0, + "characters": ["ZEN", "ZEN"], + "opponent": "pyftg-kick-b-v1", + "rounds": 3, + "round_frames": 3600, + "initial_hp": 400, + "native_seed_policy": "no-native-seed;deterministic-opponent" +} diff --git a/game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/tests/rcb_limits.json b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/tests/rcb_limits.json new file mode 100644 index 0000000..490c5fa --- /dev/null +++ b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/tests/rcb_limits.json @@ -0,0 +1,26 @@ +{ + "agent_timeout_sec": 600, + "caps": { + "main": { + "cpus": 1.0, + "disk_gb": 2.0, + "memory_gb": 1.0, + "pids": 256 + }, + "sim": { + "cpus": 1.0, + "memory_gb": 1.0, + "pids": 128 + } + }, + "disk_gb": 2.0, + "disk_tick_sec": 60, + "format": "rcb-limits/2", + "gpu": false, + "mode": "standard", + "scope_services": [ + "main" + ], + "task": "fightingice-zen-kick-p1-i01-standard", + "tick_sec": 5 +} diff --git a/game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/tests/test.sh b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/tests/test.sh new file mode 100755 index 0000000..0cf878a --- /dev/null +++ b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p1-i01-standard/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +rm -rf /logs/verifier/* +trap 'p=$(command -v python3 || command -v python); "$p" /tests/rcb_limits.py verify' EXIT # resources, after the grader (PROTOCOL §6) +p=$(command -v python3 || command -v python); "$p" /tests/rcb_limits.py sanitize /app/output || true # untrusted agent files (PROTOCOL H.1) +mkdir -p /logs/verifier +python3 /tests/grade.py 2>/logs/verifier/grade.log diff --git a/game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/DIGEST b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/DIGEST new file mode 100644 index 0000000..ba328ef --- /dev/null +++ b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/DIGEST @@ -0,0 +1 @@ +sha256:475414f6ac4af2d3969520f68deaead27f3f228fd75e63d28e1ed334fe6907dd diff --git a/game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/README.md b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/README.md new file mode 100644 index 0000000..03eaa36 --- /dev/null +++ b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/README.md @@ -0,0 +1,40 @@ +# fightingice-zen-kick-p2-i01-standard + +| | | +|---|---| +| Benchmark | FightingICE | +| Mode | standard (`game-standard/2.2`) | +| Twin | — (none: native match is isolated; no privileged replay task is implemented) | +| Simulator / robot | `fightingice` / `game-agent` | +| Family / instance | `zen-kick` / seed 0 | +| Oracle | `full` | +| Agent time budget | 600 s; tokens: protocol default (docs/protocol/running.md "Official runs") | +| Base image | `docker.io/library/python:3.12.10-slim-bookworm@sha256:fd95fa221297a88e1cf49c55ec1828edd7c5a428187e67b5d1805692d11588db` | + +## Task +Control P2 ZEN against the frozen KickAI in one native three-round match. The +profile is delayed structured FrameData. No reset, no wall-clock realtime. +Versioned conditions and differences are in the benchmark README. + +## Difficulty +Minimal native combat and program-control smoke coverage, not tournament difficulty. + +## Reference solution +The offline controller wins the three native rounds by remaining outside the +opponent's short attack range. It is confined to solution/, not the agent image. + +## Verification +The separate verifier checks trusted native rounds, fixed-denominator score, +ending flags and action counts. Internal frame hashes and the audit transcript +are not public observations. The transcript is not a native gameplay recording. + +## Resources +Caps per container (PROTOCOL §6). + +| Container | CPUs | Memory | Processes | GPU memory | Disk | +|---|---|---|---|---|---| +| `main` (the agent's) | 1 | 1 GiB | 256 | no GPU | 2 GiB | +| `sim` | 1 | 1 GiB | 128 | no GPU | — | +| verifier (as `main`) | 1 | 1 GiB | no cap | no GPU | 2 GiB | + +- GPU: not needed. diff --git a/game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/environment/Dockerfile b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/environment/Dockerfile new file mode 100644 index 0000000..07818c0 --- /dev/null +++ b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/environment/Dockerfile @@ -0,0 +1,11 @@ +FROM docker.io/library/python:3.12.10-slim-bookworm@sha256:fd95fa221297a88e1cf49c55ec1828edd7c5a428187e67b5d1805692d11588db +RUN python3 -c "from pathlib import Path; p = Path('/etc/apt/sources.list.d/debian.sources'); p.write_text(p.read_text().replace('http://deb.debian.org', 'https://deb.debian.org'))" \ + && apt-get -o Acquire::Retries=3 -o Acquire::https::Timeout=30 update \ + && apt-get -o Acquire::Retries=3 -o Acquire::https::Timeout=30 install -y --no-install-recommends bash curl git nodejs npm ca-certificates \ + && rm -rf /var/lib/apt/lists/* +RUN npm install -g @openai/codex@0.167.1 && npm cache clean --force +COPY --from=ghcr.io/mll-lab-nu/efe:game-files-0.6.0@sha256:bfb708928954d5cc194a614ab772a65b1e56f381b49dfeb2227c3d609e5f2ecc /game_client.py /app/game_client.py +COPY --from=ghcr.io/mll-lab-nu/efe:connection-files-0.1.0@sha256:6d1002dea6ca507b4148d3196e233838e645b33bcfa9a27ae4a43027ae519999 /service_connection.py /app/service_connection.py +ENV PYTHONUNBUFFERED=1 PYTHONPATH=/app +RUN mkdir -p /app/output +WORKDIR /app diff --git a/game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/environment/docker-compose.yaml b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/environment/docker-compose.yaml new file mode 100644 index 0000000..2709827 --- /dev/null +++ b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/environment/docker-compose.yaml @@ -0,0 +1,44 @@ +services: + main: + pids_limit: 256 # rcb-monitor + volumes: # rcb-monitor + - rcb_limits:/run/rcb-limits:ro # rcb-monitor + depends_on: [sim] + sim: + cpus: 1 # rcb-monitor + mem_limit: 1024m # rcb-monitor + pids_limit: 128 # rcb-monitor + volumes: # rcb-monitor + - rcb_observe:/run/rcb-observe:ro # rcb-monitor + build: + context: sim + dockerfile: Dockerfile + working_dir: /srv + command: python3 /srv/server.py + environment: + RCB_WALL_CLOCK_S: "600" + SERVER_HOST: "127.0.0.1" + # >>> rcb_monitor (resource monitor, PROTOCOL §6; generated by images/monitor/rcb_monitor/inject.py) + rcb_monitor: + image: ghcr.io/mll-lab-nu/efe:monitor-0.5.0@sha256:ecc5f24f1516ca11711d7c2d3ac07c89f79cd9220812c1244498ec71e352402a + pid: host + cgroup: host + network_mode: none + cap_add: [SYS_PTRACE] + cpus: 0.5 + mem_limit: 256m + pids_limit: 64 + restart: on-failure + working_dir: /var/rcb-monitor + volumes: + - ./rcb_monitor/limits.json:/opt/rcb_monitor/limits.json:ro + - rcb_limits:/run/rcb-limits + - rcb_observe:/run/rcb-observe + environment: + RCB_LIMITS_ENFORCE: ${RCB_LIMITS_ENFORCE:-0} + RCB_LIMITS_TOLERANCE: ${RCB_LIMITS_TOLERANCE:-0.05} + command: ["python3", "/opt/rcb_monitor/monitor.py", "run"] + # <<< rcb_monitor +volumes: # rcb-monitor + rcb_limits: # rcb-monitor + rcb_observe: # rcb-monitor diff --git a/game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/environment/rcb_monitor/limits.json b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/environment/rcb_monitor/limits.json new file mode 100644 index 0000000..e05de2d --- /dev/null +++ b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/environment/rcb_monitor/limits.json @@ -0,0 +1,26 @@ +{ + "agent_timeout_sec": 600, + "caps": { + "main": { + "cpus": 1.0, + "disk_gb": 2.0, + "memory_gb": 1.0, + "pids": 256 + }, + "sim": { + "cpus": 1.0, + "memory_gb": 1.0, + "pids": 128 + } + }, + "disk_gb": 2.0, + "disk_tick_sec": 60, + "format": "rcb-limits/2", + "gpu": false, + "mode": "standard", + "scope_services": [ + "main" + ], + "task": "fightingice-zen-kick-p2-i01-standard", + "tick_sec": 5 +} diff --git a/game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/environment/sim/Dockerfile b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/environment/sim/Dockerfile new file mode 100644 index 0000000..12749e0 --- /dev/null +++ b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/environment/sim/Dockerfile @@ -0,0 +1,14 @@ +FROM docker.io/library/python:3.12.10-slim-bookworm@sha256:fd95fa221297a88e1cf49c55ec1828edd7c5a428187e67b5d1805692d11588db +RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates fontconfig libstdc++6 && rm -rf /var/lib/apt/lists/* +ADD --checksum=sha256:51141204fe01a9f9dd74eab621d5eca7511eac67315c9975dbde5f2625bdca55 https://github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.2%2B13/OpenJDK21U-jre_x64_linux_hotspot_21.0.2_13.tar.gz /tmp/java.tar.gz +RUN mkdir /opt/java && tar -xzf /tmp/java.tar.gz -C /opt/java --strip-components=1 && rm /tmp/java.tar.gz +ENV JAVA_HOME=/opt/java PATH=/opt/java/bin:$PATH FIGHTINGICE_HOME=/opt/fightingice PYTHONUNBUFFERED=1 SERVER_HOST=127.0.0.1 +COPY --from=ghcr.io/mll-lab-nu/efe:fightingice-files-0.1.0@sha256:20832c27e23b258cb2a489c6614e531e35b535d83c662bb5e99ab2db47830e71 /requirements.txt /srv/requirements.txt +RUN pip install --no-cache-dir --no-deps -r /srv/requirements.txt && pip check +COPY --from=ghcr.io/mll-lab-nu/efe:fightingice-files-0.1.0@sha256:20832c27e23b258cb2a489c6614e531e35b535d83c662bb5e99ab2db47830e71 /install_native.py /SOURCE.json /LICENSE-pyftg /srv/ +RUN python3 /srv/install_native.py /opt/fightingice +COPY --from=ghcr.io/mll-lab-nu/efe:game-files-0.6.0@sha256:bfb708928954d5cc194a614ab772a65b1e56f381b49dfeb2227c3d609e5f2ecc /server.py /contracts.py /config_schema.py /reducers.py /encoding.py /recording.py /srv/ +COPY --from=ghcr.io/mll-lab-nu/efe:fightingice-files-0.1.0@sha256:20832c27e23b258cb2a489c6614e531e35b535d83c662bb5e99ab2db47830e71 /adapter.py /bridge.py /instance_schema.py /srv/ +COPY instance.json /srv/instance.json +WORKDIR /srv +CMD ["python3", "/srv/server.py"] diff --git a/game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/environment/sim/instance.json b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/environment/sim/instance.json new file mode 100644 index 0000000..852ded4 --- /dev/null +++ b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/environment/sim/instance.json @@ -0,0 +1,32 @@ +{ + "schema_version": "game-instance/2.2", + "protocol": "game-standard/2.2", + "adapter_version": "1.0.0", + "capabilities": { + "images": false, + "action_mode": "enum", + "timing": "action-stepped", + "native_truncation": false + }, + "benchmark": "fightingice", + "env_id": "DareFightingICE-ZEN-KickAI-v7.0", + "family": "zen-kick", + "seed": 0, + "max_steps": null, + "initial_state_sha256": "ee2eec694cae65c044567771ceb256357c5c10111e9338abbe91ad4799415146", + "observation_profile": "native-delayed-framedata-v1", + "metric_spec": { + "primary": "round_win_score", + "reducer": "family_macro", + "reducer_version": "1.0.0", + "success_label": "match_won" + }, + "engine_versions": {"fightingice": "7.0", "pyftg": "2.3"}, + "player": 1, + "characters": ["ZEN", "ZEN"], + "opponent": "pyftg-kick-b-v1", + "rounds": 3, + "round_frames": 3600, + "initial_hp": 400, + "native_seed_policy": "no-native-seed;deterministic-opponent" +} diff --git a/game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/instruction.md b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/instruction.md new file mode 100644 index 0000000..566c073 --- /dev/null +++ b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/instruction.md @@ -0,0 +1,80 @@ +# FightingICE: ZEN versus KickAI + +You control P2 ZEN in a two-player fighting game. The other player is controlled +by a fixed opponent. Use the Python client to observe the fight and execute +directional and attack inputs. Play one match of three rounds. + +## Rules +- Write and run a controller using the public client. Your program may execute many actions in a loop, and you may inspect feedback and revise it during the same match. Keep your main controller at `/app/output/gen.py`. +- There is no reset, undo, character change or second match. Automatic resets between rounds are part of the game. Stop sending actions when `done` is true. +- Use only the observations returned by the client. Do not connect to internal game interfaces or read hidden state. +- The game waits between actions. Each accepted key combination advances one native input frame. A round ends at a KO or after 3600 native frames. Each player starts each round with 400 HP. +- Observations are returned to your program; print or inspect the parts you need. They are not automatically displayed to the model. + +## Scoring +Each native round is won by the player with greater remaining HP; equal HP is +a draw. You earn `100 * rounds_won / 3` points. Draws and unfinished rounds give +no win credit. Winning the match requires completing all three rounds with +more wins than losses. `done` can also mean that a budget or agent session ended. + +## Client +```python +from game_client import GameClient + +game = GameClient() +spec = game.spec() +print(spec["action_schema"]["enum"]) # legal strings: noop, A, B, ..., BDR, ... +print(spec["native_action_ids"]) # numeric action IDs in FrameData +print(spec["native_state_ids"]) # numeric state IDs in FrameData +reply = game.observe() # read without advancing the fight +data = reply["observation"] +player = data["player"] # 0 for P1, 1 for P2 +frame = data["frame_data"] +if not frame["empty_flag"]: + me, opponent = frame["character_data"][player], frame["character_data"][1-player] + print(me["hp"], me["x"], opponent["hp"], opponent["x"]) +if not reply["done"]: + reply = game.step("noop", expected_step=reply["step"]) # release every key for one frame + print(reply["step"], reply["done"]) +``` + +### Observations +`frame_data` is the native delayed structured observation, not a screenshot. +It contains `empty_flag`, `current_frame_number`, `current_round`, `front`, +`character_data` and `projectile_data`. The two character entries are always +ordered P1 then P2. Positions use native stage coordinates: x increases right, +y increases down. The stage is 960 by 640. + +Character entries include HP, energy, position/bounds, velocity, numeric action +and state, facing direction, remaining action frames and native attack data. +`spec()` supplies the numeric ID tables and static `game_data`. `is_control` +is the native callback flag indicating whether your character can be controlled. +The nominal FrameData delay is 15 frames. At round starts, empty observations +have no character entries; check `empty_flag` before indexing. The callback's +own control flag need not refer to the delayed observation's frame. + +### Actions and feedback +`A`, `B`, `C` are attack buttons; `D`, `L`, `R`, `U` are down, left, right and up. +Combine letters once each, in the order `ABCDLRU`, to hold them simultaneously +for one input frame. For example, `AR` means right and A; `noop` releases all +keys. Directions are absolute, not relative to facing. Native input recognition +determines which move executes; sending a key does not guarantee an attack. + +`step()` returns the same snapshot fields as `observe()`: `step`, `done`, +`observation`, `steps_remaining` and `time_left_s`. `step` counts accepted input +frames across the match; the delayed native frame counter restarts each round. +`steps_remaining` is null because only the native round limits apply. Invalid +keys and stale step numbers raise `ValueError` without advancing. If a reply is +lost, read the current observation before selecting the next action. + +## External material +You may install packages and use public tools. Note external resources used. +Do not obtain a ready-made solution to this exact task. Network access is open. + +## Resources +Your container: **1 CPUs**, **1 GiB of memory**, **256 processes and threads** and **2 GiB** of disk (new files under `/app`, `/tmp` and `/root`). Your container has no GPU. The simulator runs in its own container and does not count against these. CPU only slows you down; a process that goes over any other cap can be killed. Usage and caps: `/run/rcb-limits/usage.json`. + +## Time limit +You have 600 seconds to complete this task. Do not cheat by using online solutions or hints specific to this task. + +The wall-clock budget starts with your session and includes service startup, waiting and tool execution. At the cutoff, the episode is graded as it stands. Use `deadline_utc` and `time_left_s` in `/run/rcb-limits/usage.json` to plan around the agent deadline. The client's `time_left_s` counts from the first `observe()` or accepted action, whichever comes first. `spec()` does not start that clock. diff --git a/game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/solution/control.py b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/solution/control.py new file mode 100644 index 0000000..3a65214 --- /dev/null +++ b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/solution/control.py @@ -0,0 +1,18 @@ +"""Offline smoke reference; excluded from the agent image.""" +def choose(observation): + frame = observation['frame_data'] + if frame['empty_flag']: + return 'noop' + player = observation['player'] + me, other = frame['character_data'][player], frame['character_data'][1-player] + forward = 'R' if me['x'] < other['x'] else 'L' + return forward if abs(me['x']-other['x']) > 260 else 'BD' + forward + + +if __name__ == '__main__': + from game_client import GameClient + client = GameClient() + reply = client.observe() + while not reply['done']: + reply = client.step(choose(reply['observation']), reply['step']) + print('Match completed:', reply['step'], 'input frames') diff --git a/game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/solution/solve.sh b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/solution/solve.sh new file mode 100755 index 0000000..4cda490 --- /dev/null +++ b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -euo pipefail +cp /solution/control.py /app/output/gen.py +python3 /app/output/gen.py diff --git a/game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/task.toml b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/task.toml new file mode 100644 index 0000000..390d4ed --- /dev/null +++ b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/task.toml @@ -0,0 +1,58 @@ +schema_version = "1.3" +artifacts = [{ source = "/var/rcb-monitor/", service = "rcb_monitor" }, { source = "/data/final.json", service = "sim" }, + { source = "/data/episode.jsonl", service = "sim" }, + { source = "/data/recording.json", service = "sim" }, + { source = "/data/replay.mp4", service = "sim" }, + { source = "/data/replay.last.png", service = "sim" }, + "/app/output/", +] + +[task] +name = "embodied-first-exam/fightingice-zen-kick-p2-i01-standard" +description = "Control P2 ZEN in one native three-round FightingICE match." +keywords = ["game", "fightingice", "combat", "standard-mode"] + +[metadata] +task_type = "trajectory" +simulator = "fightingice" +robot = "game-agent" +family = "zen-kick" +dynamics = "dynamic" +protocol = "game-standard/2.2" +oracle = "full" +instance_seed = 0 +expert_time_estimate_hours = 0.5 + +[verifier] +timeout_sec = 120.0 +environment_mode = "separate" +network_mode = "no-network" + +# Resources (PROTOCOL §6): seal the monitor's record first. +[[verifier.collect]] +service = "rcb_monitor" +command = "python3 /opt/rcb_monitor/monitor.py seal --wait 90" +timeout_sec = 120 + +[[verifier.collect]] +service = "main" +command = "kill -9 -1 2>/dev/null; exit 0" +timeout_sec = 30 + +[[verifier.collect]] +service = "sim" +command = "kill -USR1 $(cat /data/server.pid); i=0; while [ ! -f /data/collection.ready ] && [ $i -lt 30 ]; do sleep 1; i=$((i+1)); done; test -f /data/collection.ready && test -f /data/final.json" +timeout_sec = 40 + +[agent] +timeout_sec = 600.0 +network_mode = "public" + +[environment] +build_timeout_sec = 1800.0 +cpus = 1 +memory_mb = 1024 +storage_mb = 2048 + +[verifier.env] +RCB_LIMITS_ENFORCE = "${RCB_LIMITS_ENFORCE:-0}" diff --git a/game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/tests/Dockerfile b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/tests/Dockerfile new file mode 100644 index 0000000..56b5240 --- /dev/null +++ b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/tests/Dockerfile @@ -0,0 +1,8 @@ +FROM docker.io/library/python:3.12.10-slim-bookworm@sha256:fd95fa221297a88e1cf49c55ec1828edd7c5a428187e67b5d1805692d11588db +COPY test.sh instance.json /tests/ +COPY --from=ghcr.io/mll-lab-nu/efe:game-files-0.6.0@sha256:bfb708928954d5cc194a614ab772a65b1e56f381b49dfeb2227c3d609e5f2ecc /grade.py /config_schema.py /reducers.py /tests/ +COPY --from=ghcr.io/mll-lab-nu/efe:fightingice-files-0.1.0@sha256:20832c27e23b258cb2a489c6614e531e35b535d83c662bb5e99ab2db47830e71 /instance_schema.py /metric_rules.py /tests/ +RUN chmod +x /tests/test.sh +# resources (PROTOCOL §6) # rcb-monitor +COPY --from=ghcr.io/mll-lab-nu/efe:monitor-0.5.0@sha256:ecc5f24f1516ca11711d7c2d3ac07c89f79cd9220812c1244498ec71e352402a /opt/rcb_monitor/rcb_limits.py /tests/rcb_limits.py +COPY rcb_limits.json /tests/rcb_limits.json diff --git a/game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/tests/instance.json b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/tests/instance.json new file mode 100644 index 0000000..852ded4 --- /dev/null +++ b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/tests/instance.json @@ -0,0 +1,32 @@ +{ + "schema_version": "game-instance/2.2", + "protocol": "game-standard/2.2", + "adapter_version": "1.0.0", + "capabilities": { + "images": false, + "action_mode": "enum", + "timing": "action-stepped", + "native_truncation": false + }, + "benchmark": "fightingice", + "env_id": "DareFightingICE-ZEN-KickAI-v7.0", + "family": "zen-kick", + "seed": 0, + "max_steps": null, + "initial_state_sha256": "ee2eec694cae65c044567771ceb256357c5c10111e9338abbe91ad4799415146", + "observation_profile": "native-delayed-framedata-v1", + "metric_spec": { + "primary": "round_win_score", + "reducer": "family_macro", + "reducer_version": "1.0.0", + "success_label": "match_won" + }, + "engine_versions": {"fightingice": "7.0", "pyftg": "2.3"}, + "player": 1, + "characters": ["ZEN", "ZEN"], + "opponent": "pyftg-kick-b-v1", + "rounds": 3, + "round_frames": 3600, + "initial_hp": 400, + "native_seed_policy": "no-native-seed;deterministic-opponent" +} diff --git a/game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/tests/rcb_limits.json b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/tests/rcb_limits.json new file mode 100644 index 0000000..e05de2d --- /dev/null +++ b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/tests/rcb_limits.json @@ -0,0 +1,26 @@ +{ + "agent_timeout_sec": 600, + "caps": { + "main": { + "cpus": 1.0, + "disk_gb": 2.0, + "memory_gb": 1.0, + "pids": 256 + }, + "sim": { + "cpus": 1.0, + "memory_gb": 1.0, + "pids": 128 + } + }, + "disk_gb": 2.0, + "disk_tick_sec": 60, + "format": "rcb-limits/2", + "gpu": false, + "mode": "standard", + "scope_services": [ + "main" + ], + "task": "fightingice-zen-kick-p2-i01-standard", + "tick_sec": 5 +} diff --git a/game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/tests/test.sh b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/tests/test.sh new file mode 100755 index 0000000..0cf878a --- /dev/null +++ b/game_first_exam/tasks/fightingice/fightingice-zen-kick-p2-i01-standard/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +rm -rf /logs/verifier/* +trap 'p=$(command -v python3 || command -v python); "$p" /tests/rcb_limits.py verify' EXIT # resources, after the grader (PROTOCOL §6) +p=$(command -v python3 || command -v python); "$p" /tests/rcb_limits.py sanitize /app/output || true # untrusted agent files (PROTOCOL H.1) +mkdir -p /logs/verifier +python3 /tests/grade.py 2>/logs/verifier/grade.log diff --git a/game_first_exam/tests/benchmarks/fightingice/exported.toml b/game_first_exam/tests/benchmarks/fightingice/exported.toml new file mode 100644 index 0000000..5f116e0 --- /dev/null +++ b/game_first_exam/tests/benchmarks/fightingice/exported.toml @@ -0,0 +1,12 @@ +[protocols] +standard = ["game-standard/2.2"] + +[[tasks]] +name = "fightingice-zen-kick-p1-i01-standard" +source_task = "DareFightingICE-ZEN-KickAI-v7.0" +protocol = "game-standard/2.2" + +[[tasks]] +name = "fightingice-zen-kick-p2-i01-standard" +source_task = "DareFightingICE-ZEN-KickAI-v7.0" +protocol = "game-standard/2.2" diff --git a/game_first_exam/tests/check_fightingice_result.py b/game_first_exam/tests/check_fightingice_result.py new file mode 100644 index 0000000..04648cc --- /dev/null +++ b/game_first_exam/tests/check_fightingice_result.py @@ -0,0 +1,59 @@ +"""Check a complete two-side Harbor smoke job; no model calls or Docker needed.""" +import argparse +import json +from pathlib import Path + + +def check(job, agent): + job = Path(job) + + def read(path): + return json.loads(path.read_text()) + + def require(condition, message): + if not condition: + raise ValueError(message) + + expected = {f'fightingice-zen-kick-p{side}-i01-standard' for side in (1, 2)} + results = sorted(job.glob('*/result.json')) + require(len(results) == 2, 'expected exactly two completed trials') + seen, rows = set(), [] + for path in results: + result = read(path) + name = result['task_name'].rsplit('/', 1)[-1] + require(name in expected and name not in seen, 'unknown or duplicate task') + seen.add(name) + require(result.get('exception_info') is None, f'{name}: Harbor exception') + require(result.get('agent_info', {}).get('name') == agent, f'{name}: unexpected agent') + trial = path.parent + reward = read(trial / 'verifier/reward.json') + require(reward.get('result_valid') == 1, f'{name}: invalid verifier result') + for field in ('infra_error', 'sim_error', 'environment_error'): + require(reward.get(field) == 0, f'{name}: {field}') + score, steps = (100, 10800) if agent == 'oracle' else (0, 0) + require(reward.get('primary_score') == score, f'{name}: unexpected score') + require(reward.get('success') == int(agent == 'oracle'), f'{name}: unexpected success') + final = read(trial / 'artifacts/data/final.json') + require(final['steps'] == reward['steps'] == steps, f'{name}: input count changed') + require(final['terminated'] == (agent == 'oracle') and not final['truncated'], f'{name}: ending flags') + require(final['reason'] == ('native_terminated' if agent == 'oracle' else 'agent_finished'), f'{name}: ending reason') + require(final['metrics']['completed_rounds'] == (3 if agent == 'oracle' else 0), f'{name}: round count') + require(read(trial / 'artifacts/data/recording.json')['render_error'] is None, f'{name}: rendering failed') + video = trial / 'artifacts/data/replay.mp4' + require(video.is_file() and video.stat().st_size > 1000, f'{name}: recording missing') + rows.append({'task': name, 'score': score, 'steps': steps, + 'resource_monitor_missing': reward.get('resource_monitor_missing'), + 'resource_enforced': reward.get('resource_enforced')}) + require(seen == expected, 'task coverage incomplete') + require(read(job / 'game-provenance.json')['status'] == 'complete', 'provenance incomplete') + require(read(job / 'runtime-images.json')['complete'] is True, 'runtime image capture incomplete') + require(read(job / 'game-report/summary.json')['complete'] is True, 'derived report incomplete') + print(json.dumps({'agent': agent, 'evidence': 'complete', 'trials': rows}, indent=2)) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('job', type=Path) + parser.add_argument('agent', choices=('oracle', 'nop')) + args = parser.parse_args() + check(args.job, args.agent) diff --git a/game_first_exam/tests/envs/fightingice.Dockerfile b/game_first_exam/tests/envs/fightingice.Dockerfile new file mode 100644 index 0000000..2ea9ad5 --- /dev/null +++ b/game_first_exam/tests/envs/fightingice.Dockerfile @@ -0,0 +1,10 @@ +FROM docker.io/library/python:3.12.10-slim-bookworm@sha256:fd95fa221297a88e1cf49c55ec1828edd7c5a428187e67b5d1805692d11588db +RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates fontconfig libstdc++6 && rm -rf /var/lib/apt/lists/* +ADD --checksum=sha256:51141204fe01a9f9dd74eab621d5eca7511eac67315c9975dbde5f2625bdca55 https://github.com/adoptium/temurin21-binaries/releases/download/jdk-21.0.2%2B13/OpenJDK21U-jre_x64_linux_hotspot_21.0.2_13.tar.gz /tmp/java.tar.gz +RUN mkdir /opt/java && tar -xzf /tmp/java.tar.gz -C /opt/java --strip-components=1 && rm /tmp/java.tar.gz +ENV JAVA_HOME=/opt/java PATH=/opt/java/bin:$PATH FIGHTINGICE_HOME=/opt/fightingice PYTHONUNBUFFERED=1 +COPY game_first_exam/tests/envs/locks/fightingice.txt /requirements.txt +RUN pip install --no-cache-dir --no-deps -r /requirements.txt && pip check +COPY game_first_exam/benchmarks/fightingice/install_native.py game_first_exam/benchmarks/fightingice/SOURCE.json /installer/ +RUN python3 /installer/install_native.py /opt/fightingice +WORKDIR /repo diff --git a/game_first_exam/tests/envs/locks/fightingice.txt b/game_first_exam/tests/envs/locks/fightingice.txt new file mode 100644 index 0000000..f41beba --- /dev/null +++ b/game_first_exam/tests/envs/locks/fightingice.txt @@ -0,0 +1,9 @@ +grpcio==1.62.3 +grpcio-tools==1.62.3 +imageio==2.37.0 +imageio-ffmpeg==0.6.0 +numpy==1.26.4 +pillow==10.4.0 +protobuf==4.25.9 +pyftg==2.3 +setuptools==84.2.1 diff --git a/game_first_exam/tests/run.sh b/game_first_exam/tests/run.sh index a033e85..7af37d1 100755 --- a/game_first_exam/tests/run.sh +++ b/game_first_exam/tests/run.sh @@ -4,6 +4,10 @@ set -euo pipefail root="$(cd "$(dirname "$0")/../.." && pwd)" cd "$root" case "${1:-common}" in + fightingice) + python3 game_first_exam/tests/test_fightingice.py --native + python3 game_first_exam/tests/test_fightingice_competition.py + ;; common) python3 -m unittest discover -s game_first_exam/tests -p 'test_layout.py' python3 -m unittest discover -s game_first_exam/tests -p 'test_game_service.py' @@ -12,6 +16,7 @@ case "${1:-common}" in python3 -m unittest discover -s game_first_exam/tests -p 'test_game_runtime.py' python3 -m unittest discover -s game_first_exam/tests -p 'test_game_connection.py' python3 -m unittest discover -s game_first_exam/tests -p 'test_game_modes.py' + python3 game_first_exam/tests/test_fightingice.py ;; minihack) export GAME_TEST_BENCHMARK=minihack diff --git a/game_first_exam/tests/test_fightingice.py b/game_first_exam/tests/test_fightingice.py new file mode 100644 index 0000000..bbaaeab --- /dev/null +++ b/game_first_exam/tests/test_fightingice.py @@ -0,0 +1,253 @@ +"""Configuration checks by default; --native requires the installed real Java engine.""" +import copy +import importlib.util +import json +from pathlib import Path +import sys +import shutil +import subprocess +import tempfile +import threading +import time +import unittest + +ROOT = Path(__file__).resolve().parents[2] +sys.path[:0] = [str(ROOT / 'scripts'), str(ROOT / 'game_first_exam/runtime')] +from game_schemas import register_schemas +from config_schema import validate_instance + +register_schemas() +TASKS = sorted((ROOT / 'game_first_exam/tasks/fightingice').glob('*-standard')) +BENCH = ROOT / 'game_first_exam/benchmarks/fightingice' + + +def load(name, path): + spec = importlib.util.spec_from_file_location(name, path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +RULES = load('fightingice_metrics', BENCH / 'metric_rules.py') + + +class Configuration(unittest.TestCase): + def test_frozen_match_parameters_fail_closed(self): + self.assertEqual(len(TASKS), 2) + for task in TASKS: + instance = json.loads((task / 'tests/instance.json').read_text()) + validate_instance(instance) + for change in ({'player': True}, {'player': 2}, {'rounds': 1}, {'initial_hp': 401}, + {'round_frames': 3601}, {'seed': 1}, {'opponent': 'arbitrary'}, + {'max_steps': 100}, {'observation_profile': 'non-delay'}, + {'characters': ['GARNET', 'ZEN']}, {'unexpected': True}): + with self.subTest(change=change), self.assertRaises((ValueError, TypeError)): + validate_instance({**instance, **change}) + + def test_round_scores_and_partial_matches(self): + instance = json.loads((TASKS[0] / 'tests/instance.json').read_text()) + rounds = [{'current_round': i, 'remaining_hps': [400, 364], 'elapsed_frame': 3600} + for i in range(1, 4)] + metrics = {'rounds': rounds, 'wins': 3, 'losses': 0, 'draws': 0, 'completed_rounds': 3, + 'round_win_score': 100.0, 'native_steps': 10800} + final = {'metrics': metrics, 'steps': 10800, 'terminated': True, 'truncated': False, + 'return': 0.0, 'success': True} + RULES.validate_metrics(final, instance) + for change in ({'round_win_score': 99}, {'wins': True}, {'native_steps': 10801}, + {'draws': 1}, {'completed_rounds': 2}, {'round_win_score': float('nan')}): + altered = copy.deepcopy(final) + altered['metrics'].update(change) + with self.subTest(change=change), self.assertRaises(ValueError): + RULES.validate_metrics(altered, instance) + partial = copy.deepcopy(final) + partial.update(steps=3600, terminated=False, success=False) + partial['metrics'].update(rounds=rounds[:1], completed_rounds=1, wins=1, + round_win_score=100/3, native_steps=3600) + RULES.validate_metrics(partial, instance) + partial['metrics']['round_win_score'] = 100 + with self.assertRaises(ValueError): + RULES.validate_metrics(partial, instance) + impossible = copy.deepcopy(final) + impossible['metrics']['rounds'][0]['elapsed_frame'] = 10 + with self.assertRaises(ValueError): + RULES.validate_metrics(impossible, instance) + + def test_public_images_do_not_contain_the_engine_or_solution(self): + for task in TASKS: + dockerfile = (task / 'environment/Dockerfile').read_text() + for forbidden in ('FightingICE.jar', 'bridge.py', 'instance.json', 'control.py', '/solution', '/tests'): + self.assertNotIn(forbidden, dockerfile) + self.assertNotIn('ports:', (task / 'environment/docker-compose.yaml').read_text()) + self.assertIn('SERVER_HOST=127.0.0.1', (task / 'environment/sim/Dockerfile').read_text()) + + +class Native(unittest.TestCase): + @classmethod + def setUpClass(cls): + sys.path.insert(0, str(BENCH)) + cls.adapter = load('fightingice_adapter', BENCH / 'adapter.py') + + def test_native_delay_pause_key_mapping_and_cleanup(self): + instance = json.loads((TASKS[0] / 'tests/instance.json').read_text()) + adapter = self.adapter.Adapter(instance) + process = adapter.process + try: + self.assertEqual(adapter.fingerprint(), instance['initial_state_sha256']) + self.assertTrue(adapter.observe()['frame_data']['empty_flag']) + initial = adapter.fingerprint() + for _ in range(3): + adapter.spec(); adapter.observe(); adapter.frame() + time.sleep(.2) + self.assertEqual(adapter.fingerprint(), initial) + port = int(process.args[-1]) + listeners = [line.split()[1].split(':')[0] + for path in ('/proc/net/tcp', '/proc/net/tcp6') + for line in Path(path).read_text().splitlines()[1:] + if line.split()[3] == '0A' and int(line.split()[1].split(':')[1], 16) == port] + self.assertEqual(len(listeners), 1) + self.assertIn(listeners[0], ('0100007F', '0000000000000000FFFF00000100007F')) + for _ in range(20): + adapter.step('R') + observation = adapter.observe() + self.assertEqual(set(observation), {'player', 'frame_data', 'is_control'}) + self.assertNotIn('non_delay_frame_data', observation) + self.assertEqual(observation['frame_data']['current_frame_number'], 6) + self.assertGreater(adapter.audit['current_frame_number'], observation['frame_data']['current_frame_number']) + with self.assertRaises(ValueError): + adapter.step('reset') + with self.assertRaises(ValueError): + adapter.step('RB') # non-canonical key order + finally: + adapter.close() + self.assertIsNotNone(process.poll()) + self.assertFalse(adapter.session.thread.is_alive()) + + def test_reference_matches_live_grading_and_evidence(self): + from grade import grade + from server import Game, InvalidAction + for task in TASKS: + instance = json.loads((task / 'tests/instance.json').read_text()) + reference = load('fightingice_reference', task / 'solution/control.py') + with self.subTest(player=instance['player']), tempfile.TemporaryDirectory() as output: + game = Game(self.adapter.Adapter(instance), instance, output) + try: + self.assertIsNone(game.final) + with self.assertRaises(InvalidAction): + game.submit({'action': 'reset', 'expected_step': 0, 'request_id': 'bad'}) + while game.final is None: + body = {'action': reference.choose(game.observe()['observation']), + 'expected_step': game.steps, 'request_id': str(game.steps)} + reply = game.submit(body) + if game.steps == 1: + self.assertEqual(game.submit(body), reply) + self.assertEqual(game.steps, 1) + verdict = grade(game.final, instance, RULES.validate_metrics) + self.assertEqual((verdict['success'], verdict['primary_score'], verdict['infra_error']), (1, 100, 0)) + self.assertEqual(verdict['steps'], 10800) + recording = json.loads((Path(output) / 'recording.json').read_text()) + self.assertIsNone(recording['render_error']) + self.assertGreater((Path(output) / 'replay.mp4').stat().st_size, 1000) + with self.assertRaises(ValueError): + game.submit({'action': 'noop', 'expected_step': game.steps, 'request_id': 'after'}) + finally: + game.close() + + def test_no_keys_draw_and_early_exit_failures(self): + from grade import grade + from server import Game + instance = json.loads((TASKS[0] / 'tests/instance.json').read_text()) + adapter = self.adapter.Adapter(instance) + try: + while not adapter.done: + adapter.step('noop') + self.assertEqual((adapter.metrics()['draws'], adapter.metrics()['round_win_score']), (3, 0)) + self.assertFalse(adapter.success()) + finally: + adapter.close() + with tempfile.TemporaryDirectory() as output: + game = Game(self.adapter.Adapter(instance), instance, output) + try: + game.finalize('agent_finished') + result = grade(game.final, instance, RULES.validate_metrics) + self.assertEqual((result['success'], result['primary_score'], result['infra_error']), (0, 0, 0)) + self.assertFalse(game.final['terminated']) + finally: + game.close() + + def test_repeated_native_inputs_preserve_gameplay_and_engine_fault_is_invalid(self): + from grade import grade + from server import EnvironmentFault, Game + instance = json.loads((TASKS[0] / 'tests/instance.json').read_text()) + traces = [] + for _ in range(2): + adapter = self.adapter.Adapter(instance) + try: + trace = [adapter.fingerprint()] + for index in range(200): + adapter.step('R' if index < 60 else 'BDR') + trace.append(adapter.fingerprint()) + traces.append(trace) + finally: + adapter.close() + self.assertEqual(traces[0], traces[1]) + with tempfile.TemporaryDirectory() as output: + game = Game(self.adapter.Adapter(instance), instance, output) + try: + game.adapter.process.kill() + game.adapter.process.wait(timeout=5) + with self.assertRaises(EnvironmentFault): + game.submit({'action': 'noop', 'expected_step': 0, 'request_id': 'engine-fault'}) + verdict = grade(game.final, instance, RULES.validate_metrics) + self.assertEqual(verdict['environment_error'], 1) + self.assertIsNone(verdict['primary_score']) + finally: + game.close() + + def test_native_http_client_and_separate_stdlib_verifier(self): + from http.server import HTTPServer + sys.path.insert(0, str(ROOT / 'shared/connection')) + from game_client import GameClient + from server import Game, Handler + instance = json.loads((TASKS[0] / 'tests/instance.json').read_text()) + with tempfile.TemporaryDirectory() as temporary: + output = Path(temporary) + game = Game(self.adapter.Adapter(instance), instance, output) + server = HTTPServer(('127.0.0.1', 0), Handler) + server.game = game + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + client = GameClient(f'http://127.0.0.1:{server.server_port}') + self.assertEqual(client.spec()['game_data']['character_names'], ['ZEN', 'ZEN']) + reply = client.observe() + for _ in range(20): + reply = client.step('R', reply['step']) + self.assertEqual(reply['step'], 20) + self.assertEqual(set(reply['observation']), {'player', 'frame_data', 'is_control'}) + game.finalize('agent_finished') + verifier = output / 'verifier' + verifier.mkdir() + for name in ('grade', 'config_schema', 'reducers'): + shutil.copyfile(ROOT / f'game_first_exam/runtime/{name}.py', verifier / f'{name}.py') + for name in ('instance_schema', 'metric_rules'): + shutil.copyfile(BENCH / f'{name}.py', verifier / f'{name}.py') + subprocess.run([sys.executable, '-S', str(verifier / 'grade.py'), + '--evidence', str(output / 'final.json'), + '--instance', str(TASKS[0] / 'tests/instance.json'), + '--output', str(verifier)], check=True, capture_output=True) + metrics = json.loads((verifier / 'metrics.json').read_text()) + self.assertEqual((metrics['primary_score'], metrics['infra_error']), (0, 0)) + finally: + server.shutdown() + thread.join(timeout=5) + server.server_close() + game.close() + + +if __name__ == '__main__': + native = '--native' in sys.argv + suite = unittest.defaultTestLoader.loadTestsFromTestCase(Configuration) + if native: + suite.addTests(unittest.defaultTestLoader.loadTestsFromTestCase(Native)) + result = unittest.TextTestRunner(verbosity=2).run(suite) + raise SystemExit(not result.wasSuccessful()) diff --git a/game_first_exam/tests/test_fightingice_competition.py b/game_first_exam/tests/test_fightingice_competition.py new file mode 100644 index 0000000..bd90c6e --- /dev/null +++ b/game_first_exam/tests/test_fightingice_competition.py @@ -0,0 +1,323 @@ +"""Focused tests for the separate archive-based competition prototype.""" +from concurrent.futures import ThreadPoolExecutor +from contextlib import redirect_stderr +from io import StringIO +import json +from pathlib import Path +import socket +import sys +import tempfile +import unittest +from unittest.mock import patch + +BENCHMARK = Path(__file__).resolve().parents[1] / "benchmarks/fightingice" +sys.path.insert(0, str(BENCHMARK)) +from competition import author_controller, load_model_profile, main, snapshot, stage_author +from competition_results import ( + SPEEDRUN_PROFILE, TRACKS, duel_report, duel_schedule, read_match, schedule, + speedrun_report, summarize, verify_evidence, +) +from competition_match import relay +from competition_wire import packet, public_state, receive, send + + +class CompetitionTests(unittest.TestCase): + def test_speedrun_model_uses_track_instructions_and_one_authoring_job(self): + import tomllib + + profile = {"agents": [{"name": "oracle"}]} + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + for track, style in (("rushdown", "close-range pressure"), ("zoning", "distance control")): + character, baseline, _ = TRACKS[track] + task = root / track + stage_author(task, track=track, league="speedrun") + prompt = (task / "instruction.md").read_text() + for text in (character, baseline, style, "average scored frames", "4200 frames", + "does not provide audio or screen"): + self.assertIn(text, prompt) + cfg = tomllib.loads((task / "task.toml").read_text()) + self.assertEqual(cfg["agent"]["timeout_sec"], 600) + self.assertEqual(cfg["verifier"]["environment_mode"], "separate") + self.assertEqual(cfg["verifier"]["network_mode"], "no-network") + job = json.loads((task / "author-job.json").read_text()) + self.assertEqual((job["n_attempts"], job["retry"]["max_retries"]), (1, 0)) + argv = ["competition.py", "run", "--league", "speedrun", "--track", track, + "--model", "profile.json", "--release", "engine.zip", "--resources", "resources.zip", + "--output", str(task)] + with patch.object(sys, "argv", argv), patch("competition.load_native_profile", return_value=profile), \ + patch("competition.run_series") as run: + main() + args, output, rows, sources, profiles = run.call_args.args + self.assertEqual(args.track, track) + self.assertEqual(output, task) + self.assertEqual(rows, schedule(track, ["entry"], "speedrun")) + self.assertEqual(sources, {}) + self.assertEqual(profiles, {"entry": profile}) + with patch.object(sys, "argv", [*argv, "another=/tmp/source"]), redirect_stderr(StringIO()), \ + patch("competition.run_series") as run, self.assertRaises(SystemExit): + main() + run.assert_not_called() + + def test_speedrun_schedule(self): + for track, (character, baseline, _) in TRACKS.items(): + rows = schedule(track, ["alpha", "beta"], "speedrun") + self.assertEqual(len(rows), 20) + for entry in ("alpha", "beta"): + for p1, p2 in ((entry, baseline), (baseline, entry)): + self.assertEqual([r["game"] for r in rows if (r["p1"], r["p2"]) == (p1, p2)], + list(range(1, 6))) + self.assertTrue(all(r["character"] == character for r in rows)) + + def test_speedrun_scores_all_rounds_and_shares_rank(self): + rows = schedule("rushdown", ["slow", "fast-tie", "fast"], "speedrun") + results = [] + for match in rows: + entry_is_p2 = match["p1"] == "MctsAi23i" + name = match["p2"] if entry_is_p2 else match["p1"] + points = [(1, 400, 0, 600 if name != "slow" else 3000), + (2, 100, 200, 50), (3, 50, 50, 3600)] + if entry_is_p2: + points = [(n, other, hp, frames) for n, hp, other, frames in points] + results.append({"points": points}) + + report = speedrun_report(rows, results) + self.assertEqual(report["standings"], [ + {"rank": 1, "controllers": ["fast", "fast-tie"]}, {"rank": 3, "controllers": ["slow"]}, + ]) + fast = report["controllers"]["fast"] + self.assertEqual((fast["games"], fast["rounds"], fast["wins"], fast["draws"], fast["losses"]), + (10, 30, 10, 10, 10)) + self.assertEqual((fast["penalty_rounds"], fast["average_frames"]), (10, 2800)) + self.assertAlmostEqual(fast["average_seconds"], 2800 / 60) + swapped = report["matches"][-1]["rounds"] + self.assertEqual(swapped[0], dict(round=1, p1_hp=0, p2_hp=400, elapsed_frames=600, + scored_frames=600, outcome="win")) + self.assertEqual((swapped[1]["elapsed_frames"], swapped[1]["scored_frames"]), (50, 4200)) + with self.assertRaisesRegex(ValueError, "incomplete speedrun match matrix"): + speedrun_report(rows, results[:-1]) + with self.assertRaisesRegex(ValueError, "five matches on each side"): + speedrun_report(rows[:-1], results[:-1]) + results[-1]["points"].pop() + with self.assertRaisesRegex(ValueError, "incomplete speedrun rounds"): + speedrun_report(rows, results) + + def test_speedrun_summarize_requires_frozen_schedule_and_verified_matches(self): + with tempfile.TemporaryDirectory() as tmp, patch.object(sys, "argv", ["competition.py", "summarize", tmp]): + output = Path(tmp) + rows = schedule("zoning", ["entry"], "speedrun") + (output / "provenance.json").write_text(json.dumps({ + "profile": SPEEDRUN_PROFILE, "track": "zoning", "baseline": "MctsAiZoning", + "controller_sha256": {"entry": {}}, + })) + matrix = output / "schedule.json" + matrix.write_text(json.dumps(rows[:-1])) + with self.assertRaisesRegex(ValueError, "stored match matrix"): + main() + matrix.write_text(json.dumps(rows)) + with self.assertRaisesRegex(ValueError, "0001: missing verified match"): + main() + (output / "0001").mkdir() + (output / "0001/verified.json").write_text("{}") + with patch("competition.verify_evidence", return_value={"points": []}): + with self.assertRaisesRegex(ValueError, "0001: native CSV and verified result differ"): + main() + + def test_duel_schedule_and_score(self): + rows = duel_schedule("rushdown", 2) + self.assertEqual([(r["p1"], r["p2"], r["game"]) for r in rows], [ + ("model-a", "model-b", 1), ("model-b", "model-a", 1), + ("model-a", "model-b", 2), ("model-b", "model-a", 2), + ]) + for pairs in (0, -1, True): + with self.assertRaises(ValueError): + duel_schedule("rushdown", pairs) + # The two controllers tie on points, but B has more remaining HP. + points = [[1, 110, 0, 360], [2, 0, 0, 720], [3, 110, 110, 3600]] + swapped = [[1, 200, 0, 360], [2, 0, 0, 720], [3, 200, 200, 3600]] + style = [{f"P{side}_{col}": 0 for side in (1, 2) + for col in ("comboCount", "ProximityScore", "corneredFrames")}] * 3 + report = duel_report(rows[:2], [{"points": p, "style": style} for p in (points, swapped)], {}) + self.assertEqual([s["controllers"] for s in report["standings"]], [["model-b"], ["model-a"]]) + self.assertEqual(report["matches"][1]["round_points"], {"model-a": 1.0, "model-b": 2.0}) + self.assertFalse(report["audio"]) + with self.assertRaises(ValueError): + duel_report(rows, [], {}) + + def test_duel_harbor_profiles_and_failed_artifacts(self): + with tempfile.TemporaryDirectory() as temp: + root = Path(temp) + config = root / "model.json" + profile = {"agents": [{"name": "codex", "model_name": "example-model", + "kwargs": {"version": "0.1", "reasoning_effort": "low"}}]} + config.write_text(json.dumps(profile)) + self.assertEqual(load_model_profile(config), profile) + for invalid in ({**profile, "tasks": [{}]}, {**profile, "n_attempts": 2}, { + "agents": [{**profile["agents"][0], "override_timeout_sec": 900}] + }, {"agents": profile["agents"] * 2}): + config.write_text(json.dumps(invalid)) + with self.assertRaises(ValueError): + load_model_profile(config) + task = root / "author" + stage_author(task, track="zoning") + prompt = (task / "instruction.md").read_text() + self.assertIn("both sides as NEZ", prompt) + self.assertIn("does not provide audio", prompt) + jobs = root / "author-jobs" + trial = jobs / "model-a/trial" + trial.mkdir(parents=True) + result = {"finished_at": "finished", "verifier_environment_mode": "separate", + "agent_info": {"name": "codex", "version": "0.1"}, + "verifier_result": {"rewards": {"reward": 1.0}}, "exception_info": None} + result_file = trial / "result.json" + result_file.write_text(json.dumps(result)) + with patch("competition.subprocess.run") as run: + path, model = author_controller("harbor", task, jobs, "model-a", profile) + self.assertEqual(path, trial / "artifacts/app/output") + self.assertEqual(model["model_name"], "example-model") + self.assertEqual(model["reasoning_effort"], "low") + self.assertIn("model-a", run.call_args.args[0]) + result["exception_info"] = {"type": "AgentTimeoutError"} + result_file.write_text(json.dumps(result)) + with self.assertRaisesRegex(ValueError, "did not produce a verified controller"): + author_controller("harbor", task, jobs, "model-a", profile) + + def test_archive_schedule_sizes(self): + entries = list("abcdefgh") + for track in ("zoning", "rushdown"): + standard = schedule(track, entries, "standard") + self.assertEqual(len(standard), 90) # 10 players, each pair switches sides. + self.assertEqual(len(schedule(track, entries, "style")), 160) # only entrants scored + self.assertEqual(len(schedule(track, ["entry"], "style", mcts_only=True)), 10) + self.assertEqual(sum(r["p1"] == "a" for r in standard), 9) + for entries in (["a", "a"], ["../a"], ["organizer"], []): + with self.assertRaises(ValueError): + schedule("rushdown", entries, "style") + + def test_archive_style_and_standard_metrics(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + points, style = root / "points.csv", root / "style.csv" + points.write_text("1,400,350,3600\n2,0,20,1000\n3,20,20,3600\n") + style.write_text( + "P1_ProjectileScore,P1_ProximityScore,P1_AntiAirCount," + "P2_ProjectileScore,P2_ProximityScore,P2_AntiAirCount\n" + "69,-76,7,34,-76,3\n72,-76,10,36,-76,1\n66,-32,5,33,-32,6\n") + result = read_match("zoning", points, style) + match = schedule("zoning", ["entry"], "style", True)[0] + totals = summarize([match], [result])["controllers"]["entry"] + self.assertEqual((totals["round_points"], totals["remaining_hp"], totals["speed_frames"]), + (1.5, 420, 11400)) + self.assertEqual(totals["style"]["ProjectileScore"], 69) + self.assertNotIn("standings", summarize([match], [result])) + with self.assertRaises(ValueError): + summarize([match], []) + points.write_text("1,400,350,3600\n2,0,20,1000\n") + with self.assertRaises(ValueError): + read_match("zoning", points, style) + + def test_verifier_rejects_callback_disagreement(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + for name in ("point", "style"): + (root / "engine/log" / name).mkdir(parents=True) + points = [[i, 400, 400, 3600] for i in range(1, 4)] + (root / "engine/log/point/match.csv").write_text( + "".join(",".join(map(str, row)) + "\n" for row in points)) + columns = [f"P{side}_{field}" for side in (1, 2) + for field in ("comboCount", "ProximityScore", "corneredFrames")] + (root / "engine/log/style/match.csv").write_text(",".join(columns) + "\n" + "0,0,0,0,0,0\n" * 3) + match = schedule("rushdown", ["entry"], "standard", True)[0] + callback = {"callbacks": 10800, "controller_disconnected": False, "round_results": points} + record = {"points": points, "style": [dict.fromkeys(columns, 0)] * 3, "callbacks": {"1": callback}} + result_file = root / "match-result.json" + result_file.write_text(json.dumps(record)) + totals = summarize([match], [verify_evidence(root, match)]) + self.assertEqual(totals["standings"], [{"rank": 1, "controllers": ["MctsAi23i", "entry"]}]) + callback["round_results"] = points[:2] + result_file.write_text(json.dumps(record)) + with self.assertRaises(ValueError): + verify_evidence(root, match) + + def test_snapshot_rejects_symlink_and_harbor_task_is_artifact_only(self): + import tomllib + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + source = root / "source" + source.mkdir() + controller = source / "controller.py" + controller.write_text("class AI: pass\n") + manifest = snapshot(source, root / "snapshot") + self.assertEqual(list(manifest), ["controller.py"]) + (source / "not-a-submission").symlink_to(controller) + with self.assertRaises(ValueError): + snapshot(source, root / "unsafe") + stage_author(root / "author") + cfg = tomllib.loads((root / "author/task.toml").read_text()) + self.assertEqual(cfg["verifier"]["network_mode"], "no-network") + self.assertEqual(cfg["artifacts"], ["/app/output/"]) + self.assertNotIn("competition_match", (root / "author/environment/Dockerfile").read_text()) + + def test_packet_limit_and_no_privileged_state(self): + from pyftg.models.enums.flag import Flag + from pyftg.protoc.service_pb2 import PlayerGameState + native = PlayerGameState(state_flag=Flag.PROCESSING.value, is_control=True) + native.frame_data.current_frame_number = 6 + native.non_delay_frame_data.current_frame_number = 20 + native.screen_data.SetInParent() + native.audio_data.SetInParent() + flag, public = public_state(native) + self.assertEqual(flag, Flag.PROCESSING) + self.assertEqual(public.frame_data.current_frame_number, 6) + self.assertFalse(public.HasField("non_delay_frame_data")) + self.assertFalse(public.HasField("screen_data")) + self.assertTrue(public.HasField("audio_data")) + _, duel_public = public_state(native, audio=False) + self.assertFalse(duel_public.HasField("audio_data")) + self.assertTrue(duel_public.is_control) + left, right = socket.socketpair() + with left, right: + send(left, public.SerializeToString()) + self.assertEqual(PlayerGameState.FromString(packet(right)), public) + send(left, b"x" * 129) + with self.assertRaises(ValueError): + packet(right, 128) + + def test_relay_passes_native_events_and_returns_only_keys(self): + from pyftg.models.enums.flag import Flag + from pyftg.protoc.message_pb2 import GrpcKey + from pyftg.protoc.service_pb2 import PlayerGameState + + engine, trusted_engine = socket.socketpair() + player, trusted_player = socket.socketpair() + with engine, trusted_engine, player, trusted_player, ThreadPoolExecutor() as pool: + for sock in (engine, trusted_engine, player, trusted_player): + sock.settimeout(2) + future = pool.submit(relay, trusted_engine, trusted_player, audio=False) + for flag in (Flag.INITIALIZE, Flag.PROCESSING, Flag.GAME_END): + message = PlayerGameState(state_flag=flag.value) + if flag == Flag.PROCESSING: + message.audio_data.SetInParent() + if flag == Flag.GAME_END: + message.round_result.current_round = 3 + message.round_result.remaining_hps.extend([300, 0]) + message.round_result.elapsed_frame = 100 + engine.sendall(b"\1") + send(engine, message.SerializeToString()) + self.assertEqual(receive(player, 1), b"\1") + public = PlayerGameState.FromString(packet(player)) + self.assertEqual(public.state_flag, flag.value) + self.assertFalse(public.HasField("audio_data")) + if flag == Flag.PROCESSING: + key = GrpcKey() + key.A = True + send(player, key.SerializeToString()) + self.assertEqual(GrpcKey.FromString(packet(engine)), key) + engine.sendall(b"\0") + self.assertEqual(receive(player, 1), b"\0") + self.assertEqual(future.result(), {"callbacks": 1, "controller_disconnected": False, + "round_results": [[3, 300, 0, 100]]}) + + +if __name__ == "__main__": + unittest.main() diff --git a/game_first_exam/tests/test_game_configuration.py b/game_first_exam/tests/test_game_configuration.py index 37561f9..ca015df 100644 --- a/game_first_exam/tests/test_game_configuration.py +++ b/game_first_exam/tests/test_game_configuration.py @@ -79,7 +79,7 @@ def test_instance_and_reducer_typos_fail_closed(self): validate_instance(missing) def test_native_ci_and_runtime_dependency_locks_match(self): - for benchmark in ('minigrid', 'crafter', 'textworld', 'babaisai', 'minihack'): + for benchmark in ('minigrid', 'crafter', 'textworld', 'babaisai', 'minihack', 'fightingice'): filename = 'requirements-v2.txt' if benchmark == 'minigrid' else 'requirements.txt' runtime = ROOT / 'game_first_exam/benchmarks' / benchmark / filename lock = ROOT / 'game_first_exam/tests/envs/locks' / (benchmark + '.txt') diff --git a/game_first_exam/tests/test_game_harbor.py b/game_first_exam/tests/test_game_harbor.py index e6e71f6..c16f1c5 100644 --- a/game_first_exam/tests/test_game_harbor.py +++ b/game_first_exam/tests/test_game_harbor.py @@ -32,13 +32,13 @@ class GameSelection(unittest.TestCase): def test_game_only_default_and_all_selection_never_launches(self): for flags, expected in ((["--list", "--standard"], 30), - (["--all", "--standard", "--list"], 42)): + (["--all", "--standard", "--list"], 44)): with self.subTest(flags=flags), contextlib.redirect_stdout(io.StringIO()) as output, \ patch("efe.harbor") as launch, patch("efe.prepull") as pull: self.assertEqual(efe.run(flags), 0) names = output.getvalue().splitlines() self.assertEqual(len(names), expected) - self.assertTrue(all(name.startswith(("minigrid-", "crafter-", "textworld-", "babaisai-", "minihack-")) + self.assertTrue(all(name.startswith(("minigrid-", "crafter-", "textworld-", "babaisai-", "minihack-", "fightingice-")) for name in names)) launch.assert_not_called() pull.assert_not_called() diff --git a/scripts/task_conventions.py b/scripts/task_conventions.py index 36b7e5c..61e8f36 100644 --- a/scripts/task_conventions.py +++ b/scripts/task_conventions.py @@ -72,6 +72,7 @@ # benchmark's game_first_exam/benchmarks//; BENCHMARKS and BENCHMARK_DIRS below are views of this table, and # ci_checks/ci_scope.py --check holds its UNITS / FILES_IMAGE to it. A new benchmark adds one row here. BENCHMARK_TABLE = [ + ("fightingice-", "FightingICE", "fightingice"), ("minihack-", "MiniHack", "minihack"), ("babaisai-", "Baba Is AI", "babaisai"), ("crafter-", "Crafter", "crafter"), @@ -218,6 +219,7 @@ "`/run/rcb-limits/usage.json` to plan around the agent deadline. The client's `time_left_s` counts from the " "first `observe()` or accepted action, whichever comes first. `spec()` does not start that clock." ) +CUTOFF_NOTE_OWN[("FightingICE", "standard")] = CUTOFF_NOTE_TASK["minihack-room-i01-standard"] CUTOFF_NOTE_START = "This is wall-clock time from the start of your session;" # how an earlier note is recognised WALL_CLOCK_ENV = "RCB_WALL_CLOCK_S" # the standard modes' sim service: what its /spec budget and time_left_s report CUTOFF_CAP = 14400 # PROTOCOL §2, no benchmark excepted (ci_checks/check-cutoffs.py) diff --git a/scripts/task_resources.toml b/scripts/task_resources.toml index f5e2106..8bf4d3e 100644 --- a/scripts/task_resources.toml +++ b/scripts/task_resources.toml @@ -1,5 +1,11 @@ # Game task resource caps; shared rendering and monitor enforcement are inherited from upstream. +[[cap]] +match = "^fightingice-.*-standard$" +main = { cpus = 1, memory_gb = 1, pids = 256, disk_gb = 2 } +sim = { cpus = 1, memory_gb = 1, pids = 128 } +measured = "Local native container tests passed with 1 CPU, 1 GiB of memory, and a 128-process limit. The native Harbor rerun recorded the Docker limits in runtime-images.json." + [[cap]] match = "^minigrid-.*-standard$" main = { cpus = 1, memory_gb = 1, pids = 256, disk_gb = 2 } From 2b81bd48ec6ab44a398649055c9378f69dc56b8a Mon Sep 17 00:00:00 2001 From: lyh <2641805259@qq.com> Date: Fri, 27 Nov 2026 14:25:46 +0800 Subject: [PATCH 2/2] Add FightingICE post-match video export --- docs/VALIDATION.md | 12 ++ .../benchmarks/fightingice/competition.md | 30 ++++ .../benchmarks/fightingice/record-replay.sh | 41 ++++++ .../benchmarks/fightingice/replay.Dockerfile | 7 + .../benchmarks/fightingice/replay.py | 138 ++++++++++++++++++ .../tests/test_fightingice_competition.py | 22 +++ 6 files changed, 250 insertions(+) create mode 100644 game_first_exam/benchmarks/fightingice/record-replay.sh create mode 100644 game_first_exam/benchmarks/fightingice/replay.Dockerfile create mode 100644 game_first_exam/benchmarks/fightingice/replay.py diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md index b5e15ee..de35a38 100644 --- a/docs/VALIDATION.md +++ b/docs/VALIDATION.md @@ -186,3 +186,15 @@ This workflow is separate from the frozen 7.0 smoke tasks above. and undelayed-state callbacks. Local Oracle jobs made no model API calls. - The 46-task static check, 55 common tests, 17 Harbor configuration tests, 8 native FightingICE tests, and 12 competition tests passed. + +## FightingICE video export + +- The replay exporter recorded four verified 7.1 matches with the native + graphical engine, including both Rushdown sides, a Zoning match, and a + duel. The renderer reproduced all twelve original round lengths. FFmpeg + decoded each 960×640 H.264 video through the end. +- A missing `.dat` produced a failed manifest entry, the next match still + exported, and the saved league report kept the same SHA256. +- A local browser preview outside the checkout played the videos, switched + sides and tracks, and displayed the verified round results at desktop and + mobile widths. diff --git a/game_first_exam/benchmarks/fightingice/competition.md b/game_first_exam/benchmarks/fightingice/competition.md index e54a8fe..fd19da8 100644 --- a/game_first_exam/benchmarks/fightingice/competition.md +++ b/game_first_exam/benchmarks/fightingice/competition.md @@ -177,6 +177,36 @@ per-match native evidence, and `league-report.json` for a complete schedule. `python "$FTG/competition.py" summarize RUN_DIR` rechecks the native CSVs against the verified match records. Partial MCTS-only results stay explicitly marked. +## Export match videos + +For a completed 7.1 duel or speedrun, export native `.dat` replays to silent +960×640 H.264 MP4 files for browser playback. The export rechecks the stored +scores, compares each replay's character, frame count, and final round HP to +the verified match, and runs the pinned 7.1 engine in a separate offline +container with a virtual display. It checks the lengths of all three rounds +reported by the replay player before publishing the video. + +```bash +FTG=game_first_exam/benchmarks/fightingice +docker build -f "$FTG/competition.Dockerfile" \ + -t game-exam:fightingice-competition "$FTG" +docker build -f "$FTG/replay.Dockerfile" \ + -t game-exam:fightingice-replay "$FTG" + +python "$FTG/replay.py" /path/to/completed-run \ + --release /path/to/DareFightingICE-7.1.zip \ + --resources /path/to/resource-7.1.zip \ + --output /tmp/opencode/ftg-video \ + --match 1 --match 2 +``` + +Omit `--match` to export the entire run. Each match produces a `replay.mp4` +and a `poster.jpg`. The browser can load `replays.json` for the competitors, +starting sides, verified round results, and relative paths to the media. +A failed export has a status in the manifest and local render logs. The +export continues with the remaining matches and exits nonzero if any failed. +The original run is read-only during export. + ## Verification The focused regression is `python game_first_exam/tests/test_fightingice_competition.py` diff --git a/game_first_exam/benchmarks/fightingice/record-replay.sh b/game_first_exam/benchmarks/fightingice/record-replay.sh new file mode 100644 index 0000000..fcda964 --- /dev/null +++ b/game_first_exam/benchmarks/fightingice/record-replay.sh @@ -0,0 +1,41 @@ +#!/usr/bin/env bash +set -euo pipefail + +cd /tmp +for asset in FightingICE.jar lib data; do + ln -s "/install/$asset" "$asset" +done +mkdir -p log/replay /tmp/cache +ln -s /input/match.dat log/replay/match.dat +export XDG_CACHE_HOME=/tmp/cache SERVER_HOST=127.0.0.1 + +java -cp 'FightingICE.jar:lib/*:lib/grpc/*:lib/lwjgl/*:lib/lwjgl/natives/linux/amd64/*' \ + Main --c1 "$1" --c2 "$1" --limithp 400 400 --mute > /out/engine.log 2>&1 & +game=$! +capture= +trap 'if [[ -n "$capture" ]]; then kill -INT "$capture" 2>/dev/null || true; wait "$capture" || true; fi; kill "$game" 2>/dev/null || true; wait "$game" || true' EXIT + +window=$(timeout 25 xdotool search --sync --onlyvisible --name '^DareFightingICE$') +xdotool windowfocus --sync "$window" +until grep -q 'Socket server is started' /out/engine.log; do + kill -0 "$game" + sleep .1 +done +# The first display update installs the home menu's key handlers. +sleep .5 +xdotool key --delay 250 Down z + +ffmpeg -nostdin -loglevel warning -f x11grab -framerate 30 -video_size 960x640 \ + -draw_mouse 0 -i "$DISPLAY" -an -c:v libx264 -threads 2 -preset veryfast \ + -crf 21 -pix_fmt yuv420p -movflags +faststart /out/capture.mp4 > /out/ffmpeg.log 2>&1 & +capture=$! +while [[ $(grep -c 'Round Duration:' /out/engine.log || true) -lt 3 ]]; do + kill -0 "$game" "$capture" + sleep .2 +done +kill -INT "$capture" +wait "$capture" || [[ $? == 255 ]] +capture= +ffprobe -v error -select_streams v:0 -show_entries stream=codec_name,width,height \ + -show_entries format=duration -of json /out/capture.mp4 > /out/video.json +ffmpeg -nostdin -v error -ss 5 -i /out/capture.mp4 -frames:v 1 -update 1 /out/poster.jpg diff --git a/game_first_exam/benchmarks/fightingice/replay.Dockerfile b/game_first_exam/benchmarks/fightingice/replay.Dockerfile new file mode 100644 index 0000000..fce1c6a --- /dev/null +++ b/game_first_exam/benchmarks/fightingice/replay.Dockerfile @@ -0,0 +1,7 @@ +FROM game-exam:fightingice-competition +RUN apt-get update && apt-get install -y --no-install-recommends \ + xvfb xauth xdotool ffmpeg libgl1 libgl1-mesa-dri libxrandr2 libxi6 \ + && rm -rf /var/lib/apt/lists/* +ENV LIBGL_ALWAYS_SOFTWARE=1 LP_NUM_THREADS=2 JAVA_TOOL_OPTIONS=-XX:ActiveProcessorCount=2 +COPY record-replay.sh /record-replay.sh +ENTRYPOINT ["timeout", "--kill-after=5", "250", "xvfb-run", "-a", "-s", "-screen 0 960x640x24 -nolisten tcp", "bash", "/record-replay.sh"] diff --git a/game_first_exam/benchmarks/fightingice/replay.py b/game_first_exam/benchmarks/fightingice/replay.py new file mode 100644 index 0000000..0c2e903 --- /dev/null +++ b/game_first_exam/benchmarks/fightingice/replay.py @@ -0,0 +1,138 @@ +"""Export verified FightingICE 7.1 matches to MP4 and a static replay manifest.""" +import argparse +import json +import os +from pathlib import Path +import re +from struct import unpack_from +import subprocess +import sys +import tempfile + +from competition import HERE, docker, dump, install, mount, outside_checkout, sha + + +REPLAY_IMAGE = "game-exam:fightingice-replay" +CHARACTER_IDS = {"GARNET": 0, "NEZ": 3} + + +def match_rounds(match): + if "entry" in match: + return match["rounds"] + return [dict(round=n, p1_hp=hp1, p2_hp=hp2, elapsed_frames=frames) + for n, hp1, hp2, frames in match["rounds"]] + + +def check_recording(replay, character, rounds): + # The 7.1 HP-mode header has three int32s per player. Each frame then + # contains two 20-byte player records. HP starts at byte 3 in each record. + frames = sum(row["elapsed_frames"] for row in rounds) + expected_size = 24 + frames * 40 + with replay.open("rb") as stream: + data = stream.read(expected_size + 1) + if (len(data) != expected_size + or unpack_from(">6i", data) != (-1, 400, CHARACTER_IDS[character]) * 2): + raise ValueError("replay size or character header disagrees with the verified match") + end = 24 + for row in rounds: + end += row["elapsed_frames"] * 40 + recorded = [max(0, unpack_from(">i", data, end - offset)[0]) for offset in (37, 17)] + if recorded != [max(0, row["p1_hp"]), max(0, row["p2_hp"])]: + raise ValueError(f"replay HP disagrees with verified round {row['round']}") + + +def render(replay, engine, destination, image, character, rounds): + expected = [row["elapsed_frames"] for row in rounds] + check_recording(replay, character, rounds) + digest = sha(replay) + with tempfile.TemporaryDirectory(dir=destination, prefix=".render-") as temp: + work = Path(temp) + with (destination / "render.log").open("wb") as log: + try: + docker("run", "--rm", "--network", "none", "--read-only", "--cap-drop", "ALL", + "--security-opt", "no-new-privileges", "--user", f"{os.getuid()}:{os.getgid()}", + "--pids-limit", "128", "--cpus", "2", "--memory", "2g", "--shm-size", "128m", + "--tmpfs", "/tmp:rw,nosuid,nodev,exec", + *mount(engine, "/install"), *mount(replay, "/input/match.dat"), + *mount(work, "/out", False), image, character, stdout=log, + stderr=subprocess.STDOUT, timeout=275) + engine_log = (work / "engine.log").read_text() + durations = re.findall(r"Round Duration: .*?\(Expected (\d+\.\d+)\)", engine_log) + if ([round(float(seconds) * 60) for seconds in durations] != expected + or "finished in the middle" in engine_log): + raise ValueError("native playback did not reproduce all verified round lengths") + info = json.loads((work / "video.json").read_text()) + duration = float(info["format"]["duration"]) + if (info["streams"] != [{"codec_name": "h264", "width": 960, "height": 640}] + or duration < sum(expected) / 60): + raise ValueError("capture is missing or shorter than the verified match") + (work / "poster.jpg").replace(destination / "poster.jpg") + (work / "capture.mp4").replace(destination / "replay.mp4") + finally: + for filename in ("engine.log", "ffmpeg.log"): + if (work / filename).is_file(): + (work / filename).replace(destination / filename) + return dict(duration_seconds=round(duration, 2), native_replay_sha256=digest, + video=f"{destination.name}/replay.mp4", poster=f"{destination.name}/poster.jpg") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("run", type=Path, help="completed competition.py duel or speedrun output") + parser.add_argument("--release", type=Path, required=True) + parser.add_argument("--resources", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True, help="new directory outside the checkout and run") + parser.add_argument("--match", type=int, action="append", help="one-based match number, repeat to select several") + args = parser.parse_args() + + run = args.run.resolve() + output = outside_checkout(args.output) + if output.is_relative_to(run): + parser.error("place exports outside the scored run directory") + report = json.loads(subprocess.check_output([sys.executable, str(HERE / "competition.py"), + "summarize", str(run)])) + matches = report.get("matches") + if not matches: + parser.error("replay export requires a completed 7.1 duel or speedrun") + selected = sorted(set(args.match or range(1, len(matches) + 1))) + if any(i < 1 or i > len(matches) for i in selected): + parser.error("match number is outside the verified schedule") + image = docker("image", "inspect", "--format", "{{.Id}}", REPLAY_IMAGE, + capture_output=True, text=True, timeout=30).stdout.strip() + output.mkdir(parents=True) + manifest = {key: report[key] for key in ("track", "league", "mode", "baseline", "controllers", "standings") + if key in report} + manifest["models"] = {name: {field: model[field] for field in ("agent", "model_name", "reasoning_effort") + if field in model} + for name, model in report.get("models", {}).items()} + manifest.update(schema_version=1, renderer_image=image, matches=[]) + failed = False + with tempfile.TemporaryDirectory(prefix="ftg-replay-") as temp: + engine = Path(temp) / "engine" + install(engine, [args.release, args.resources]) + for i in selected: + directory = f"{i:04d}" + target = output / directory + target.mkdir() + match = matches[i - 1] + item = {**match, "id": i, "rounds": match_rounds(match)} + try: + replays = list((run / directory / "engine/log/replay").glob("*.dat")) + if len(replays) != 1: + raise ValueError(f"expected one native replay for match {i}, found {len(replays)}") + item.update(render(replays[0], engine, target, image, match["character"], item["rounds"])) + item["status"] = "ready" + except (OSError, ValueError, subprocess.SubprocessError) as error: + failed = True + item.update(status="failed", error=str(error)) + manifest["matches"].append(item) + pending = output / ".replays.json" + dump(pending, manifest) + pending.replace(output / "replays.json") + print(f"Match {i}: {item['status']}", flush=True) + print(output / "replays.json") + return int(failed) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/game_first_exam/tests/test_fightingice_competition.py b/game_first_exam/tests/test_fightingice_competition.py index bd90c6e..05c0506 100644 --- a/game_first_exam/tests/test_fightingice_competition.py +++ b/game_first_exam/tests/test_fightingice_competition.py @@ -5,6 +5,7 @@ import json from pathlib import Path import socket +from struct import pack, pack_into import sys import tempfile import unittest @@ -19,9 +20,30 @@ ) from competition_match import relay from competition_wire import packet, public_state, receive, send +from replay import check_recording, match_rounds class CompetitionTests(unittest.TestCase): + def test_replay_export_binds_native_recording_to_score(self): + rounds = match_rounds({"rounds": [[1, 0, 300, 1], [2, 400, 0, 1], [3, 400, 400, 1]]}) + data = bytearray(pack(">6i", -1, 400, 3, -1, 400, 3) + bytes(120)) + for row in rounds: + offset = 24 + (row["round"] - 1) * 40 + pack_into(">i", data, offset + 3, row["p1_hp"]) + pack_into(">i", data, offset + 23, row["p2_hp"]) + pack_into(">i", data, 27, -5) # The DAT preserves KO overkill before CSV clamping. + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "match.dat" + path.write_bytes(data) + check_recording(path, "NEZ", rounds) + with self.assertRaisesRegex(ValueError, "character header"): + check_recording(path, "GARNET", rounds) + with self.assertRaisesRegex(ValueError, "verified round 1"): + check_recording(path, "NEZ", [{**rounds[0], "p2_hp": 299}, *rounds[1:]]) + path.write_bytes(data[:-1]) + with self.assertRaisesRegex(ValueError, "replay size"): + check_recording(path, "NEZ", rounds) + def test_speedrun_model_uses_track_instructions_and_one_authoring_job(self): import tomllib