Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions .github/workflows/slimevolley.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
name: slimevolley
on:
pull_request:
push:
branches: [main]
workflow_dispatch:
permissions:
contents: read
jobs:
smoke:
runs-on: ubuntu-latest
timeout-minutes: 30
env:
TASK: game_first_exam/tasks/slimevolley/slimevolley-pixel-vs-baseline-i01-standard
steps:
- uses: actions/checkout@v4
with: {persist-credentials: false}
- uses: actions/setup-python@v5
with: {python-version: '3.12'}
- uses: docker/setup-docker-action@v5
with:
version: v29.5.2
set-host: true
daemon-config: '{"features":{"containerd-snapshotter":true}}'
- run: python -m pip install -e .
- run: harbor run --game-suite slimevolley --standard --list
- name: Compare against the pinned native simulator
run: |
python scripts/files_image.py build game-files
python scripts/files_image.py build slimevolley-files
docker build -t slimevolley-native "$TASK/environment/sim"
docker run --rm --network none -v "$PWD:/repo:ro" slimevolley-native \
python /repo/game_first_exam/tests/test_slimevolley_native.py
- name: Run SlimeVolley with a frozen reference
run: |
harbor run --game-suite slimevolley --standard \
-c configs/harbor/oracle.json --plugin game_harbor:GameRecords \
--job-name fresh-slimevolley -y
- name: Check the match and decode the replay
run: |
python - <<'PY'
import json
from pathlib import Path
job = Path("jobs/fresh-slimevolley")
summary = json.loads((job / "game-report/summary.json").read_text())
assert summary["complete"] and summary["valid_trials"] == 1
episode, = summary["trials"]
assert (episode["primary_score"], episode["success"], episode["steps"]) == (1, 1, 3000)
assert episode["terminal_reason"] == "native_truncated"
assert json.loads((job / "runtime-images.json").read_text())["complete"]
PY
docker run --rm --network none -v "$PWD/jobs:/jobs:ro" slimevolley-native sh -ec \
'"$(python -c "import imageio_ffmpeg; print(imageio_ffmpeg.get_ffmpeg_exe())")" -v error -xerror -i /jobs/fresh-slimevolley/*/artifacts/data/replay.mp4 -f null -'
- name: Verify the practice and scored match isolation
run: python scripts/run_slimevolley_exam.py --smoke --output "$PWD/jobs/slimevolley-exam-smoke"
3 changes: 3 additions & 0 deletions configs/game_benchmarks.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,8 @@ schema = "game_first_exam/benchmarks/textworld/instance_schema.py"
[benchmarks.babaisai]
schema = "game_first_exam/benchmarks/babaisai/instance_schema.py"

[benchmarks.slimevolley]
schema = "game_first_exam/benchmarks/slimevolley/instance_schema.py"

[benchmarks.minihack]
schema = "game_first_exam/benchmarks/minihack/instance_schema.py"
10 changes: 10 additions & 0 deletions configs/game_suites/slimevolley.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
schema_version = "game-suite/2.1"
version = "1.0.0"
tier = "smoke"
name = "games-slimevolley-v1.0.0"
files_images = ["connection-files", "game-files", "slimevolley-files"]

[[tasks]]
name = "slimevolley-pixel-vs-baseline-i01-standard"
benchmark = "slimevolley"
family = "pixel-vs-baseline"
20 changes: 20 additions & 0 deletions docs/slimevolley_exam.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# SlimeVolley practice and scored match

Run from the repository root with the project's Harbor environment and Docker Engine 29. If the SlimeVolley files image is unavailable in your registry or local cache, run `python scripts/files_image.py build slimevolley-files` first. Choose an output directory outside the checkout. A Docker daemon running on another host needs access to that directory through the same filesystem path.

