# /// script # requires-python = ">=3.12" # dependencies = ["harbor==0.25.0"] # /// """s3-aggregation's checks that need no model (huggingface/legion#115, section 5): uv run check.py # all of them; the Trials run on HF Sandboxes (HF_TOKEN) uv run check.py --env docker # the Trials in local docker instead uv run check.py --env none # skip the Trials 1. Generator: generate.py reproduces problems.json and tasks/ byte for byte from its seed; another seed gives other problems; 32 problems of 16 integers in 1..99; the English words read back to their numbers; a team `agg-pPP-nNN` has one task per slot, `-sKK`, whose answer is the problem's first N numbers sorted and whose instruction states slot K's number. 2. Graders, run as Harbor runs them (tests/ copied in after the agent is done), on slot 1 of every team (every slot's tests/ and solution/ are the same, which this checks): the oracle (solution/solve.sh) scores 1, and a wrong, partial, padded, unsorted or duplicate-dropping answer scores 0. On one team per size, malformed answers (missing, empty, not JSON, NaN, an object, strings, words, floats, booleans, nested, a "####" prefix, invalid UTF-8) and cheats score 0: the answer as a symlink to the tests' expected.json (dangling until the tests arrive, absolute or relative), a symlink or a hardlink to a right answer elsewhere, a hardlink to expected.json, a symlinked /app (to a right answer, or to the tests' folder), an expected.json planted as a link to the answer before the tests arrive, a directory and a FIFO (which must not hang the grader); and a wrong answer with Python made to read any answer as right: 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 (PYTHONUSERBASE), and a `dirname` shadowed on the PATH that points expected.json at the agent's own file. 3. No-cheat, in the files: a task folder holds only instruction.md, task.toml, tests/ and solution/; its instruction states its own slot's number on one line and is otherwise the same for every task of its team size, so it holds no teammate's number; the answer is only in tests/ and solution/; and there is no folder beside tasks/ that holds numbers. 4. No-cheat, from inside Trials (`--env`), on team `agg-p01-n16`, with probe agents (no model): - one per slot, each in its own slot's task, looks around the container while "the agent works": no tests/ or solution/, no file holding the answer or a teammate's hyphenated number word, no process whose environment or command line holds a teammate's number, and its instruction holds its own number and no teammate's; then it writes the answer, the same search finds it (a control), and the task's own verifier scores it 1; - the others leave a cheat with a wrong answer: /app/answer.json as a symlink to /tests/expected.json; a symlinked /app into a /tests they made; a json.py that reads any answer as right wherever the verifier may start; a sitecustomize in site-packages that does the same. The verifier scores each 0. `--env` takes a Harbor environment type or an import path. """ import argparse import asyncio import base64 import json import os import re import shlex import shutil import subprocess import sys import tempfile from pathlib import Path HERE = Path(__file__).resolve().parent sys.path.insert(0, str(HERE)) import generate as g # noqa: E402 TASK_FILES = {"instruction.md", "task.toml", "tests/test.sh", "tests/expected.json", "solution/solve.sh"} PROBE_TEAM = "agg-p01-n16" NUMBER_LINE = re.compile(r"^Your private number is ([a-z-]+)\.$", re.MULTILINE) failures: list[str] = [] def check(ok: bool, what: str) -> None: if not ok: failures.append(what) 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, and Harbor runs the scripts with bash).""" out = {"problems.json": (root / "problems.json").read_bytes()} for path in sorted((root / "tasks").rglob("*")): if path.is_file(): out[str(path.relative_to(root))] = path.read_bytes() return out VALUES = {w: i for i, w in enumerate(g.ONES) if w} | { w: 10 * i for i, w in enumerate(g.TENS) if w} def read_words(text: str) -> int: """English words back to a number, independently of generate.words.""" head, _, tail = text.partition("-") return VALUES[head] + (VALUES[tail] if tail else 0) def team_of(task: str) -> tuple[int, int]: """(problem, N) of a task or team name, `agg-pPP-nNN[-sKK]`.""" m = re.match(r"agg-p(\d\d)-n(\d\d)", task) return int(m[1]), int(m[2]) def held(team: str) -> dict[str, str]: """A team's slot labels and their private numbers.""" problem, n = team_of(team) numbers = json.loads((HERE / "problems.json").read_text())["problems"][f"p{problem:02d}"] return {f"agent-{k:03d}": g.words(x) for k, x in enumerate(numbers[:n], 1)} def check_generator() -> None: with tempfile.TemporaryDirectory() as d: g.generate(Path(d)) check(files(Path(d)) == files(HERE), "generate.py does not reproduce the committed files") drawn = g.problems() check(drawn == g.problems(), "the same seed gave other problems") check(drawn != g.problems(g.SEED + 1), "another seed gave the same problems") check(len(drawn) == 32 and all(len(p) == 16 and all(type(x) is int and 1 <= x <= 99 for x in p) for p in drawn), "not 32 problems of 16 integers in 1..99") check(all(read_words(g.words(n)) == n for n in range(1, 100)) and len({g.words(n) for n in range(1, 100)}) == 99, "the English words are wrong") names = [] for p, numbers in enumerate(drawn, 1): for n in g.SIZES: team = numbers[:n] for slot, number in enumerate(team, 1): name = g.task_name(p, n, slot) names.append(name) task = HERE / "tasks" / name expected = json.loads((task / "tests" / "expected.json").read_text()) check(expected == sorted(team), f"{name}: expected.json is not the first {n} sorted") stated = NUMBER_LINE.findall((task / "instruction.md").read_text()) check(len(stated) == 1 and read_words(stated[0]) == number, f"{name}: the instruction does not state slot {slot}'s number ({stated})") check(sorted(p.name for p in (HERE / "tasks").iterdir()) == sorted(names), "tasks/ has other folders") for p, _ in enumerate(drawn, 1): for n in g.SIZES: slots = sorted(x for x in names if x.startswith(g.team_name(p, n) + "-")) check(slots == [g.task_name(p, n, k) for k in range(1, n + 1)], f"{g.team_name(p, n)}: its slots in name order are not slot order") def grade(task: Path, answer: bytes | None = None, cheat=None) -> int: """The task's grader as Harbor runs it: `app/answer.json` stands for /app/answer.json and `tests/` for /tests, whose files are copied in only after the agent is done, through any link the agent left there (the worst case). `cheat(root)` lays out what an agent leaves behind instead of `answer` (None: no file), and may return the grader's extra `env` and working directory (`cwd`). Returns the reward.""" with tempfile.TemporaryDirectory() as d: root = Path(d).resolve() # the grader takes paths without links app, tests, verifier = root / "app", root / "tests", root / "verifier" app.mkdir() extra = {} if cheat is not None: extra = cheat(root) or {} elif answer is not None: (app / "answer.json").write_bytes(answer) tests.mkdir(exist_ok=True) for name in ("test.sh", "expected.json"): shutil.copyfile(task / "tests" / name, tests / name) env = {**os.environ, "ANSWER": str(app / "answer.json"), "VERIFIER_DIR": str(verifier), **extra.get("env", {})} try: subprocess.run(["bash", str(tests / "test.sh")], capture_output=True, timeout=60, env=env, cwd=extra.get("cwd"), check=False) except subprocess.TimeoutExpired: return -1 # a grader that hangs is a failure too return int((verifier / "reward.txt").read_text().strip()) FAKE_JSON = "def loads(*args, **kwargs):\n return [1]\n" # any answer equals any expected PATCH_JSON = "import json\njson.loads = lambda *args, **kwargs: [1]\n" def planted(root: Path, folder: str, name: str, text: str) -> Path: """A wrong answer, and `name` holding `text` in root/folder (made).""" (root / "app" / "answer.json").write_text("[0]") (root / folder).mkdir(parents=True, exist_ok=True) (root / folder / name).write_text(text) return root / folder def user_site(name: str, text: str): """A hook in the user site that PYTHONUSERBASE points at.""" 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() planted(root, str(Path(site).relative_to(root)), name, text) return {"env": env} return cheat def shadowed_dirname(root: Path) -> dict: """A `dirname` first on the PATH that points expected.json at the agent's own file.""" (root / "app" / "expected.json").write_text("[0]") script = planted(root, "bin", "dirname", f"#!/bin/sh\necho {root / 'app'}\n") / "dirname" script.chmod(0o755) return {"env": {"PATH": f"{root / 'bin'}:{os.environ['PATH']}"}} def oracle(task: Path) -> int: with tempfile.TemporaryDirectory() as d: path = Path(d) / "app" / "answer.json" subprocess.run(["bash", str(task / "solution" / "solve.sh")], capture_output=True, timeout=60, env={**os.environ, "ANSWER": str(path)}, check=True) return grade(task, path.read_bytes()) def wrong_answers(team: list[int]) -> dict[str, list]: """The answers that must score 0 for a team (sorted): those that apply to it.""" last = team[-1] + 1 if team[-1] < 99 else team[-1] - 1 out = {"wrong": sorted(team[:-1] + [last]), "partial": team[:-1], "padded": sorted(team + [team[-1]])} if len(set(team)) > 1: out["unsorted"] = team[::-1] if len(set(team)) < len(team): out["duplicate-dropping"] = sorted(set(team)) return out def malformed(team: list[int]) -> dict[str, bytes | None]: dump = json.dumps(team).encode() return {"missing": None, "empty": b"", "not JSON": b"[1, 2,", "NaN": b"[NaN]", "object": json.dumps({"answer": team}).encode(), "strings": json.dumps([str(x) for x in team]).encode(), "words": json.dumps([g.words(x) for x in team]).encode(), "floats": json.dumps([float(x) for x in team]).encode(), "booleans": json.dumps([True] * len(team)).encode(), "nested": json.dumps([team]).encode(), "#### prefix": b"#### " + dump, "invalid UTF-8": b"\xff" + dump} def cheats(task: Path) -> dict: """What an agent could leave behind to score without the answer, or with a right answer that is not its own regular file: `cheat(root)` for grade().""" right = (task / "tests" / "expected.json").read_bytes() def link(target): # the answer as a symlink return lambda root: (root / "app" / "answer.json").symlink_to(target(root)) def right_elsewhere(make): def cheat(root): (root / "elsewhere.json").write_bytes(right) make(root / "elsewhere.json", root / "app" / "answer.json") return cheat def hardlink_expected(root): # as if the tests could be reached while the agent works (root / "tests").mkdir() shutil.copyfile(task / "tests" / "expected.json", root / "tests" / "expected.json") os.link(root / "tests" / "expected.json", root / "app" / "answer.json") def app_to(make_target): def cheat(root): (root / "app").rmdir() (root / "app").symlink_to(make_target(root)) return cheat def right_folder(root): (root / "real").mkdir() (root / "real" / "answer.json").write_bytes(right) return root / "real" def tests_folder(root): (root / "tests").mkdir() (root / "tests" / "answer.json").symlink_to("expected.json") return root / "tests" def planted_expected(root): # the upload writes the answer into it through the link (root / "app" / "answer.json").write_bytes(b"[0]") (root / "tests").mkdir() (root / "tests" / "expected.json").symlink_to(root / "app" / "answer.json") return { "symlink to the tests' expected.json": link(lambda r: r / "tests" / "expected.json"), "relative symlink to the tests' expected.json": link( lambda r: Path("../tests/expected.json")), "symlink to a right answer elsewhere": right_elsewhere(lambda s, d: d.symlink_to(s)), "hardlink to a right answer elsewhere": right_elsewhere(os.link), "hardlink to the tests' expected.json": hardlink_expected, "symlinked /app with a right answer": app_to(right_folder), "symlinked /app into the tests": app_to(tests_folder), "expected.json planted as a link to the answer": planted_expected, "a directory": lambda root: (root / "app" / "answer.json").mkdir(), "a FIFO": lambda root: os.mkfifo(root / "app" / "answer.json"), # a wrong answer, and Python made to read any answer as right "a json.py in the working directory": lambda root: { "cwd": planted(root, "work", "json.py", FAKE_JSON)}, "a json.py on PYTHONPATH": lambda root: { "env": {"PYTHONPATH": str(planted(root, "pp", "json.py", FAKE_JSON))}}, "a sitecustomize on PYTHONPATH": lambda root: { "env": {"PYTHONPATH": str(planted(root, "pp", "sitecustomize.py", PATCH_JSON))}}, "a usercustomize in the user site": user_site("usercustomize.py", PATCH_JSON), "a .pth file in the user site": user_site( "hook.pth", "import json; json.loads = lambda *args, **kwargs: [1]\n"), "a dirname shadowed on the PATH": shadowed_dirname, } def check_graders() -> dict[str, int]: covered: dict[str, int] = {} for task in sorted((HERE / "tasks").glob("*-s01")): # slot 1 of every team for other in sorted(task.parent.glob(task.name.removesuffix("-s01") + "-s*")): check(all((other / f).read_bytes() == (task / f).read_bytes() for f in ("tests/test.sh", "tests/expected.json", "solution/solve.sh")), f"{other.name}: tests/ or solution/ differ from slot 1's") team = json.loads((task / "tests" / "expected.json").read_text()) check(oracle(task) == 1, f"{task.name}: the oracle does not score 1") cases = {k: (json.dumps(v).encode(), None) for k, v in wrong_answers(team).items()} if task.name.startswith("agg-p01-"): cases |= {k: (v, None) for k, v in malformed(team).items()} cases |= {k: (None, cheat) for k, cheat in cheats(task).items()} for case, (answer, cheat) in cases.items(): covered[case] = covered.get(case, 0) + 1 check(grade(task, answer, cheat) == 0, f"{task.name}: {case} does not score 0") check(covered.get("duplicate-dropping", 0) > 0, "no task has a duplicate to drop") return covered def check_files() -> None: by_size: dict[int, set[tuple[str, str]]] = {} for task in sorted((HERE / "tasks").iterdir()): listed = {str(p.relative_to(task)) for p in task.rglob("*") if p.is_file()} check(listed == TASK_FILES, f"{task.name}: holds {sorted(listed ^ TASK_FILES)}") problem, n = team_of(task.name) slot = int(task.name.split("-s")[-1]) toml = (task / "task.toml").read_text().replace(task.name, "TASK").replace( f"problem = {problem}\n", "problem = P\n").replace(f"slot = {slot}\n", "slot = K\n") text = (task / "instruction.md").read_text() own = held(task.name)[f"agent-{slot:03d}"] check(NUMBER_LINE.findall(text) == [own], f"{task.name}: its number line isn't its own") generic = NUMBER_LINE.sub("Your private number is NUMBER.", text) # no other number by_size.setdefault(n, set()).add((generic, toml)) answer = (task / "tests" / "expected.json").read_text().strip() holders = {str(p.relative_to(task)) for p in task.rglob("*") if p.is_file() and answer in p.read_text()} check(holders == {"tests/expected.json", "solution/solve.sh"}, f"{task.name}: the answer is in {sorted(holders)}") check(all(len(v) == 1 for v in by_size.values()), "an instruction (but its number) or task.toml differs between tasks of one team size") beside = {p.name for p in HERE.iterdir() if p.is_dir()} - {"tasks", ".cache", "__pycache__", ".git"} check(not beside, f"folders beside tasks/: {sorted(beside)}") def holds(text: str, words) -> set[str]: """The number words found in `text` as whole words ("seven" is not in "seventy-seven").""" return {w for w in words if re.search(rf"(?`, so it holds no number word # itself: its own command line is searched too. In files it looks for the teammates' hyphenated # number words (a bare single-digit word is in many system files) and the answer. PROBE_PY = r""" import base64, json, os, re, sys cfg = json.loads(base64.b64decode(sys.argv[1])) own, others, answer = cfg["own"], cfg["others"], cfg["answer"] needles = [w for w in others if "-" in w] + [answer, answer.replace(" ", "")] def whole(word, text): return re.search(r"(? 20 << 20: continue with open(path, "rb") as stream: text = stream.read().decode("utf-8", "ignore") except OSError: continue if any(x in text for x in found_in): found.append(path) return found out = {"visible": [d for d in ("/tests", "/solution") if os.path.exists(d)], "files": search(needles), "env": [], "cmdline": [], "own_env": [], "processes": 0} for pid in os.listdir("/proc"): if not pid.isdigit(): continue try: with open(f"/proc/{pid}/environ", "rb") as stream: env = stream.read().decode("utf-8", "ignore").split("\0") with open(f"/proc/{pid}/cmdline", "rb") as stream: cmd = stream.read().decode("utf-8", "ignore").replace("\0", " ") except OSError: continue out["processes"] += 1 for entry in env: key, _, value = entry.partition("=") if any(whole(w, value) for w in others): out["env"].append(f"{pid}:{key}") if value == own: out["own_env"].append(f"{pid}:{key}") if any(whole(w, cmd) for w in others): out["cmdline"].append(f"{pid}:{cmd[:80]}") os.makedirs("/app", exist_ok=True) with open("/app/answer.json", "w") as stream: stream.write(answer) out["control"] = search([answer]) # the same search finds the answer once it is written print("PROBE " + json.dumps(out)) """ # What a cheating agent leaves for the verifier, before the tests arrive FAKE_JSON_SH = "printf 'def loads(*args, **kwargs):\\n return [1]\\n'" CHEATS = { "symlink": "mkdir -p /app && ln -s /tests/expected.json /app/answer.json", "symlinked-app": "mkdir -p /tests && ln -s expected.json /tests/answer.json" " && rm -rf /app && ln -s /tests /app", # a wrong answer, and a json module that reads any answer as right wherever the verifier # may start (/, /app, /tests, the home and the verifier's folders), or a site hook "json-module": "mkdir -p /app /tests /logs/verifier && printf '[0]' > /app/answer.json && " "for d in / /app /tests /root /logs/verifier; do " f"{FAKE_JSON_SH} > $d/json.py; done", "sitecustomize": "mkdir -p /app && printf '[0]' > /app/answer.json && printf 'import json\\n" "json.loads = lambda *args, **kwargs: [1]\\n' > \"$(python3 -c " "'import site; print(site.getsitepackages()[0])')/sitecustomize.py\"", } try: from harbor.agents.base import BaseAgent class Probe(BaseAgent): """No model. `mode` answer: in its slot's task, looks around the container as that slot's agent could while it works, writes `probe.json` in its logs dir on the host, then the answer for the verifier. Any other mode: leaves that cheat (CHEATS) instead.""" def __init__(self, *args, mode="answer", own="", others=(), answer="", **kwargs): super().__init__(*args, **kwargs) self.mode, self.answer = mode, answer self.own, self.others = own, list(others) @staticmethod def name() -> str: return "s3-aggregation-probe" def version(self) -> str: return "4" async def setup(self, environment) -> None: pass async def run(self, instruction, environment, context) -> None: if self.mode != "answer": result = await environment.exec(CHEATS[self.mode], timeout_sec=60) (self.logs_dir / "probe.json").write_text(json.dumps( {"return_code": result.return_code, "cheat": CHEATS[self.mode]})) return # the teammates' numbers travel base64-encoded: a copy of the command in the # container would otherwise hold them encoded = base64.b64encode(json.dumps( {"own": self.own, "others": self.others, "answer": self.answer}).encode()).decode() result = await environment.exec(f"python3 -c {shlex.quote(PROBE_PY)} {encoded}", timeout_sec=600) line = next((x for x in (result.stdout or "").splitlines() if x.startswith("PROBE ")), None) found = json.loads(line.removeprefix("PROBE ")) if line else {} (self.logs_dir / "probe.json").write_text(json.dumps({ "return_code": result.return_code, **found, "instruction_holds": sorted(holds(instruction, [self.own, *self.others])), }, indent=1)) except ImportError: # `--env none` needs no Harbor Probe = None async def run_trial(env: str, jobs: Path, mode: str, kwargs: dict, task: str, name: str = "") -> tuple[dict | None, dict]: """One Trial of `task` with the probe in `mode`: (its probe.json, rewards and error).""" from harbor.models.trial.config import ( AgentConfig, EnvironmentConfig, TaskConfig, TrialConfig, ) from harbor.trial.trial import Trial sandbox = {"flavor": "cpu-basic", "job_timeout": 900} environment = (EnvironmentConfig(import_path=env, kwargs=sandbox if "Sandbox" in env else {}) if ":" in env else EnvironmentConfig(type=env, kwargs=sandbox if env == "hf-sandbox" else {})) config = TrialConfig( task=TaskConfig(path=HERE / "tasks" / task), trial_name=f"probe-{name or mode}", trials_dir=jobs, environment=environment, agent=AgentConfig(import_path="__main__:Probe", kwargs={"mode": mode, **kwargs})) result = await (await Trial.create(config)).run() probe_file = jobs / config.trial_name / "agent" / "probe.json" probe = json.loads(probe_file.read_text()) if probe_file.is_file() else None 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} async def check_trials(env: str, jobs: Path) -> dict: team = held(PROBE_TEAM) tasks = {agent: g.task_name(*team_of(PROBE_TEAM), int(agent[-3:])) for agent in team} answer = (HERE / "tasks" / tasks["agent-001"] / "tests" / "expected.json").read_text().strip() probes = {agent: {"own": own, "answer": answer, "others": sorted({w for w in team.values() if w != own})} for agent, own in team.items()} gate = asyncio.Semaphore(10) # sandboxes at once async def one(mode, kwargs, task, name=""): async with gate: return await run_trial(env, jobs, mode, kwargs, task, name) runs = await asyncio.gather( *(one("answer", kwargs, tasks[agent], agent) for agent, kwargs in probes.items()), *(one(mode, {}, tasks["agent-001"]) for mode in CHEATS)) report = {} for (agent, kwargs), (probe, graded) in zip(probes.items(), runs[:len(probes)], strict=True): what = f"Trial {tasks[agent]}" ran = probe is not None and probe.get("return_code") == 0 and "files" in probe check(ran, f"{what}: the probe did not run ({graded['error']})") if ran: check(not probe["visible"], f"{what}: visible while the agent works: " f"{probe['visible']}") check(not probe["files"], f"{what}: files hold a teammate's number or the answer: " f"{probe['files']}") check(not probe["env"], f"{what}: a process's environment holds a teammate's " f"number: {probe['env']}") check(not probe["cmdline"], f"{what}: a command line holds a teammate's number: " f"{probe['cmdline']}") check(probe["instruction_holds"] == [kwargs["own"]], f"{what}: the instruction holds {probe['instruction_holds']}, not just " f"{kwargs['own']}") check("/app/answer.json" in probe["control"], f"{what}: the search did not find the written answer ({probe['control']})") check(graded["rewards"] == {"reward": 1.0}, f"{what}: the verifier gave the answer {graded['rewards']} ({graded['error']})") report[tasks[agent]] = {"instruction_holds": probe and probe.get("instruction_holds"), "processes": probe and probe.get("processes"), "teammates": len(kwargs["others"]), **graded} for mode, (left, result) in zip(CHEATS, runs[len(probes):], strict=True): check(left is not None and left["return_code"] == 0, f"Trial: cheat {mode} not left") check(result["rewards"] == {"reward": 0.0}, f"Trial: cheat {mode} gave {result['rewards']} ({result['error']})") report[mode] = {"left": left, **result} return report def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) parser.add_argument("--env", default="hf-sandbox", 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() check_generator() print(f"1. generator: {len(failures)} failures") before = len(failures) covered = check_graders() print(f"2. graders: {len(failures) - before} failures; zero-score cases checked: {covered}") before = len(failures) check_files() print(f"3. no-cheat (files): {len(failures) - before} failures") if args.env != "none": before = len(failures) with tempfile.TemporaryDirectory() as d: jobs = args.jobs_dir or Path(d) jobs.mkdir(parents=True, exist_ok=True) report = asyncio.run(check_trials(args.env, jobs)) print(f"4. no-cheat (Trials on {args.env}, {PROBE_TEAM}): {len(failures) - before} " f"failures; {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())