# /// script # requires-python = ">=3.12" # dependencies = ["harbor==0.25.0"] # /// """s3-aggregation's checks that need no model (huggingface/flock#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, tasks/ and roles/ 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; each task's team is its problem's first N numbers, and each role file holds its own slot's number. 2. Graders, run as Harbor runs them (tests/ copied in after the agent is done): on every task, the oracle (solution/solve.sh) scores 1, and a wrong, partial, padded, unsorted or duplicate-dropping answer scores 0. On one task per team 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 is the same for every problem of its team size; the answer is only in tests/ and solution/; the role files live outside tasks/. 4. No-cheat, from inside Trials (`--env`), on `agg-p01-n16`, with probe agents (no model): - one looks around the container while "the agent works" and finds no tests/ or solution/ and no file holding the answer, a role line or a hyphenated number word of the team (every number of the problem); 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. Harbor 0.25.0's hf-sandbox uploads tests/ with the host's file owner, which a sandbox can't take when the host's uid is over 65535 (some clusters): use flock's `--env flock.harbor.envs:HFSandbox` there. """ import argparse import asyncio import base64 import json import os 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_TASK = "agg-p01-n16" 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 folder in ("tasks", "roles"): for path in sorted((root / folder).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 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 = set() for p, numbers in enumerate(drawn, 1): for n in g.SIZES: name = g.task_name(p, n) names.add(name) team = numbers[:n] expected = json.loads((HERE / "tasks" / name / "tests" / "expected.json").read_text()) check(expected == sorted(team), f"{name}: expected.json is not the first {n} sorted") roles = sorted((HERE / "roles" / name).glob("*")) check([r.name for r in roles] == [f"slot-{k:02d}.md" for k in range(1, n + 1)], f"{name}: not one role file per slot") for slot, (path, number) in enumerate(zip(roles, team, strict=False), 1): text = path.read_text() check(text == f"Your private number: {g.words(number)}\n" and read_words(text.split(": ")[1].strip()) == number, f"{name}: slot {slot} does not hold its own number") check({p.name for p in (HERE / "tasks").iterdir()} == names, "tasks/ has other folders") check({p.name for p in (HERE / "roles").iterdir()} == names, "roles/ has other folders") 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").iterdir()): 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)}") n = int(task.name.split("-n")[1]) problem = int(task.name.split("-p")[1][:2]) toml = (task / "task.toml").read_text().replace(task.name, "TASK").replace( f"problem = {problem}\n", "problem = P\n") by_size.setdefault(n, set()).add(((task / "instruction.md").read_text(), 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(not any("Your private number:" in (task / f).read_text() for f in TASK_FILES), f"{task.name}: a role line is in the task folder") check(all(len(v) == 1 for v in by_size.values()), "an instruction or task.toml differs between problems of one team size") PROBE_SH = r""" mapfile -t secrets < <(printf %s "$1" | base64 -d) for d in /tests /solution; do [ -e "$d" ] && echo "visible $d"; done args=(); for s in "${secrets[@]}"; do args+=(-e "$s"); done search() { find / -xdev \( -path /proc -o -path /sys -o -path /dev -o -path /logs \) -prune -o -type f \ -size -20M -print0 2>/dev/null | xargs -0 -r grep -IlF "$@" 2>/dev/null } search "${args[@]}" | sed 's/^/holds /' mkdir -p /app && printf %s "$2" > /app/answer.json search -e "$2" | sed 's/^/control /' # the same search finds the answer once it is written """ # 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: looks around the container as an 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", secrets=(), answer="", task_instruction="", **kwargs): super().__init__(*args, **kwargs) self.mode, self.secrets, self.answer = mode, secrets, answer self.task_instruction = task_instruction @staticmethod def name() -> str: return "s3-aggregation-probe" def version(self) -> str: return "2" 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 secrets travel base64-encoded: a copy of the command in the container would # otherwise hold them encoded = base64.b64encode("\n".join(self.secrets).encode()).decode() result = await environment.exec( f"bash -c {shlex.quote(PROBE_SH)} probe {encoded} {shlex.quote(self.answer)}", timeout_sec=600) lines = (result.stdout or "").splitlines() (self.logs_dir / "probe.json").write_text(json.dumps({ "return_code": result.return_code, "visible": [x.split(" ", 1)[1] for x in lines if x.startswith("visible ")], "holds": [x.split(" ", 1)[1] for x in lines if x.startswith("holds ")], "control": [x.split(" ", 1)[1] for x in lines if x.startswith("control ")], "instruction_is_the_task_text": instruction.strip() == self.task_instruction.strip(), }, indent=1)) except ImportError: # `--env none` needs no Harbor Probe = None async def run_trial(env: str, jobs: Path, mode: str, kwargs: dict) -> tuple[dict | None, dict]: """One Trial of PROBE_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" / PROBE_TASK), trial_name=f"probe-{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: task, roles = HERE / "tasks" / PROBE_TASK, HERE / "roles" / PROBE_TASK answer = (task / "tests" / "expected.json").read_text().strip() lines = [p.read_text().strip() for p in sorted(roles.glob("slot-*.md"))] hyphenated = sorted({w for line in lines if "-" in (w := line.split(": ")[1])}) secrets = [answer, answer.replace(" ", ""), "Your private number:", *lines, *hyphenated] runs = await asyncio.gather( run_trial(env, jobs, "answer", {"secrets": secrets, "answer": answer, "task_instruction": (task / "instruction.md").read_text()}), *(run_trial(env, jobs, mode, {}) for mode in CHEATS)) (probe, graded), *cheated = runs check(probe is not None and probe["return_code"] == 0, f"Trial: the probe did not run ({graded['error']})") if probe is not None: check(not probe["visible"], f"Trial: visible while the agent works: {probe['visible']}") check(not probe["holds"], f"Trial: files hold the team's numbers: {probe['holds']}") check("/app/answer.json" in probe["control"], f"Trial: the search did not find the written answer ({probe['control']})") check(probe["instruction_is_the_task_text"], "Trial: the instruction is not the task's") check(graded["rewards"] == {"reward": 1.0}, f"Trial: the verifier gave the answer {graded['rewards']} ({graded['error']})") report = {"answer": {"probe": probe, **graded, "searched_for": len(secrets)}} for mode, (left, result) in zip(CHEATS, cheated, 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_TASK}): {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())