```sh
# Verify both scenarios and the saved practice controller at a shortened cutoff.
python scripts/run_slimevolley_exam.py --smoke --output /path/to/new-smoke-output

# Run one coding agent with the full 600-second practice budget.
python scripts/run_slimevolley_exam.py \
--agent-config configs/harbor/claude-deepseek.json \
--allow-agent-host api.deepseek.com \
--output /path/to/new-exam-output
```

The agent config supplies exactly one agent. The runner sets the task, resource limits, timeout, and one attempt. Practice ends when the agent finishes or its 600 seconds expire. A fresh container launches the saved `gen.py` for up to 120 seconds with the public pixel client. If that file is missing, the evaluator selects `practice_gen.py` from the same collected output directory. The evaluator freezes the selected file under `official/gen.py`. A deterministic `idle` action completes the remaining frames if there is no usable selected file or the controller stops early.

Practice slots `A` and `B` are fixed. The runner samples a separate hidden seed before practice and excludes both practice seeds. For experiments comparing multiple agents on the same held-out scenario, pass `--official-seed-file` with a private file containing one integer. Every run needs a new output directory. Keep the seed file and run logs inaccessible to the practice agents.

Read `exam.json` for the independently verified official score, controller outcome, the original filename in `submission_source`, and controller/idle frame counts. The snapshot and scoring evidence are under `official/`, including `official/evidence/replay.mp4`. The Harbor job under `practice-job/` tracks the rehearsal and submission only. A simulator or evaluation infrastructure failure invalidates the run. The frozen single-match standard task is available separately through the regular SlimeVolley suite.
8 changes: 8 additions & 0 deletions game_first_exam/benchmarks/slimevolley/SOURCE.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"repository": "https://github.com/hardmaru/slimevolleygym",
"commit": "8ac22434fc5a587a3395311f7854aeda17d10303",
"archive_url": "https://codeload.github.com/hardmaru/slimevolleygym/tar.gz/8ac22434fc5a587a3395311f7854aeda17d10303",
"archive_sha256": "07e285d85edb443ecd602132f7ed72d42ff2580bca5854431882407b224d5ec8",
"license": "Apache-2.0",
"modifications": "none"
}
66 changes: 66 additions & 0 deletions game_first_exam/benchmarks/slimevolley/adapter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
"""Native SlimeVolley pixel play against the built-in left-side policy."""

from importlib.metadata import version

from slimevolleygym.slimevolley import SlimeVolleyAtariEnv
from contracts import Capabilities, Transition
from encoding import png, state_hash

ACTIONS = ("idle", "left", "left_jump", "jump", "right_jump", "right")


class Adapter:
def __init__(self, instance, assets=None):
for package, expected in instance["engine_versions"].items():
if version(package) != expected:
raise ValueError(f"SlimeVolley dependency version mismatch: {package}")
self.env = SlimeVolleyAtariEnv()
if self.env.t_limit != instance["native_max_steps"] or self.env.action_space.n != len(ACTIONS):
raise ValueError("SlimeVolley native limits or actions changed")
self.env.seed(instance["seed"])
self.image = self.env.reset()
self.ended = False

def spec(self):
return {
"adapter_version": "1.0.0",
"capabilities": Capabilities(images=True, action_mode="enum", native_truncation=True).to_dict(),
"action_schema": {"type": "string", "enum": list(ACTIONS)},
"observation": "Native 168×84 RGB frame from the right player's match.",
}

def observe(self):
return {"image_png_base64": png(self.image)}

def step(self, action):
if self.ended:
raise ValueError("episode closed")
self.image, reward, self.ended, info = self.env.step(ACTIONS.index(action))
terminated = min(info["ale.lives"], info["ale.otherLives"]) == 0
return Transition(float(reward), terminated, bool(self.ended and not terminated))

def success(self):
game = self.env.game
return self.ended and game.agent_right.life > game.agent_left.life

def metrics(self):
game = self.env.game
right, left = game.agent_right.life, game.agent_left.life
return {"native_return": right - left, "right_lives": right, "left_lives": left,
"points_for": 5 - left, "points_against": 5 - right, "native_steps": self.env.t}

