Download check.py from HuggingFaceSwarms/s3-maze: direct link, hf CLI and curl.
- Browser
- Download file 48.3 kB
-
https://huggingface.co/datasets/HuggingFaceSwarms/s3-maze/resolve/refs%2Fpr%2F1/check.py
- Command line
-
hf download hf://datasets/HuggingFaceSwarms/s3-maze@refs/pr/1/check.py
-
curl -L -o check.py https://huggingface.co/datasets/HuggingFaceSwarms/s3-maze/resolve/refs%2Fpr%2F1/check.py
48.3 kB
| # /// script | |
| # requires-python = ">=3.12" | |
| # dependencies = ["harbor==0.25.0"] | |
| # /// | |
| """s3-maze's checks that need no model (huggingface/legion#115, section 5): | |
| uv run check.py --env podman # all of them; the Trials in rootless podman (README: "Checks") | |
| uv run check.py --env docker # the Trials in local docker | |
| uv run check.py --env none # without the Trials (no container engine needed) | |
| 1. Generator: generate.py reproduces tasks/ byte for byte from its seed, and another seed gives | |
| other trees, which record that seed in their task.toml and regenerate from it. Each of the | |
| 32 trees has 391 rooms with distinct labels of one fixed length, is a tree (390 two-way | |
| doors, every room reachable from the start), has 27 dead ends, all 30 moves from the start, | |
| one of which is the exit; the shortest path is 30 moves and a full depth-first search | |
| through the service's engine 780. Door orders are shuffled (the way back | |
| is not always listed in the same place), and the exits fall on many positions of the search | |
| order. Every task's service, agent and grader files are template/'s, its image tags are its | |
| files' digests, and the budget is the same in the tree, the grader, the instruction and | |
| task.toml. | |
| 2. The maze service, run as it runs in its container (service.py over HTTP on this machine): | |
| it starts in the start room with the whole budget; a move into a room that isn't one of the | |
| current room's doors is refused (the exit from the start, a room two doors away, the room | |
| itself, a number, an object, a long string, a malformed body) and costs nothing; once the | |
| budget is spent every move is refused, a door included; at the exit every move is refused. | |
| No route reveals the tree or the exit: every other path and method answers a bare 404, and | |
| no answer names a room other than the current one and its doors (or what the agent asked | |
| for); the exit is named only once the agent stands in it. The move log has one record per | |
| move request, refused ones included, each with agent, from, to and time, and its accepted | |
| moves are the walk. success.py says false until the exit is reached | |
| and true after, and false for a missing or linked state file; export.py writes the service's | |
| record for the grader; a restarted service resumes the walk. The `maze` command prints the | |
| service's JSON and exits 0, 1 for a refused move, 2 for a usage error. | |
| 3. Graders, as Harbor runs them (tests/test.sh on the evidence export.py wrote), on every tree: | |
| the oracle (solution/solve.sh, walking the shortest path through the `maze` command) scores | |
| 1, and a walk that never reaches the exit scores 0. On one tree, more walks and forgeries | |
| score 0: the budget spent without the exit, no move at all, a forged final.json (the exit | |
| claimed but not in the log, no `exported_by`, another tree's hash, another start, another | |
| budget, the move count changed), a forged log (a jump between rooms that aren't adjacent in | |
| the walk, the exit reached in more moves than the budget), another tree's winning evidence, | |
| evidence as a symlink or a hardlink to a winning copy, a symlinked /evidence, a directory, a | |
| FIFO (which must not hang the grader), a missing file, invalid JSON and NaN; and a losing | |
| walk with Python made to read any record as a win: a json.py in the grader's working | |
| directory or on PYTHONPATH, a sitecustomize on PYTHONPATH, a usercustomize or a .pth file in | |
| the user site; and a reward.txt or reward.json left as 1, or as a link, in the verifier's | |
| folder. | |
| 4. No-cheat, in the files: the agent's build context (environment/agent/) holds only its | |
| Dockerfile and the `maze` command, and names no room; nor do the instruction, task.toml or | |
| the compose file; the exit is named only in environment/maze/tree.json, tests/expected.json | |
| and solution/solve.sh; and no folder beside tasks/ holds a tree. | |
| 5. Trials (`--env`), on maze-t01, with agents that need no model: | |
| - a walker checks success.py in the maze service (false), walks the shortest path | |
| with `maze move`, checks it again (true), and scores 1; the verifier's folder then holds | |
| the move log and the export; | |
| - Harbor's oracle agent (solution/solve.sh) scores 1; | |
| - a probe looks around the agent's container while it works: no file, process environment | |
| or command line names any room but the start and its doors, nor the tree's hash; the maze | |
| service answers only its two routes; there is no tests/ or solution/. Then it plants a | |
| winning record (from a local walk of this tree) in /evidence, /logs/artifacts and | |
| /logs/verifier, a reward.txt of 1, a json.py and a sitecustomize, makes three moves | |
| short of the exit, and scores 0. | |
| `--env` takes a Harbor environment type (podman, docker) or an import path. | |
| """ | |
| import argparse | |
| import asyncio | |
| import base64 | |
| import hashlib | |
| import json | |
| import os | |
| import re | |
| import shlex | |
| import shutil | |
| import socket | |
| import subprocess | |
| import sys | |
| import tempfile | |
| import time | |
| import urllib.error | |
| import urllib.request | |
| from pathlib import Path | |
| HERE = Path(__file__).resolve().parent | |
| sys.dont_write_bytecode = True # nothing new in tasks/ or template/ | |
| sys.path.insert(0, str(HERE)) | |
| sys.path.insert(0, str(HERE / "template" / "environment" / "maze")) | |
| import generate as g # noqa: E402 | |
| from engine import Maze, Walk # noqa: E402 | |
| LABEL = re.compile(rf"R\d{{{g.DIGITS}}}") | |
| PROBE_TASK = "maze-t01" | |
| failures: list[str] = [] | |
| def check(ok: bool, what: str) -> None: | |
| if not ok: | |
| failures.append(what) | |
| def tasks() -> list[Path]: | |
| return sorted((HERE / "tasks").iterdir()) | |
| def tree_of(task: Path) -> dict: | |
| return json.loads((task / "environment" / "maze" / "tree.json").read_text()) | |
| def files(root: Path) -> dict[str, bytes]: | |
| """Relative path -> bytes for the generated files under root (not their modes: a download | |
| from the Hub has none).""" | |
| return {str(p.relative_to(root)): p.read_bytes() | |
| for p in sorted((root / "tasks").rglob("*")) | |
| if p.is_file() and "__pycache__" not in p.parts} | |
| def distances(t: dict) -> dict[str, int]: | |
| out, queue = {t["start"]: 0}, [t["start"]] | |
| for room in queue: | |
| for door in t["doors"][room]: | |
| if door not in out: | |
| out[door] = out[room] + 1 | |
| queue.append(door) | |
| return out | |
| def full_search(t: dict) -> int: | |
| """Moves for a depth-first search of the whole tree through the engine, back to the start.""" | |
| walk = Walk(Maze({**t, "exit": None, "budget": 10 ** 6})) | |
| seen, path = {walk.room}, [walk.room] | |
| while True: | |
| unexplored = [d for d in walk.look()["doors"] if d not in seen] | |
| if unexplored: | |
| target = unexplored[0] | |
| path.append(target) | |
| elif len(path) > 1: | |
| path.pop() | |
| target = path[-1] | |
| else: | |
| return walk.moves | |
| _, why = walk.move(target) | |
| check(why is None, f"the engine refused a search move ({why})") | |
| seen.add(target) | |
| def check_generator() -> None: | |
| with tempfile.TemporaryDirectory() as d: | |
| shutil.copytree(HERE / "template", Path(d) / "template") | |
| g.generate(Path(d)) | |
| check(files(Path(d)) == files(HERE), "generate.py does not reproduce the committed tasks/") | |
| other = g.SEED + 1 # the seed a task records regenerates its tree | |
| g.generate(Path(d), seed=other) | |
| for t, tree in enumerate(g.trees(other), 1): | |
| task = Path(d) / "tasks" / g.task_name(t) | |
| recorded = re.findall(r"^seed = (\d+)$", (task / "task.toml").read_text(), re.M) | |
| check(recorded == [str(other)] and tree_of(task) == tree | |
| and g.trees(int(recorded[0]))[t - 1] == tree, | |
| f"seed {other}: {task.name} records seed {recorded}, not its own") | |
| drawn = g.trees() | |
| check(drawn == g.trees(), "the same seed gave other trees") | |
| check(all(a["doors"] != b["doors"] for a, b in zip(drawn, g.trees(g.SEED + 1), strict=True)), | |
| "another seed gave the same trees") | |
| check([p.name for p in tasks()] == [g.task_name(t) for t in range(1, 33)], | |
| "tasks/ is not maze-t01 .. maze-t32") | |
| template = {f: g.template(f) for f in ("environment/agent", "environment/maze", "tests")} | |
| exit_ranks, back_positions = set(), set() | |
| for t, task in enumerate(tasks(), 1): | |
| tree = tree_of(task) | |
| name = task.name | |
| check(tree == drawn[t - 1] | {"budget": g.BUDGET}, f"{name}: tree.json is not generate's") | |
| doors = tree["doors"] | |
| rooms = list(doors) | |
| check(len(rooms) == 391 and len(set(rooms)) == 391, f"{name}: not 391 distinct rooms") | |
| check(all(LABEL.fullmatch(r) for r in rooms), f"{name}: a label isn't R and digits") | |
| pairs = {(a, b) for a in rooms for b in doors[a]} | |
| check(len(pairs) == 2 * 390 and all((b, a) in pairs for a, b in pairs) | |
| and all(len(set(doors[r])) == len(doors[r]) for r in rooms), | |
| f"{name}: not 390 two-way doors") | |
| dist = distances(tree) | |
| check(len(dist) == 391, f"{name}: not every room is reachable from the start") | |
| ends = [r for r in rooms if len(doors[r]) == 1 and r != tree["start"]] | |
| check(len(ends) == 27 and all(dist[r] == 30 for r in ends), | |
| f"{name}: not 27 dead ends 30 moves from the start") | |
| check(tree["exit"] in ends, f"{name}: the exit is not a dead end") | |
| check(len(g.shortest_path(tree)) == 30 == dist[tree["exit"]], | |
| f"{name}: the shortest path is not 30 moves") | |
| check(full_search(tree) == 780, f"{name}: a full search is not 780 moves") | |
| order, stack, seen = [], [tree["start"]], {tree["start"]} | |
| while stack: # the dead ends in listed depth-first order, and where the way back is | |
| room = stack.pop() | |
| if room in ends: | |
| order.append(room) | |
| onward = [d for d in doors[room] if d not in seen] | |
| for door in onward: | |
| seen.add(door) | |
| back_positions.add((len(doors[door]), doors[door].index(room))) | |
| stack += onward[::-1] | |
| exit_ranks.add(order.index(tree["exit"])) | |
| for folder, expected in template.items(): | |
| have = {str(p.relative_to(task / folder)): p.read_bytes() | |
| for p in sorted((task / folder).rglob("*")) if p.is_file()} | |
| extra = {"environment/maze": {"tree.json"}, "tests": {"expected.json"}}.get( | |
| folder, set()) | |
| check({k: v for k, v in have.items() if k not in extra} == expected, | |
| f"{name}: {folder} is not template/'s") | |
| check(set(have) - set(expected) == extra, f"{name}: {folder} holds {set(have)}") | |
| compose = (task / "environment" / "docker-compose.yaml").read_text() | |
| maze = g.template("environment/maze") | { | |
| "tree.json": (task / "environment" / "maze" / "tree.json").read_bytes()} | |
| check(f"s3-maze-agent:{g.digest(template['environment/agent'])}" in compose | |
| and f"s3-maze-service:{name}-{g.digest(maze)}" in compose, | |
| f"{name}: an image tag is not its files' digest") | |
| expected = json.loads((task / "tests" / "expected.json").read_text()) | |
| check(expected == {"start": tree["start"], "exit": tree["exit"], "budget": g.BUDGET, | |
| "tree_sha256": hashlib.sha256(maze["tree.json"]).hexdigest()}, | |
| f"{name}: expected.json does not match the tree") | |
| check(f"at most {g.BUDGET} moves" in (task / "instruction.md").read_text() | |
| and f"move_budget = {g.BUDGET}\n" in (task / "task.toml").read_text() | |
| and tree["budget"] == g.BUDGET, f"{name}: the budget differs between its files") | |
| check({(4, k) for k in range(4)} | {(2, 0), (2, 1)} <= back_positions, | |
| "the way back is not listed in every place a junction or corridor room has") | |
| check(len(exit_ranks) >= 10, f"the exits fall on only {len(exit_ranks)} search positions") | |
| # ------------------------------------------------------------------ the service, as it runs | |
| def free_port() -> int: | |
| with socket.socket() as s: | |
| s.bind(("127.0.0.1", 0)) | |
| return s.getsockname()[1] | |
| class Service: | |
| """service.py of a task, on this machine, with its state in `state` (a fresh one each).""" | |
| def __init__(self, task: Path, state: Path, tree: dict | None = None): | |
| self.task, self.state = task, state | |
| maze_dir = task / "environment" / "maze" | |
| self.tree_path = maze_dir / "tree.json" | |
| if tree is not None: # e.g. a smaller budget | |
| self.tree_path = state.parent / f"{state.name}-tree.json" | |
| self.tree_path.write_text(json.dumps(tree)) | |
| self.port = free_port() | |
| self.url = f"http://127.0.0.1:{self.port}" | |
| self.env = {**os.environ, "MAZE_TREE": str(self.tree_path), "MAZE_STATE_DIR": str(state), | |
| "MAZE_PORT": str(self.port), "MAZE_AGENT": "check-maze-t01-agent-001-t1__env"} | |
| self.process = None | |
| self.answers: list[tuple[str, int, str]] = [] # (what was asked, status, body) | |
| def __enter__(self): | |
| self.start() | |
| return self | |
| def start(self): | |
| script = self.task / "environment" / "maze" / "service.py" | |
| self.process = subprocess.Popen([sys.executable, "-I", "-S", str(script)], env=self.env, | |
| stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) | |
| deadline = time.monotonic() + 15 | |
| while time.monotonic() < deadline: | |
| try: | |
| with socket.create_connection(("127.0.0.1", self.port), timeout=1): | |
| return | |
| except OSError: | |
| time.sleep(0.1) | |
| raise RuntimeError(f"the service did not start: {self.process.stderr.read()[-500:]}") | |
| def stop(self): | |
| self.process.terminate() | |
| self.process.wait(10) | |
| def __exit__(self, *exc): | |
| self.stop() | |
| def request(self, method: str, path: str, body: bytes | None = None) -> tuple[int, dict]: | |
| request = urllib.request.Request(self.url + path, data=body, method=method, | |
| headers={"Content-Type": "application/json"}) | |
| try: | |
| with urllib.request.urlopen(request, timeout=10) as response: | |
| status, text = response.status, response.read().decode() | |
| except urllib.error.HTTPError as e: | |
| status, text = e.code, e.read().decode() | |
| self.answers.append((f"{method} {path} {body!r}", status, text)) | |
| try: | |
| return status, json.loads(text) if text else {} | |
| except ValueError: | |
| return status, {"raw": text} | |
| def look(self) -> dict: | |
| return self.request("GET", "/look")[1] | |
| def move(self, room) -> tuple[int, dict]: | |
| return self.request("POST", "/move", json.dumps({"room": room}).encode()) | |
| def export(self, evidence: Path) -> None: | |
| env = {**self.env, "MAZE_EVIDENCE_DIR": str(evidence)} | |
| subprocess.run([sys.executable, "-I", "-S", | |
| str(self.task / "environment" / "maze" / "export.py")], | |
| env=env, check=True, capture_output=True, timeout=30) | |
| def success(self) -> dict: | |
| out = subprocess.run([sys.executable, "-I", "-S", | |
| str(self.task / "environment" / "maze" / "success.py")], | |
| env=self.env, check=True, capture_output=True, text=True, timeout=30) | |
| return json.loads(out.stdout) | |
| def log(self) -> list[dict]: | |
| path = self.state / "moves.jsonl" | |
| return [json.loads(x) for x in path.read_text().splitlines()] if path.exists() else [] | |
| def visible(answer: str, tree: dict) -> set[str]: | |
| return set(LABEL.findall(answer)) & set(tree["doors"]) | |
| def walk_to(service: Service, rooms: list[str]) -> None: | |
| for room in rooms: | |
| status, _ = service.move(room) | |
| check(status == 200, f"a move along the path was refused ({room})") | |
| def dead_end_walk(tree: dict, moves: int) -> list[str]: | |
| """A walk of `moves` moves that never reaches the exit: into a branch that doesn't hold it, | |
| back and forth along its corridor.""" | |
| on_path = set(g.shortest_path(tree)) | |
| first = next(d for d in tree["doors"][tree["start"]] if d not in on_path) | |
| walk = [] | |
| while len(walk) < moves: | |
| walk += [first, tree["start"]] | |
| return walk[:moves] | |
| def check_service(work: Path) -> dict: | |
| task = HERE / "tasks" / PROBE_TASK | |
| tree = tree_of(task) | |
| doors, start, exit_room = tree["doors"], tree["start"], tree["exit"] | |
| path = g.shortest_path(tree) | |
| report = {} | |
| with Service(task, work / "state-a") as s: | |
| here = s.look() | |
| check(here == {"room": start, "doors": doors[start], "exit": False, "arrived_from": None, | |
| "moves_left": g.BUDGET}, f"the start's observation is wrong: {here}") | |
| check(s.success()["success"] is False, "success_check is true before any move") | |
| two_away = next(r for r, d in distances(tree).items() if d == 2) | |
| refused = {"the exit": exit_room, "a room two doors away": two_away, "itself": start, | |
| "a number": 5, "an object": {"room": doors[start][0]}, | |
| "a long string": "R" * 1000, "a list": [doors[start][0]]} | |
| for case, room in refused.items(): | |
| status, body = s.move(room) | |
| check(status == 409 and "error" in body and body.get("room") == start, | |
| f"a move into {case} was not refused ({status})") | |
| too_long = json.dumps({"room": "R" * 5000}).encode() | |
| for case, raw in {"no body": b"", "not JSON": b"{", "no room": b'{"to": "R1"}', | |
| "a list": b"[]", "a body over 4 KiB": too_long}.items(): | |
| status, _ = s.request("POST", "/move", raw or None) | |
| check(status == 400, f"a malformed move ({case}) was not refused ({status})") | |
| check(s.look()["moves_left"] == g.BUDGET, "a refused move cost a move") | |
| # every other route answers a bare 404 | |
| for method in ("GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"): | |
| for p in ("/", "/tree", "/state", "/exit", "/doors", "/map", "/private/tree.json", | |
| "/look/", "/look?room=" + exit_room, "/move/" + exit_room, "/health", | |
| "/../private/tree.json", "/%2e%2e/private/tree.json", "/moves.jsonl"): | |
| if (method, p) in (("GET", "/look"), ("POST", "/move")): | |
| continue | |
| status, body = s.request(method, p, b"{}" if method in ("POST", "PUT") else None) | |
| check(status in (404, 501) and not visible(json.dumps(body), tree), | |
| f"{method} {p} answered {status} {body}") | |
| # walk the path; every answer names only the current room and its doors | |
| walk_to(s, path[:-1]) | |
| check(s.success()["success"] is False, "success_check is true before the exit") | |
| walk_to(s, path[-1:]) | |
| here = s.look() | |
| check(here["exit"] is True and here["room"] == exit_room | |
| and here["moves_left"] == g.BUDGET - 30, f"the exit's observation is wrong: {here}") | |
| status, body = s.move(here["doors"][0]) | |
| check(status == 409, "a move out of the exit was accepted") | |
| verdict = s.success() | |
| check(verdict["success"] is True and verdict["evidence"]["exit_reached"] is True, | |
| f"success_check is not true at the exit: {verdict}") | |
| log = s.log() | |
| requests = sum(1 for asked, _, _ in s.answers if asked.startswith("POST /move ")) | |
| check(len(log) == requests, f"the move log has {len(log)} records for {requests} requests") | |
| check(all({"agent", "from", "to", "time", "ok"} <= set(r) for r in log) | |
| and all(r["agent"] == "check-maze-t01-agent-001-t1" for r in log), | |
| "a move record lacks agent, from, to or time") | |
| ok = [r for r in log if r["ok"]] | |
| check([r["to"] for r in ok] == path and [r["from"] for r in ok] == [start] + path[:-1], | |
| "the log's accepted moves are not the walk") | |
| # what the service said, at every step: only the room and its doors, or what was asked | |
| room_then = start | |
| for asked, status, text in s.answers: | |
| named = visible(text, tree) - set(LABEL.findall(asked)) | |
| allowed = {room_then, *doors[room_then]} | |
| if status == 200 and asked.startswith("POST /move"): | |
| room_then = json.loads(text)["room"] | |
| allowed |= {room_then, *doors[room_then]} | |
| check(named <= allowed, f"{asked} named {sorted(named - allowed)}") | |
| said_exit = '"exit": true' in text | |
| check(said_exit == (room_then == exit_room and status in (200, 409)), | |
| f"{asked}: the service said exit: {said_exit} in {room_then}") | |
| s.export(work / "evidence-a") | |
| final = json.loads((work / "evidence-a" / "final.json").read_text()) | |
| check(final["reached"] is True and final["exported_by"] == "maze" and final["moves"] == 30, | |
| f"the export is wrong: {final}") | |
| report["requests"] = requests | |
| # a restart resumes the walk | |
| s.stop() | |
| s.start() | |
| check(s.look()["room"] == exit_room, "a restarted service lost the walk") | |
| # the budget: a tree with a budget of 4 | |
| with Service(task, work / "state-b", tree | {"budget": 4}) as s: | |
| walk_to(s, dead_end_walk(tree, 4)) | |
| status, body = s.move(s.look()["doors"][0]) | |
| check(status == 409 and body["moves_left"] == 0 and "No moves left" in body["error"], | |
| "a move past the budget was not refused") | |
| check(s.log()[-1]["refused"] == "no_moves_left", "the refused move past the budget " | |
| "is not logged as such") | |
| # success_check never counts a missing or linked state | |
| with tempfile.TemporaryDirectory() as d: | |
| env = {**os.environ, "MAZE_STATE_DIR": d} | |
| script = str(task / "environment" / "maze" / "success.py") | |
| out = json.loads(subprocess.run([sys.executable, "-I", "-S", script], env=env, text=True, | |
| capture_output=True, check=True).stdout) | |
| check(out["success"] is False, "success_check is true without a state") | |
| (Path(d) / "state.json").symlink_to(work / "state-a" / "state.json") | |
| out = json.loads(subprocess.run([sys.executable, "-I", "-S", script], env=env, text=True, | |
| capture_output=True, check=True).stdout) | |
| check(out["success"] is False, "success_check followed a linked state file") | |
| # the `maze` command | |
| with Service(task, work / "state-c") as s: | |
| cli = [sys.executable, str(task / "environment" / "agent" / "maze")] | |
| env = {**os.environ, "MAZE_URL": s.url} | |
| run = lambda *a: subprocess.run(cli + list(a), env=env, capture_output=True, text=True, # noqa: E731 | |
| timeout=60) | |
| out = run("look") | |
| check(out.returncode == 0 and json.loads(out.stdout)["room"] == start, "maze look failed") | |
| out = run("move", path[0]) | |
| check(out.returncode == 0 and json.loads(out.stdout)["room"] == path[0], "maze move failed") | |
| out = run("move", exit_room) | |
| check(out.returncode == 1 and "error" in json.loads(out.stdout), | |
| "a refused maze move did not exit 1") | |
| check(run("jump").returncode == 2 and run().returncode == 2, "maze's usage is not exit 2") | |
| return report | |
| # ------------------------------------------------------------------ the graders | |
| def evidence(task: Path, work: Path, name: str, rooms: list[str], tree: dict | None = None, | |
| cli: bool = False) -> Path: | |
| """The service's export after a walk through `rooms` (with solution/solve.sh if `cli`).""" | |
| with Service(task, work / f"state-{name}", tree) as s: | |
| if cli: | |
| bin_dir = work / f"bin-{name}" | |
| bin_dir.mkdir() | |
| shutil.copy(task / "environment" / "agent" / "maze", bin_dir / "maze") | |
| (bin_dir / "maze").chmod(0o755) | |
| env = {**os.environ, "MAZE_URL": s.url, "PATH": f"{bin_dir}:{os.environ['PATH']}"} | |
| subprocess.run(["bash", str(task / "solution" / "solve.sh")], env=env, check=True, | |
| capture_output=True, timeout=300) | |
| else: | |
| for room in rooms: | |
| s.move(room) | |
| s.export(work / f"evidence-{name}") | |
| return work / f"evidence-{name}" | |
| def grade(task: Path, source: Path | None, cheat=None, isolated: bool = True) -> int: | |
| """tests/test.sh as Harbor runs it in the verifier's container: /evidence holds what was | |
| collected from the maze service (`source`), /tests the task's tests/. `cheat(root)` may | |
| change what's there first and return the grader's extra `env` and working directory.""" | |
| with tempfile.TemporaryDirectory() as d: | |
| root = Path(d).resolve() | |
| evidence_dir, tests, verifier = root / "evidence", root / "tests", root / "verifier" | |
| if source is not None: | |
| shutil.copytree(source, evidence_dir) | |
| shutil.copytree(task / "tests", tests) | |
| verifier.mkdir() | |
| extra = cheat(root) if cheat else None | |
| extra = extra if isinstance(extra, dict) else {} | |
| env = {**os.environ, "EVIDENCE_DIR": str(evidence_dir), "VERIFIER_DIR": str(verifier), | |
| **extra.get("env", {})} | |
| command = ["bash", str(tests / "test.sh")] | |
| if not isolated: # the control: test.sh's python3 without -I -S | |
| command = ["python3", str(tests / "grade.py")] | |
| try: | |
| subprocess.run(command, capture_output=True, timeout=60, env=env, | |
| cwd=extra.get("cwd"), check=False) | |
| except subprocess.TimeoutExpired: | |
| return -1 | |
| reward = verifier / "reward.txt" | |
| if reward.is_symlink() or not reward.is_file(): | |
| return -2 | |
| if (verifier / "reward.json").exists(): | |
| return -3 # Harbor would read it first | |
| value = int(reward.read_text().strip()) | |
| if value == 1 and isolated: # the grader keeps the service's record for the metrics | |
| check((verifier / "moves.jsonl").read_bytes() == (evidence_dir / "moves.jsonl") | |
| .read_bytes(), f"{task.name}: the verifier's moves.jsonl is not the export") | |
| return value | |
| # Imported by the grader, either would score 1 whatever the evidence: it rewrites the reward | |
| # as the grader's Python exits. | |
| WIN_AT_EXIT = ("import atexit, os; atexit.register(lambda: open(os.path.join(os.environ[" | |
| "'VERIFIER_DIR'], 'reward.txt'), 'w').write('1'))") | |
| FAKE_JSON = WIN_AT_EXIT + "\nfrom _json import *\n" | |
| PATCH_JSON = WIN_AT_EXIT + "\n" | |
| def edited(name: str, change): | |
| """Change the export's `name` file: `change(text) -> text`.""" | |
| def cheat(root): | |
| path = root / "evidence" / name | |
| path.write_text(change(path.read_text())) | |
| return cheat | |
| def final_with(**fields): | |
| return edited("final.json", lambda t: json.dumps(json.loads(t) | fields)) | |
| def log_with(change): | |
| def apply(text): | |
| records = [json.loads(x) for x in text.splitlines()] | |
| return "".join(json.dumps(r) + "\n" for r in change(records)) | |
| return edited("moves.jsonl", apply) | |
| def replaced(win: Path, *names: str, how: str): | |
| """Evidence files replaced by links to (or a link to the folder of) a winning copy.""" | |
| def cheat(root): | |
| target = root / "win" | |
| shutil.copytree(win, target) | |
| if how == "folder": | |
| shutil.rmtree(root / "evidence") | |
| (root / "evidence").symlink_to(target) | |
| return | |
| for name in names: | |
| (root / "evidence" / name).unlink() | |
| if how == "symlink": | |
| (root / "evidence" / name).symlink_to(target / name) | |
| else: | |
| os.link(target / name, root / "evidence" / name) | |
| return cheat | |
| def user_site(name: str, text: str): | |
| def cheat(root): | |
| env = {"PYTHONUSERBASE": str(root / "userbase")} | |
| site = subprocess.run(["python3", "-c", "import site; print(site.getusersitepackages())"], | |
| env={**os.environ, **env}, capture_output=True, text=True, | |
| check=True).stdout.strip() | |
| Path(site).mkdir(parents=True, exist_ok=True) | |
| (Path(site) / name).write_text(text) | |
| return {"env": env} | |
| return cheat | |
| def planted(name: str, text: str): | |
| def cheat(root): | |
| folder = root / "work" | |
| folder.mkdir(exist_ok=True) | |
| (folder / name).write_text(text) | |
| return {"cwd": folder, "env": {"PYTHONPATH": str(folder)}} | |
| return cheat | |
| def left_in_verifier(name: str, link: bool = False): | |
| def cheat(root): | |
| if link: | |
| (root / "elsewhere").write_text("1") | |
| (root / "verifier" / name).symlink_to(root / "elsewhere") | |
| else: | |
| (root / "verifier" / name).write_text('{"reward": 1}' if name.endswith("json") else "1") | |
| return cheat | |
| def check_graders(work: Path) -> dict: | |
| covered: dict[str, int] = {} | |
| for task in tasks(): | |
| tree = tree_of(task) | |
| win = evidence(task, work, f"{task.name}-oracle", [], cli=True) | |
| check(grade(task, win) == 1, f"{task.name}: the oracle does not score 1") | |
| lose = evidence(task, work, f"{task.name}-lost", dead_end_walk(tree, 40)) | |
| check(grade(task, lose) == 0, f"{task.name}: a walk that never reaches the exit scores") | |
| covered["oracle"] = covered.get("oracle", 0) + 1 | |
| covered["never reaches the exit"] = covered.get("never reaches the exit", 0) + 1 | |
| task, other = HERE / "tasks" / PROBE_TASK, HERE / "tasks" / "maze-t02" | |
| tree = tree_of(task) | |
| path = g.shortest_path(tree) | |
| win = work / f"evidence-{task.name}-oracle" | |
| spent = evidence(task, work, "spent", dead_end_walk(tree, g.BUDGET + 5)) | |
| none = evidence(task, work, "none", []) | |
| other_win = work / f"evidence-{other.name}-oracle" | |
| late = evidence(task, work, "late", dead_end_walk(tree, g.BUDGET - 10) + path, | |
| tree | {"budget": g.BUDGET + 100}) | |
| cases = { | |
| "the budget spent without the exit": (spent, None), | |
| "no move at all": (none, None), | |
| "a forged final.json: the exit claimed": ( | |
| spent, final_with(reached=True, room=tree["exit"])), | |
| "a forged final.json: no exported_by": (win, edited("final.json", lambda t: json.dumps( | |
| {k: v for k, v in json.loads(t).items() if k != "exported_by"}))), | |
| "a forged final.json: another tree's hash": (win, final_with(tree_sha256="0" * 64)), | |
| "a forged final.json: another start": (win, final_with(start=path[0])), | |
| "a forged final.json: another budget": (win, final_with(budget=g.BUDGET + 1)), | |
| "a forged final.json: the move count": (win, final_with(moves=29)), | |
| "a forged log: a jump": (win, log_with(lambda rs: rs[:3] + rs[4:])), | |
| "a forged log: the exit past the budget": ( | |
| late, final_with(budget=g.BUDGET, tree_sha256=json.loads( | |
| (task / "tests" / "expected.json").read_text())["tree_sha256"])), | |
| "another tree's winning evidence": (other_win, None), | |
| "evidence as symlinks to a winning copy": (spent, replaced( | |
| win, "final.json", "moves.jsonl", how="symlink")), | |
| "evidence as hardlinks to a winning copy": (spent, replaced( | |
| win, "final.json", "moves.jsonl", how="hardlink")), | |
| "a symlinked /evidence": (spent, replaced(win, how="folder")), | |
| "a directory": (win, lambda root: ( | |
| (root / "evidence" / "final.json").unlink(), | |
| (root / "evidence" / "final.json").mkdir())), | |
| "a FIFO": (win, lambda root: ( | |
| (root / "evidence" / "moves.jsonl").unlink(), | |
| os.mkfifo(root / "evidence" / "moves.jsonl"))), | |
| "a missing file": (win, lambda root: (root / "evidence" / "moves.jsonl").unlink()), | |
| "no evidence": (None, None), | |
| "invalid JSON": (win, edited("final.json", lambda t: t[:-5])), | |
| "NaN": (win, edited("final.json", lambda t: t.replace('"moves": 30', '"moves": NaN'))), | |
| "a json.py in the working directory and on PYTHONPATH": (spent, planted("json.py", | |
| FAKE_JSON)), | |
| "a sitecustomize on PYTHONPATH": (spent, planted("sitecustomize.py", PATCH_JSON)), | |
| "a usercustomize in the user site": (spent, user_site("usercustomize.py", PATCH_JSON)), | |
| "a .pth file in the user site": (spent, user_site("hook.pth", WIN_AT_EXIT + "\n")), | |
| "a reward.txt of 1 left in the verifier": (spent, left_in_verifier("reward.txt")), | |
| "a reward.json of 1 left in the verifier": (spent, left_in_verifier("reward.json")), | |
| "a reward.txt left as a link": (spent, left_in_verifier("reward.txt", link=True)), | |
| } | |
| for case, (source, cheat) in cases.items(): | |
| covered[case] = 1 | |
| result = grade(task, source, cheat) | |
| check(result == 0, f"{task.name}: {case} scores {result}") | |
| # the controls: an unchanged copy of the winning export still wins, and the Python hooks | |
| # do win when the grader's Python isn't isolated (so it is -I -S that stops them) | |
| check(grade(task, win, edited("final.json", lambda t: t)) == 1, "the control lost") | |
| hooks = ["a json.py in the working directory and on PYTHONPATH", | |
| "a sitecustomize on PYTHONPATH"] | |
| user_site_on = subprocess.run(["python3", "-c", "import site; print(site.ENABLE_USER_SITE)"], | |
| capture_output=True, text=True).stdout.strip() == "True" | |
| if user_site_on: # a venv's python3 has no user site to plant in | |
| hooks += ["a usercustomize in the user site", "a .pth file in the user site"] | |
| covered["controls without -I -S"] = len(hooks) | |
| for case in hooks: | |
| source, cheat = cases[case] | |
| check(grade(task, source, cheat, isolated=False) == 1, | |
| f"control: {case} does not win without -I -S, so the case proves nothing") | |
| return covered | |
| def check_files() -> None: | |
| for task in tasks(): | |
| tree = tree_of(task) | |
| labels = set(tree["doors"]) | |
| agent_files = sorted(p.name for p in (task / "environment" / "agent").iterdir()) | |
| check(agent_files == ["Dockerfile", "maze"], f"{task.name}: the agent's context holds " | |
| f"{agent_files}") | |
| for path in [*(task / "environment" / "agent").iterdir(), task / "instruction.md", | |
| task / "task.toml", task / "environment" / "docker-compose.yaml"]: | |
| named = set(LABEL.findall(path.read_text())) & labels | |
| check(not named, f"{task.name}: {path.relative_to(task)} names {sorted(named)[:3]}") | |
| holders = {str(p.relative_to(task)) for p in task.rglob("*") | |
| if p.is_file() and tree["exit"] in p.read_text(errors="ignore")} | |
| check(holders == {"environment/maze/tree.json", "tests/expected.json", | |
| "solution/solve.sh"}, f"{task.name}: the exit is named in {holders}") | |
| beside = {p.name for p in HERE.iterdir() if p.is_dir()} - { | |
| "tasks", "template", ".cache", "__pycache__", ".git"} | |
| check(not beside, f"folders beside tasks/: {sorted(beside)}") | |
| check(not LABEL.search("".join(p.read_text(errors="ignore") | |
| for p in (HERE / "template").rglob("*") if p.is_file())), | |
| "template/ names a room") | |
| # ------------------------------------------------------------------ Trials | |
| # Runs in the agent's container as `python3 -c PROBE_PY <base64 config>`; its config travels | |
| # encoded, so the labels it looks for are on no command line in the container. | |
| PROBE_PY = r""" | |
| import base64, json, os, re, sys, urllib.request, urllib.error | |
| cfg = json.loads(base64.b64decode(sys.argv[1])) | |
| hidden = cfg["hidden"] | |
| label = re.compile(r"R\d{4}") | |
| def scan(text): | |
| return sorted(set(label.findall(text)) & set(hidden)) | |
| def search(): | |
| found = {} | |
| for top, dirs, names in os.walk("/"): | |
| if top == "/": | |
| dirs[:] = [d for d in dirs if d not in ("proc", "sys", "dev")] | |
| for name in names: | |
| path = os.path.join(top, name) | |
| try: | |
| if os.path.islink(path) or not os.path.isfile(path): | |
| continue | |
| if os.path.getsize(path) > 20 << 20: | |
| continue | |
| with open(path, "rb") as f: | |
| text = f.read().decode("utf-8", "ignore") | |
| except OSError: | |
| continue | |
| hits = scan(text) | |
| if hits or cfg["sha"] in text: | |
| found[path] = hits[:3] | |
| return found | |
| def http(method, path): | |
| request = urllib.request.Request("http://maze:8000" + path, method=method, | |
| data=b"{}" if method == "POST" else None) | |
| try: | |
| with urllib.request.urlopen(request, timeout=10) as r: | |
| return r.status, r.read().decode() | |
| except urllib.error.HTTPError as e: | |
| return e.code, e.read().decode() | |
| except Exception as e: | |
| return 0, str(e) | |
| out = {"files": search(), "env": [], "cmdline": [], "processes": 0, "routes": {}, | |
| "visible": [d for d in ("/tests", "/solution", "/private", "/evidence") | |
| if os.path.exists(d)]} | |
| for pid in os.listdir("/proc"): | |
| if not pid.isdigit(): | |
| continue | |
| try: | |
| with open(f"/proc/{pid}/environ", "rb") as f: | |
| env = f.read().decode("utf-8", "ignore") | |
| with open(f"/proc/{pid}/cmdline", "rb") as f: | |
| cmd = f.read().decode("utf-8", "ignore").replace("\0", " ") | |
| except OSError: | |
| continue | |
| out["processes"] += 1 | |
| if scan(env) or cfg["sha"] in env: | |
| out["env"].append(pid) | |
| if scan(cmd): | |
| out["cmdline"].append(pid) | |
| for method, path in (("GET", "/"), ("GET", "/tree"), ("GET", "/state"), ("GET", "/exit"), | |
| ("GET", "/private/tree.json"), ("POST", "/look"), ("GET", "/move"), | |
| ("GET", "/health"), ("DELETE", "/move")): | |
| status, text = http(method, path) | |
| out["routes"][f"{method} {path}"] = [status, scan(text)] | |
| status, text = http("GET", "/look") | |
| out["look"] = json.loads(text) if status == 200 else text | |
| print("PROBE " + json.dumps(out)) | |
| """ | |
| try: | |
| from harbor.agents.base import BaseAgent | |
| class Probe(BaseAgent): | |
| """No model. `walker`: success_check in the maze service, the shortest path through | |
| `maze move`, success_check again. `probe`: looks around the agent's container, leaves | |
| forged evidence and three moves short of the exit.""" | |
| def __init__(self, *args, mode="walker", path=(), hidden=(), sha="", forged="", | |
| **kwargs): | |
| super().__init__(*args, **kwargs) | |
| self.mode, self.path, self.hidden, self.sha = mode, list(path), list(hidden), sha | |
| self.forged = forged | |
| def name() -> str: | |
| return "s3-maze-probe" | |
| def version(self) -> str: | |
| return "1" | |
| async def setup(self, environment) -> None: | |
| pass | |
| async def success(self, environment) -> dict | str: | |
| result = await environment.service_exec("python3 -I -S /app/success.py", | |
| service="maze", timeout_sec=30) | |
| line = next((x for x in (result.stdout or "").splitlines() if x.startswith("{")), "") | |
| try: | |
| return json.loads(line) | |
| except ValueError: | |
| return f"rc={result.return_code} {(result.stdout or '')[-300:]}" | |
| async def run(self, instruction, environment, context) -> None: | |
| report = {} | |
| if self.mode == "walker": | |
| report["before"] = await self.success(environment) | |
| moves = " && ".join(f"maze move {shlex.quote(r)} > /dev/null" for r in self.path) | |
| result = await environment.exec(moves + " && maze look", timeout_sec=600) | |
| report["walk"] = [result.return_code, (result.stdout or "")[-500:]] | |
| report["after"] = await self.success(environment) | |
| else: | |
| encoded = base64.b64encode(json.dumps( | |
| {"hidden": self.hidden, "sha": self.sha}).encode()).decode() | |
| result = await environment.exec(f"python3 -c {shlex.quote(PROBE_PY)} {encoded}", | |
| timeout_sec=900) | |
| line = next((x for x in (result.stdout or "").splitlines() | |
| if x.startswith("PROBE ")), None) | |
| report = json.loads(line.removeprefix("PROBE ")) if line else { | |
| "error": (result.stdout or "")[-1000:]} | |
| report["instruction_names"] = sorted(set(LABEL.findall(instruction)) | |
| & set(self.hidden)) | |
| result = await environment.exec(FORGE_SH.format(forged=self.forged) + " && " + | |
| " && ".join(f"maze move {shlex.quote(r)}" | |
| for r in self.path), | |
| timeout_sec=300) | |
| report["cheat"] = [result.return_code, (result.stdout or "")[-500:]] | |
| (self.logs_dir / "probe.json").write_text(json.dumps(report, indent=1)) | |
| except ImportError: # `--env none` needs no Harbor | |
| Probe = None | |
| # What a cheating agent leaves for a verifier that might read its container: a winning record | |
| # (base64 tar of final.json and moves.jsonl) where the export, Harbor's artifacts and the | |
| # verifier's folder go, a reward of 1, and Python made to read anything as a win. | |
| FORGE_SH = ("for d in /evidence /logs/artifacts/evidence /logs/verifier /tests; do " | |
| "mkdir -p $d && echo {forged} | base64 -d | tar --no-same-owner -xz -C $d; done && " | |
| "echo 1 > /logs/verifier/reward.txt && " | |
| "printf 'def loads(*a, **k):\\n return {{}}\\n' > /tests/json.py && " | |
| "printf 'import json\\n' > " | |
| "\"$(python3 -c 'import site; print(site.getsitepackages()[0])')/sitecustomize.py\"") | |
| async def run_trial(env: str, jobs: Path, task: str, name: str, agent: dict) -> tuple[dict, dict]: | |
| from harbor.models.trial.config import ( | |
| AgentConfig, | |
| EnvironmentConfig, | |
| TaskConfig, | |
| TrialConfig, | |
| ) | |
| from harbor.trial.trial import Trial | |
| environment = (EnvironmentConfig(import_path=env) if ":" in env | |
| else EnvironmentConfig(type=env)) | |
| config = TrialConfig(task=TaskConfig(path=HERE / "tasks" / task), trial_name=name, | |
| trials_dir=jobs, environment=environment, agent=AgentConfig(**agent)) | |
| result = await (await Trial.create(config)).run() | |
| probe_file = jobs / name / "agent" / "probe.json" | |
| probe = json.loads(probe_file.read_text()) if probe_file.is_file() else {} | |
| verifier = jobs / name / "verifier" | |
| return probe, { | |
| "rewards": result.verifier_result.rewards if result.verifier_result else None, | |
| "error": result.exception_info.exception_message if result.exception_info else None, | |
| "verifier": sorted(p.name for p in verifier.iterdir()) if verifier.is_dir() else []} | |
| async def check_trials(env: str, jobs: Path, work: Path) -> dict: | |
| task = HERE / "tasks" / PROBE_TASK | |
| tree = tree_of(task) | |
| path = g.shortest_path(tree) | |
| visible = {tree["start"], *tree["doors"][tree["start"]]} | |
| hidden = sorted(set(tree["doors"]) - visible) | |
| sha = json.loads((task / "tests" / "expected.json").read_text())["tree_sha256"] | |
| win = work / f"evidence-{PROBE_TASK}-oracle" | |
| if not win.is_dir(): | |
| win = evidence(task, work, "trial-oracle", path) | |
| tar = subprocess.run(["tar", "-cz", "-C", str(win), "final.json", "moves.jsonl"], | |
| capture_output=True, check=True).stdout | |
| forged = base64.b64encode(tar).decode() | |
| probe_agent = "__main__:Probe" | |
| report = {} | |
| walker, result = await run_trial(env, jobs, PROBE_TASK, "walker", { | |
| "import_path": probe_agent, "kwargs": {"mode": "walker", "path": path}}) | |
| report["walker"] = result | {k: walker.get(k) for k in ("before", "after")} | |
| check(walker.get("before", {}).get("success") is False if isinstance( | |
| walker.get("before"), dict) else False, f"walker: success_check before: {walker}") | |
| check(isinstance(walker.get("after"), dict) and walker["after"].get("success") is True, | |
| f"walker: success_check after the exit: {walker.get('after')}") | |
| check(result["rewards"] == {"reward": 1.0}, f"walker: {result}") | |
| check({"moves.jsonl", "final.json", "reward.txt"} <= set(result["verifier"]), | |
| f"walker: the verifier's folder holds {result['verifier']}") | |
| _, result = await run_trial(env, jobs, PROBE_TASK, "oracle", {"name": "oracle"}) | |
| report["oracle"] = result | |
| check(result["rewards"] == {"reward": 1.0}, f"oracle: {result}") | |
| probe, result = await run_trial(env, jobs, PROBE_TASK, "probe", { | |
| "import_path": probe_agent, | |
| "kwargs": {"mode": "probe", "path": path[:3], "hidden": hidden, "sha": sha, | |
| "forged": forged}}) | |
| report["probe"] = result | {"processes": probe.get("processes"), | |
| "files_scanned": "error" not in probe} | |
| check("error" not in probe and probe.get("processes", 0) > 0, f"probe: {probe}") | |
| check(not probe.get("files"), f"probe: files name hidden rooms: {probe.get('files')}") | |
| check(not probe.get("env") and not probe.get("cmdline"), | |
| f"probe: processes name hidden rooms: {probe.get('env')} {probe.get('cmdline')}") | |
| check(not probe.get("visible"), f"probe: the container holds {probe.get('visible')}") | |
| check(all(status == 404 and not named for status, named in probe.get("routes", {}).values()) | |
| and len(probe.get("routes", {})) == 9, f"probe: routes: {probe.get('routes')}") | |
| check(isinstance(probe.get("look"), dict) and probe["look"].get("room") == tree["start"], | |
| f"probe: maze look: {probe.get('look')}") | |
| check(not probe.get("instruction_names"), "probe: the instruction names hidden rooms") | |
| check(probe.get("cheat", [1])[0] == 0, f"probe: the cheat did not run: {probe.get('cheat')}") | |
| check(result["rewards"] == {"reward": 0.0}, f"probe: the cheat scored {result}") | |
| return report | |
| def main() -> int: | |
| parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) | |
| parser.add_argument("--env", default="podman", | |
| help="Harbor environment type or import path for the Trials; none: skip") | |
| parser.add_argument("--jobs-dir", type=Path, default=None, | |
| help="keep the Trials' files here (default: a temporary directory)") | |
| args = parser.parse_args() | |
| with tempfile.TemporaryDirectory() as d: | |
| work = Path(d) | |
| check_generator() | |
| print(f"1. generator: {len(failures)} failures") | |
| before = len(failures) | |
| report = check_service(work) | |
| print(f"2. service: {len(failures) - before} failures; {json.dumps(report)}") | |
| before = len(failures) | |
| covered = check_graders(work) | |
| print(f"3. graders: {len(failures) - before} failures; cases: {json.dumps(covered)}") | |
| before = len(failures) | |
| check_files() | |
| print(f"4. no-cheat (files): {len(failures) - before} failures") | |
| if args.env != "none": | |
| before = len(failures) | |
| jobs = args.jobs_dir or work / "jobs" | |
| jobs.mkdir(parents=True, exist_ok=True) | |
| report = asyncio.run(check_trials(args.env, jobs, work)) | |
| print(f"5. Trials on {args.env} ({PROBE_TASK}): {len(failures) - before} failures; " | |
| f"{json.dumps(report)}") | |
| for failure in failures: | |
| print("FAIL:", failure) | |
| print("all checks passed" if not failures else f"{len(failures)} checks failed") | |
| return 1 if failures else 0 | |
| if __name__ == "__main__": | |
| sys.exit(main()) | |