def fingerprint(self):
game = self.env.game
players = [vars(player) | {"state": vars(player.state)}
for player in (game.agent_right, game.agent_left)]
return state_hash({
"players": players, "ball": vars(game.ball), "delay": game.delayScreen.life,
"opponent_rnn": self.env.policy.outputState, "steps": self.env.t,
"rng": game.np_random.bit_generator.state,
})

def frame(self):
return self.image

def close(self):
self.env.close()
145 changes: 145 additions & 0 deletions game_first_exam/benchmarks/slimevolley/exam_server.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
"""Trusted service for the SlimeVolley practice and scored phases."""
import json
import os
import signal
import sys
import tempfile
from http.server import HTTPServer
from pathlib import Path
from uuid import uuid4

from adapter import Adapter
from server import EnvironmentFault, Game, Handler

DATA = Path("/data")
ASSETS = Path("/srv")


class PracticeGame(Game):
def record_frame(self):
# The public pixel stream remains available. Only the scored match is recorded.
pass


class PracticeServer(HTTPServer):
def __init__(self, instances, scratch):
super().__init__(("0.0.0.0", 8000), PracticeHandler)
self.instances, self.scratch = instances, scratch
self.summary = {slot: {"episodes": 0, "steps": 0, "errors": 0} for slot in instances}
self.game = None
self.start("A")

def finish_episode(self):
if self.game is not None:
self.game.close()
totals = self.summary[self.slot]
totals["steps"] += self.game.steps
totals["errors"] += int(not self.game.final["result_valid"])
self.episode_dir.cleanup()
self.game = None

def start(self, slot):
self.finish_episode()
self.slot = slot
self.episode_dir = tempfile.TemporaryDirectory(dir=self.scratch)
self.game = PracticeGame.open(Adapter, self.instances[slot], ASSETS, self.episode_dir.name)
self.summary[slot]["episodes"] += 1
return {"slot": slot, **self.game.observe()}


class PracticeHandler(Handler):
def do_POST(self):
if self.path != "/practice/start":
return super().do_POST()
try:
length = int(self.headers.get("Content-Length", "0"))
if not 0 < length <= 64:
raise ValueError
body = json.loads(self.rfile.read(length))
if not isinstance(body, dict) or set(body) != {"slot"} or body["slot"] not in ("A", "B"):
raise ValueError
except ValueError:
return self.reply(400, {"error": "provide exactly one slot: A or B"})
self.reply(200, self.server.start(body["slot"]))


def serve(make_server, seal):
# Keep all simulator work out of the signal handlers.
collecting = False
stopping = False

def stop(signum, _frame):
nonlocal collecting, stopping
if signum == signal.SIGUSR1:
collecting = True
else:
stopping = True

DATA.mkdir(parents=True, exist_ok=True)
signal.signal(signal.SIGUSR1, stop)
signal.signal(signal.SIGTERM, stop)
with make_server() as server:
server.timeout = 0.25
(DATA / "server.pid").write_text(str(os.getpid()))
while not collecting and not stopping:
server.handle_request()
# After collection starts, stop accepting public requests before computing evidence.
if collecting:
seal(server)
(DATA / "collection.ready").touch()
# Harbor still needs to copy the artifacts from this container.
while not stopping:
signal.pause()


def practice():
instances = json.loads((ASSETS / "practice-instances.json").read_text())

def seal(server):
server.finish_episode()
(DATA / "practice.json").write_text(json.dumps(server.summary) + "\n")

with tempfile.TemporaryDirectory() as scratch:
serve(lambda: PracticeServer(instances, scratch), seal)


def official():
instance = json.loads((ASSETS / "instance.json").read_text())

def make_server():
server = HTTPServer(("0.0.0.0", 8000), Handler)
# The host enforces the policy deadline. Keep time available for trusted idle steps.
server.game = Game.open(Adapter, instance, ASSETS, DATA, wall_clock=3600)
return server

def seal(server):
game = server.game
controller_steps = game.steps
try:
while game.final is None:
game.submit({"action": "idle", "expected_step": game.steps, "request_id": uuid4().hex})
except EnvironmentFault:
pass # The existing grader rejects the engine's invalid verdict.
finally:
game.close()
result = {"controller_steps": controller_steps, "idle_steps": game.steps - controller_steps}
(DATA / "rollout.json").write_text(json.dumps(result) + "\n")

serve(make_server, seal)


def instances():
base = json.loads((ASSETS / "instance.json").read_text())
result = {}
for slot, seed in json.load(sys.stdin).items():
instance = {**base, "seed": seed}
adapter = Adapter(instance, ASSETS)
try:
result[slot] = {**instance, "initial_state_sha256": adapter.fingerprint()}
finally:
adapter.close()
print(json.dumps(result))


if __name__ == "__main__":
{"practice": practice, "official": official, "instances": instances}[sys.argv[1]]()
31 changes: 31 additions & 0 deletions game_first_exam/benchmarks/slimevolley/instance_schema.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
"""Frozen native pixel match configuration, shared by preflight, sim and verifier."""

from config_schema import validate_engine_versions

SCHEMA_VERSION = "1.0.0"
BENCHMARK = "slimevolley"
FIELDS = {"engine_versions", "engine_commit", "native_max_steps", "opponent"}
METRICS = {"native_return"}
PROFILES = {"native-rgb-v1"}
REDUCERS = {("family_macro", "1.0.0")}
ENGINE_COMMIT = "8ac22434fc5a587a3395311f7854aeda17d10303"
ENGINE_VERSIONS = {
"slimevolleygym": "0.1.0",
"gym": "0.25.0",
"numpy": "1.26.4",
"opencv-python-headless": "4.11.0.86",
}


def validate(value):
validate_engine_versions(value["engine_versions"], ENGINE_VERSIONS)
if value["engine_commit"] != ENGINE_COMMIT or value["opponent"] != "native-baseline":
raise ValueError("unsupported SlimeVolley engine or opponent")
if (value["env_id"] != "SlimeVolleyNoFrameskip-v0" or value["family"] != "pixel-vs-baseline"
or type(value["native_max_steps"]) is not int or value["native_max_steps"] != 3000
or value["max_steps"] is not None):
raise ValueError("unsupported native SlimeVolley match configuration")
if value["capabilities"] != {
"images": True, "action_mode": "enum", "timing": "action-stepped", "native_truncation": True,
}:
raise ValueError("SlimeVolley requires the native RGB action-stepped profile")
22 changes: 22 additions & 0 deletions game_first_exam/benchmarks/slimevolley/metric_rules.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
"""Validate the native match result and Game Exam's end flags."""


def validate_metrics(final, instance):
metrics = final["metrics"]
right, left = (metrics[key] for key in ("right_lives", "left_lives"))
if any(type(lives) is not int or not 0 <= lives <= 5 for lives in (right, left)) or right == left == 0:
raise ValueError("invalid SlimeVolley lives")
steps = final["steps"]
if (type(metrics["native_steps"]) is not int or metrics["native_steps"] != steps
or not 5 * 2 - right - left <= steps <= instance["native_max_steps"]):
raise ValueError("invalid SlimeVolley native step count")
terminated = min(right, left) == 0
truncated = not terminated and steps == instance["native_max_steps"]
if (final["terminated"], final["truncated"]) != (terminated, truncated):
raise ValueError("inconsistent SlimeVolley ending")
if final["success"] != ((terminated or truncated) and right > left):
raise ValueError("inconsistent SlimeVolley success")
expected = {"points_for": 5 - left, "points_against": 5 - right, "native_return": right - left}
if (any(type(metrics[key]) is not int or metrics[key] != value for key, value in expected.items())
or final["return"] != expected["native_return"]):
raise ValueError("inconsistent SlimeVolley score")
Loading