diff --git a/CHANGELOG.md b/CHANGELOG.md index 6384c20ae..857ecc3d5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,28 @@ ## [Unreleased] +### Added + +- `inferrsi benchmarks external list|run|selfcheck` runs a Φ-Bench task and scores it + with the suite's own grader (Refs #688, slice 1). It lands the `noop`, `negative` or + `oracle` control, a candidate patch or one agent command, captures the patch and + judges the controls against the suite's documented expectations. The `docker` + executor delegates to the suite runner; the `rootless` executor replays the task + image layout under proot for hosts without Docker and records what it did not + replay. See [public benchmarks](docs/benchmarks/public-benchmarks.md). +- `benchmarks external run --mode agent` keeps the suite's `tests/` and `solution/` + out of the agent's step (the suite mounts them only for grading), forwards named + environment variables with `--agent-env` and bounds the agent step with the + task's own `[agent] timeout_sec`. Like the suite runner, it grades an agent that + failed or timed out on the tree it left and marks a timed-out grader + `verifier_timed_out`; that run has status `verifier_timeout` and exits 1 even when + the grader wrote a reward (the raw score stays in `result.json` for audit), and a + control judged on it is `INCONCLUSIVE`; a run with no readable + reward is `no_reward` and exits 1, and steps without a `timeout_sec` use the + suite runner's defaults, read from `task.toml` with the suite's own TOML parser; + the rootless agent step cannot see the suite clone and + cannot leave files for the grading step under `/tests` or `/logs/verifier`. + ### Fixed - Six Apps defects from the 2026-11-23 repository review (Refs #595, group 2): diff --git a/docs/benchmarks/engineering-benchmarks.md b/docs/benchmarks/engineering-benchmarks.md index 24b3e6e14..6b98b3b4b 100644 --- a/docs/benchmarks/engineering-benchmarks.md +++ b/docs/benchmarks/engineering-benchmarks.md @@ -11,6 +11,8 @@ For a complete optimization benchmark driven by the current Agent, use the snapshots, round feedback, selection, independent final evaluation and cumulative usage exports. The entries in the table below are the individual task measurement operations. +Tasks from public suites such as Φ-Bench are not packaged here; run them with +the [public benchmark adapter](public-benchmarks.md). | Package | Optimization target | Execution entry | | --- | --- | --- | diff --git a/docs/benchmarks/public-benchmarks.md b/docs/benchmarks/public-benchmarks.md new file mode 100644 index 000000000..b60c7d8b9 --- /dev/null +++ b/docs/benchmarks/public-benchmarks.md @@ -0,0 +1,147 @@ +# Public benchmark suites + +InferRSI can run tasks from a public benchmark suite and score them with that +suite's own grader. The first suite is +[Φ-Bench](https://github.com/one2piece2hello/faibench_Frontier_InfraBench) +(arXiv:2609.10226, Apache-2.0): 85 LLM-infrastructure tasks, each a Docker build +context with a starting tree, a grader under `tests/` and reference landings +under `solution/`. + +The adapter keeps four steps separate, so a later suite only needs a new task +reader: + +1. **Task package**: read the suite index and one task package. +2. **Change**: land a reference control, a candidate patch or one agent command + in the task's working tree. +3. **Patch**: capture the working-tree diff with the package's + `pre_artifacts.sh`. +4. **Independent grading**: run the package's `tests/test.sh` and read the + `reward.json` it writes. + +Benchmark owns steps 1 and 4 (`inferrsi.benchmark.external.phibench`); Apps +owns execution (`inferrsi.apps.workflows.external_benchmark`). InferRSI does not +vendor any task, grader or reference solution. Clone the suite yourself. + +## Commands + +```bash +git clone https://github.com/one2piece2hello/faibench_Frontier_InfraBench phibench +inferrsi benchmarks external list --root phibench +inferrsi benchmarks external selfcheck --root phibench --task kfc/ \ + --executor docker --oracle-tolerance --output runs/ +inferrsi benchmarks external run --root phibench --task kfc/ \ + --executor rootless --proot /path/to/proot --mode candidate \ + --candidate-patch candidate.patch --output runs/-candidate +``` + +`run --mode` takes `noop`, `negative`, `oracle`, `candidate` (with +`--candidate-patch`) or `agent` (with `--agent-command`, a shell command run in +`/app/repo` with `PHI_INSTRUCTION=/app/instruction.md`). Each mode writes +`//result.json` with the landing, capture and grading logs, the +captured patch size and the grader's score. `selfcheck` runs the three controls +and writes `/selfcheck.json`; it exits 0 only on `PASS`. + +Agent mode follows the suite's split: `tests/` and `solution/` are **not** in +the agent's step (the suite mounts them only for grading), so an agent cannot read +the hidden cases or the reference patch. proot otherwise shares the host +filesystem, so the rootless executor also covers the suite clone with an empty +directory for the agent step; keep `--python-env`, other copies of the suite and +earlier control runs (they stage `solution/`) outside it or out of reach. The +grading step starts from a fresh `tests/` and an empty `/logs/verifier`. An agent +that exits non-zero or hits its timeout is still graded on the tree it left, as +the suite runner does; `result.json` lists it under `warnings`. A grader cut off +at its own timeout adds the hard fail `verifier_timed_out`; that run has status +`verifier_timeout` and `run` exits 1, even when the grader left a reward behind +(the raw score stays in `result.json` for audit), and a control whose grader timed +out is `INCONCLUSIVE`. A grader that leaves no readable reward (`reward.json`, `metrics.json` or `reward.txt`) adds `no_reward_file`; that run has status `no_reward` and `run` exits 1. A grader that exits 124 or 137 counts as timed out too. `task.toml` is read with the same TOML parser as the suite runner, so comments, digit separators and exponents mean the same thing. Without a `timeout_sec` in `task.toml` the steps use the suite runner's defaults (agent 5400 s, grader 3600 s); a reference landing (`oracle`, `negative`, `noop`) is capped at 1800 s, as in the suite runner. `--agent-env NAME` forwards an +environment variable by name into the agent step only (model-provider keys, +`HTTPS_PROXY`, `CODEX_HOME`). The value goes into a mode-600 file inside the +task root (removed after that step), not into the result or the host process +table; the grading step does not inherit it. The agent step is bounded by the +task's own `[agent] timeout_sec` in `task.toml`. + +`--inferrsi-plugin DIR` (agent mode, rootless executor) runs the same agent with +InferRSI, using the [Codex plugin](../guides/plugins/codex-plugin.md) the +standard way for a client that cannot import the plugin archive: the built +plugin directory (`tools/build_codex_plugin.py`, or the unpacked Release ZIP) is +placed at `/opt/inferrsi-plugin`, and a short note appended to +`/app/instruction.md` tells the agent to use InferRSI through that directory's +`SKILL.md` and launcher. Choosing skills and searching knowledge stay with the +agent; nothing is retrieved for it in advance. The original instruction is +restored before grading, `tests/` and `solution/` stay out of the agent's step, +and `result.json` records the plugin's version and `content_sha256` under +`inferrsi`. The task image's interpreter runs the launcher; operations that parse +skill frontmatter need PyYAML there. Without the flag the run is unchanged, so it +is the plain-agent control: keep the task, model, effort, timeout and run count +identical between the two arms. + +## Executors + +- `docker` delegates to the suite's `scripts/run_task.py`, which builds the + task image and grades in a fresh offline container. This is the suite's + reference path. In this slice it runs the reference controls; pass extra + runner options with `--runner-arg`. +- `rootless` is for hosts without Docker or user namespaces. It recreates the + image layout in the output directory and maps it onto `/app`, `/opt`, + `/tests` and `/logs` with [proot](https://proot-me.github.io/). It replays the + Dockerfile's `COPY`, `ARG` defaults and `ENV`, the one-commit baseline of + `/app/repo` and the frozen `/opt/verifier-baseline` copies. It does not run + other `RUN` steps or the image entrypoint (its `/app/timer.sh` budget stub). + Provide a Python environment with the task's dependencies through + `--python-env`; otherwise it creates an empty venv, which is enough + for standard-library tasks. Every result records `fidelity: approximate` and + lists the Dockerfile steps it did not replay. proot does not enforce the + read-only `tests/` mount or the offline network that Docker grading uses. + +## Control expectations + +The self-check follows the suite's own documentation (README "Important +Conventions", `SCORING.md`): + +| Control | Landing | Expected | +| --- | --- | --- | +| `noop` | starting tree unchanged | reward 0 | +| `negative` | known-bad `negative.patch` | reward 0 | +| `oracle` | reference `oracle.patch` | implementation task: reward 1.0; performance task: no hard gate, measured speedup equals `ref_speedup` within `--oracle-tolerance` | + +Performance tasks use the curve `reward_md_log_speedup_v2_oracle_zero`, which +gives 0 to a submission that ties the anchor. A correct oracle therefore scores +0, and the self-check judges it on its hard gates and measured speedup instead. +Without `--oracle-tolerance` a performance oracle is `INCONCLUSIVE`. Anchors were +calibrated on an NVIDIA H20 or the authors' CPU lane; on other hardware a timed +oracle can miss the anchor and the task needs re-calibration before scoring. + +## Re-calibrating a timed task on a new host + +The grader reads the anchor from the task package's `tests/ref_speedup.txt` +first (`task.toml` `ref_speedup_source`), so a re-calibration is host-local: it +never changes InferRSI. Run the reference landing at least three times on a +quiet GPU, take the median, and write it back into the package: + +```bash +for i in 1 2 3; do + inferrsi benchmarks external run --root phibench --task kfc/ \ + --executor rootless --proot proot --python-env \ + --mode oracle --output runs/cal-$i +done +# median of runs/cal-*/oracle/result.json -> score.speedup +printf '5.4874\n' > phibench/tasks/kfc//task/tests/ref_speedup.txt +inferrsi benchmarks external selfcheck ... --oracle-tolerance 0.03 +``` + +On one NVIDIA L20X (torch 2.7.0+cu126, triton 3.3.0) the H20 anchor 6.4424 for +`kfc/merge-attn-states-combine` measured 5.5196 / 5.4874 / 5.4720 over three +fresh oracle runs (median 5.4874, 0.9% spread); the corresponding self-check +passed with the new anchor at a 3% tolerance (about twice the observed +half-spread). Re-measure per host and per run stack; do not copy these numbers +to another machine. + +## Scope of this slice + +This entry checks that a suite task, its controls and its grader work on a +host, including one real agent run on a GPU task. It does not yet score InferRSI +against the suite. Scoring under the +[InferRSI benchmark design](https://github.com/InferMatrixLab/InferRSI/issues/665) +(fixed budget, N independent runs, `reach(p)`) is a later slice; the anchor +procedure above calibrates one task on one host, not the whole suite. Φ-Bench's +hidden cases are public, so its results count as a public set only. diff --git a/docs/guides/operations.md b/docs/guides/operations.md index 24a168e62..f9dc58517 100644 --- a/docs/guides/operations.md +++ b/docs/guides/operations.md @@ -21,6 +21,7 @@ Effect classes used below: | Prepare and record a fresh native Agent | CLI `agents prepare/dispatch/bind/record/status` | Local records / explicit host handoff | The initiating Agent calls native host tools. Records prevent repeated dispatch; exported host observations do not establish task acceptance. See [native sessions](native-agent-sessions.md) | | Discover packaged tasks | CLI `benchmarks list [--iterative]` / `benchmarks show`; Python `benchmark.registry.builtin_tasks` / `describe_task` | Read-only | Reads the installed registry and [task manifests](../benchmarks/engineering-benchmarks.md). The optional filter selects task packages with an `optimization.py` file at their root | | Execute one packaged task | CLI `benchmarks run`; Python `apps.workflows.benchmark_operations.run_task` | Experiment-executing | Application launches the task entry, supplies the execution callback and preserves arguments and exit status. The task owns its device, measurement and assessment protocol | +| Run and grade a public-suite task | CLI `benchmarks external list` / `run` / `selfcheck`; Python `apps.workflows.external_benchmark` | Experiment-executing / local records | Lands a reference control, candidate patch or agent command in a [Φ-Bench task](../benchmarks/public-benchmarks.md) and scores it with the suite's own grader. Docker delegates to the suite runner; `rootless` replays the image layout under proot and records its fidelity | | Find relevant cases, skills and records | CLI `find` | Read-only | Default discovery across the registered library and package records. Follow the emitted command to read a hit and its revision | | Inspect the package catalog | CLI `knowledge search` / `knowledge show`; catalog API | Read-only | Filtered inventory and existing catalog scripts. Uses the installed package's tier/repo/backend/scenario filters and IDs | | Prepare model-aware engine research | CLI `knowledge research`; Python `research_knowledge` | Read-only | Independent model/framework/task/modality/mechanism queries over the same package catalog; source-grounded known profiles, deduplicated matches and explicit target annotations; no engine/hardware qualification | diff --git a/pyproject.toml b/pyproject.toml index c56aedd10..26797f3e2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -9,7 +9,7 @@ description = "CLI-first reproducible inference experiments and source-grounded readme = "README.md" license = "Apache-2.0" requires-python = ">=3.10" -dependencies = ["PyYAML>=6.0"] +dependencies = ["PyYAML>=6.0", "tomli>=2.0; python_version < '3.11'"] [project.scripts] inferrsi = "inferrsi.apps.cli:main" diff --git a/src/inferrsi/apps/cli/__init__.py b/src/inferrsi/apps/cli/__init__.py index 69ed0180c..958d39261 100644 --- a/src/inferrsi/apps/cli/__init__.py +++ b/src/inferrsi/apps/cli/__init__.py @@ -535,6 +535,12 @@ def main(argv: list[str] | None = None) -> int: ) _print(after_final(args, result)) return 2 if result.get("state") == "blocked" else 0 + if args.benchmark_action == "external": + from ..workflows.external_benchmark import command as external_command + + result, status = external_command(args) + _print(result) + return status if args.benchmark_action == "run": from ..workflows.benchmark_operations import run_task diff --git a/src/inferrsi/apps/cli/arguments.py b/src/inferrsi/apps/cli/arguments.py index 5842128f2..63124a6e8 100644 --- a/src/inferrsi/apps/cli/arguments.py +++ b/src/inferrsi/apps/cli/arguments.py @@ -441,6 +441,50 @@ def parser(*, parser_class=argparse.ArgumentParser) -> argparse.ArgumentParser: run = actions.add_parser("run", help="Run the selected task's benchmark.py") run.add_argument("task", help="Packaged engineering task name") run.add_argument("arguments", nargs=argparse.REMAINDER, help="Task-specific arguments") + external = actions.add_parser( + "external", help="Run a public suite's task and score it with that suite's grader", + description=("Phi-Bench first. Lands a reference control (noop/negative/oracle), a " + "candidate patch or one agent command in the task's environment, " + "captures the patch and runs the suite grader. The docker executor " + "delegates to the suite's scripts/run_task.py; the rootless executor " + "replays the image layout under proot for hosts without Docker."), + ) + external_actions = external.add_subparsers(dest="external_action", required=True) + for name in ("list", "run", "selfcheck"): + action = external_actions.add_parser(name) + action.add_argument("--suite", choices=("phibench",), default="phibench") + action.add_argument("--root", type=Path, required=True, help="Local clone of the suite") + if name == "list": + continue + action.add_argument("--task", required=True, help="Suite task ID, e.g. kfc/") + action.add_argument("--output", type=Path, required=True, + help="New directory; each mode writes //result.json") + action.add_argument("--executor", choices=("rootless", "docker"), default="docker") + action.add_argument("--proot", help="proot binary for the rootless executor") + action.add_argument("--python", help="Interpreter for the runner or the task venv") + action.add_argument("--python-env", type=Path, + help="Prepared environment with the task's Python dependencies") + action.add_argument("--runner-arg", action="append", + help="Extra argument for the suite runner (docker); repeatable") + if name == "run": + action.add_argument("--mode", required=True, + choices=("noop", "negative", "oracle", "candidate", "agent")) + action.add_argument("--candidate-patch", type=Path, + help="Working-tree patch to score (mode candidate)") + action.add_argument("--agent-command", + help="Shell command run in the task tree (mode agent)") + action.add_argument("--agent-env", action="append", metavar="NAME", + help="Environment variable forwarded by name into the agent " + "step, e.g. a model-provider key; repeatable") + action.add_argument("--inferrsi-plugin", type=Path, metavar="DIR", + help="Mode agent, rootless: put this built InferRSI Codex " + "plugin at /opt/inferrsi-plugin and tell the agent to " + "use InferRSI (directory + prompt)") + else: + action.add_argument("--oracle-tolerance", type=float, + help="Allowed relative deviation of the oracle speedup from " + "the task anchor; without it a performance oracle is " + "INCONCLUSIVE") session = actions.add_parser( "session", help="Drive iterative optimization in the current Agent" ) diff --git a/src/inferrsi/apps/workflows/external_benchmark.py b/src/inferrsi/apps/workflows/external_benchmark.py new file mode 100644 index 000000000..356f13d28 --- /dev/null +++ b/src/inferrsi/apps/workflows/external_benchmark.py @@ -0,0 +1,554 @@ +"""Run public-suite tasks (Φ-Bench first) and score them with the suite's own grader. + +The flow is: task package -> land a change (a reference control, a candidate +patch or one agent command) -> capture the working-tree patch with the +package's ``pre_artifacts.sh`` -> run the package's grader -> judge the +``reward.json`` it writes. Benchmark (``inferrsi.benchmark.external``) owns +the task reading and the judgment; this module owns process execution. + +Two executors: + +- ``docker`` delegates the whole run to the suite's ``scripts/run_task.py``, + which builds the task image and grades in a fresh offline container. This is + the suite's reference path. +- ``rootless`` serves hosts without Docker or user namespaces. It recreates + the image layout under one directory and maps it onto the container paths + with ``proot``. It replays the Dockerfile's ``COPY`` and ``ENV`` + instructions, the one-commit baseline of ``/app/repo`` and the frozen + ``/opt/verifier-baseline`` copies; it does not run other ``RUN`` steps + (system or Python package installs). Supply a Python environment that has + the task's dependencies with ``python_env``. Every result records + ``fidelity`` and the Dockerfile steps it did not replay. + +In agent mode the suite's ``tests/`` and ``solution/`` are staged only after the +agent has finished, mirroring the suite's mount-for-grading-only split; named +environment variables can be forwarded into that one step with ``agent_env``. +``inferrsi_plugin`` additionally puts a built InferRSI Codex plugin in that step's tree +and tells the agent to use InferRSI (rootless only): the plugin's standard +directory-plus-prompt use, so one run differs from its control only by InferRSI. +""" + +from __future__ import annotations + +import json +import os +import re +import shlex +import shutil +import subprocess +import sys +import time +from pathlib import Path + +try: # Python 3.11+ + import tomllib +except ModuleNotFoundError: # Python 3.10: declared in pyproject.toml. + import tomli as tomllib + +from inferrsi.benchmark.external import phibench + +MODES = (*phibench.CONTROLS, "candidate", "agent") +EXECUTORS = ("rootless", "docker") +_BASE_PATH = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" +_CONTROL_FLAG = {"oracle": "", "negative": "--negative", "noop": "--noop"} +# The suite runner caps a reference landing (its oracle agent) at 1800 s +# (scripts/run_task.py, the agent stage `timeout=... else 1800`). +_CONTROL_LANDING_TIMEOUT = 1800.0 + + +# --------------------------------------------------------------------------- Dockerfile + + +def _logical_lines(text: str) -> list[str]: + """Join continuations and drop heredoc bodies, which are RUN payloads.""" + lines, current, heredoc = [], "", None + for raw in text.splitlines(): + if heredoc is not None: + if raw.strip() == heredoc: + heredoc = None + continue + stripped = raw.strip() + if not current and (not stripped or stripped.startswith("#")): + continue + if current and stripped.startswith("#"): + continue + current += (" " if current else "") + stripped.rstrip("\\").strip() + if stripped.endswith("\\"): + continue + marker = re.search(r"<<-?\s*'?\"?([A-Za-z_][A-Za-z0-9_]*)'?\"?", current) + if marker: + heredoc = marker.group(1) + lines.append(current) + current = "" + if current: + lines.append(current) + return lines + + +def _expand(value: str, env: dict[str, str]) -> str: + return re.sub(r"\$\{?([A-Za-z_][A-Za-z0-9_]*)\}?", + lambda m: env.get(m.group(1), ""), value) + + +def parse_dockerfile(path: Path) -> dict: + """Extract what the rootless executor can replay from a task Dockerfile.""" + env: dict[str, str] = {"PATH": _BASE_PATH} + build_args: dict[str, str] = {} + copies, baseline_copies, workdir, unreplayed = [], [], None, [] + for line in _logical_lines(Path(path).read_text(encoding="utf-8")): + word, _, rest = line.partition(" ") + word = word.upper() + if word == "ARG": + key, _, value = rest.strip().partition("=") + # Docker unquotes a default (`ARG X="9.0"` is 9.0). + build_args[key] = " ".join(shlex.split(value)) + elif word == "ENV": + tokens = shlex.split(rest) + pairs = ([tuple(t.split("=", 1)) for t in tokens] if "=" in tokens[0] + else [(tokens[0], " ".join(tokens[1:]))]) + for key, value in pairs: + env[key] = _expand(value, {**build_args, **env}) + elif word == "COPY": + tokens = [t for t in shlex.split(rest) if not t.startswith("--")] + if any(t.startswith("--from") for t in shlex.split(rest)) or len(tokens) != 2: + unreplayed.append(line[:160]) + continue + copies.append((tokens[0], tokens[1])) + elif word == "WORKDIR": + workdir = _expand(rest.strip(), env) + elif word == "RUN": + found = re.findall( + r'\bcp\s+"?(/app/[^"\s]+)"?\s+"?(/opt/verifier-baseline/[^"\s]+)"?', rest) + baseline_copies.extend(found) + replayed = found or "git init" in rest or re.search(r"\bvenv\b", rest) \ + or re.match(r"mkdir -p\s", rest) + if not replayed: + unreplayed.append(line[:160]) + env.pop("DEBIAN_FRONTEND", None) + return {"env": env, "copies": copies, "baseline_copies": baseline_copies, + "workdir": workdir, "unreplayed": unreplayed} + + +# --------------------------------------------------------------------------- staging + + +def _host(root: Path, container_path: str) -> Path: + return root / container_path.lstrip("/") + + +def _copy(src: Path, dst: Path) -> None: + if src.is_dir(): + shutil.copytree(src, dst, dirs_exist_ok=True, symlinks=True) + else: + dst.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(src, dst) + + +def _git(repo: Path, *args: str) -> None: + subprocess.run(["git", "-c", "user.email=reviewer@fai-bench.local", "-c", "user.name=fai-bench", + "-c", "init.defaultBranch=main", "-C", str(repo), *args], + check=True, capture_output=True, text=True) + + +def stage_rootless(task: phibench.PhiTask, root: Path, *, python: str, + python_env: Path | None = None, include_tests: bool = True, + include_solution: bool = True) -> dict: + """Recreate the task image layout under ``root``; return the replay record. + + ``include_tests``/``include_solution`` exist for agent mode: the suite keeps + ``tests/`` and ``solution/`` out of the agent's container and mounts them only + for grading, so the agent cannot read the hidden cases or the reference patch. + """ + package = task.package_root + plan = parse_dockerfile(package / "environment" / "Dockerfile") + if root.exists(): + raise ValueError(f"Staging directory already exists: {root}") + for path in ("app/repo", "app/.timer", "app/workspace", "logs/verifier", "logs/agent", + "logs/artifacts", "opt", "root", "tmp"): + (root / path).mkdir(parents=True, exist_ok=True) + for src, dst in plan["copies"]: + source = (package / src).resolve() + if package not in source.parents and source != package: + raise ValueError(f"COPY source escapes the package: {src}") + target = _host(root, dst) + if source.is_dir(): + _copy(source, target) + else: + _copy(source, target / source.name if dst.endswith("/") else target) + repo = root / "app" / "repo" + if repo.is_dir() and not (repo / ".git").exists(): + with (repo / ".gitignore").open("a", encoding="utf-8") as handle: + handle.write("__pycache__/\n*.pyc\n") + _git(repo, "init", "-q") + _git(repo, "config", "core.fileMode", "false") + _git(repo, "add", "-A") + _git(repo, "commit", "-qm", "baseline (graded starting point)") + shutil.rmtree(repo / ".git" / "logs", ignore_errors=True) + for src, dst in plan["baseline_copies"]: + _copy(_host(root, src), _host(root, dst)) + if include_tests: + _copy(package / "tests", root / "tests") + if include_solution and (package / "solution").is_dir(): + _copy(package / "solution", root / "solution") + venv = plan["env"].get("VENV") + if venv: + target = _host(root, venv) + if python_env is not None: + target.parent.mkdir(parents=True, exist_ok=True) + target.symlink_to(Path(python_env).resolve(), target_is_directory=True) + else: + subprocess.run([python, "-m", "venv", str(target)], check=True, + capture_output=True, text=True) + return {"executor": "rootless", "fidelity": "approximate", + "env": plan["env"], "workdir": plan["workdir"] or "/app/repo", + "replayed_copies": [list(c) for c in plan["copies"]], + "replayed_baseline_copies": [list(c) for c in plan["baseline_copies"]], + "unreplayed_dockerfile_steps": plan["unreplayed"], + "python_env": str(python_env) if python_env else f"fresh venv from {python}"} + + +def proot_argv(proot: str, root: Path, command: str, *, env: dict[str, str], cwd: str, + extra_binds: list[tuple[Path, str]] = ()) -> list[str]: + binds = [(root / name, "/" + name) for name in ("app", "opt", "logs", "tmp", "root")] + binds.append((root / "tests", "/tests")) + binds.extend(extra_binds) + argv = [proot] + for host, container in binds: + argv += ["-b", f"{Path(host).resolve()}:{container}"] + argv += ["-w", cwd, "/usr/bin/env", "-i"] + argv += [f"{key}={value}" for key, value in sorted(env.items())] + return argv + ["HOME=/root", "bash", "-c", command] + + +def _run(argv: list[str], log: Path, timeout: float | None) -> dict: + started = time.monotonic() + with log.open("w", encoding="utf-8") as handle: + try: + code = subprocess.run(argv, stdout=handle, stderr=subprocess.STDOUT, + timeout=timeout, check=False).returncode + except subprocess.TimeoutExpired: + code = None + return {"exit_code": code, "timed_out": code is None, + "seconds": round(time.monotonic() - started, 1), "log": str(log)} + + +def _toml_seconds(task: phibench.PhiTask, section: str, top_key: str, + default: float) -> float: + """``[section] timeout_sec``, else top-level ``top_key``, else the runner default. + + The suite runner parses task.toml with tomllib/tomli, so this uses the same + parser: comments after a table header, exponents and digit separators are + handled by TOML itself rather than by a numeric-prefix regex. + """ + data = tomllib.loads((task.package_root / "task.toml").read_text(encoding="utf-8")) + table = data.get(section) + value = table.get("timeout_sec") if isinstance(table, dict) else None + if not _is_number(value): + value = data.get(top_key) + return float(value) if _is_number(value) else default + + +def _is_number(value: object) -> bool: + return isinstance(value, (int, float)) and not isinstance(value, bool) + + +def _verifier_timeout(task: phibench.PhiTask) -> float: + # Lookup order and default as the suite runner (scripts/run_task.py, Task.verify_timeout): + # most packages set no [verifier] timeout_sec and rely on the 3600 s default. + return _toml_seconds(task, "verifier", "timeout_sec", 3600.0) + + +def _agent_timeout(task: phibench.PhiTask) -> float: + # As the suite runner's Task.agent_timeout: [agent] timeout_sec, agent_timeout_sec, 5400 s. + return _toml_seconds(task, "agent", "agent_timeout_sec", 5400.0) + + +def _landing(task, mode, candidate_patch, agent_command, root): + binds = [] + if mode in phibench.CONTROLS: + if mode != "noop" and not task.has_oracle: + return None, binds + binds.append((root / "solution", "/solution")) + # The suite mounts the package at /task for reference runs; some packages (lh) + # keep oracle.patch there instead of under solution/. + binds.append((task.package_root, "/task")) + return f"bash /solution/solve.sh {_CONTROL_FLAG[mode]}".strip(), binds + if mode == "candidate": + patch = Path(candidate_patch).resolve() + binds.append((patch.parent, "/candidate")) + return ("git -C /app/repo apply --whitespace=nowarn " + f"/candidate/{shlex.quote(patch.name)}"), binds + return agent_command, binds + + +_PLUGIN_MOUNT = "/opt/inferrsi-plugin" +_PLUGIN_NOTE = """ + +## InferRSI + +Use InferRSI for this task. The InferRSI Codex plugin is at `{mount}`: read +`{mount}/skills/inferrsi/SKILL.md` and run InferRSI with +`python -X utf8 {mount}/skills/inferrsi/scripts/inferrsi.py `. +""" + + +def stage_inferrsi_plugin(root: Path, plugin: Path) -> dict: + """Put a built InferRSI Codex plugin in the agent's tree and say to use InferRSI. + + This is the plugin's standard use without a client that can import its archive: + the plugin directory plus a prompt naming it. Retrieval and skill selection stay + with the agent. Returns the record of the staged plugin and the original + instruction for restoring before grading. + """ + plugin = Path(plugin).resolve() + launcher = plugin / "skills" / "inferrsi" / "scripts" / "inferrsi.py" + manifest = plugin / "runtime" / "manifest.json" + for required in (plugin / "plugin.json", plugin / "skills" / "inferrsi" / "SKILL.md", + launcher, manifest): + if not required.is_file(): + raise ValueError(f"Not a built InferRSI Codex plugin (missing {required}); " + "build one with tools/build_codex_plugin.py") + _copy(plugin, _host(root, _PLUGIN_MOUNT)) + instruction_path = root / "app" / "instruction.md" + instruction = instruction_path.read_text(encoding="utf-8") + instruction_path.write_text(instruction + _PLUGIN_NOTE.format(mount=_PLUGIN_MOUNT), + encoding="utf-8") + runtime = json.loads(manifest.read_text(encoding="utf-8")) + return {"usage": "plugin directory + prompt", "plugin": str(plugin), + "mount": _PLUGIN_MOUNT, + "plugin_version": json.loads((plugin / "plugin.json").read_text( + encoding="utf-8")).get("version"), + "runtime_version": runtime.get("runtime_version"), + "content_sha256": runtime.get("content_sha256"), + "note": _PLUGIN_NOTE.format(mount=_PLUGIN_MOUNT).strip(), + "original_instruction": instruction} + + +def run_rootless(task: phibench.PhiTask, mode: str, out: Path, *, proot: str, python: str, + python_env: Path | None = None, candidate_patch: Path | None = None, + agent_command: str | None = None, + agent_env: dict[str, str] | None = None, + inferrsi_plugin: Path | None = None) -> dict: + root = out / "root" + # The suite does not put tests/ or solution/ in the agent's container: they are + # mounted only for grading. Keep that split here, or an agent could read the + # hidden cases and the reference patch before it edits anything. + agent_step = mode == "agent" + record = stage_rootless(task, root, python=python, python_env=python_env, + include_tests=not agent_step, include_solution=not agent_step) + record["grading_assets_exposed_to_agent"] = not agent_step + original_instruction = None + if inferrsi_plugin is not None: + staged = stage_inferrsi_plugin(root, inferrsi_plugin) + original_instruction = staged.pop("original_instruction") + record["inferrsi"] = staged + env = dict(record.pop("env")) + # proot runs every step under `env -i`, which would drop the host's GPU selection: a + # run reserved on one card would see them all and land on GPU 0. Docker gets the same + # selection from --gpus. + if "CUDA_VISIBLE_DEVICES" in os.environ: + env["CUDA_VISIBLE_DEVICES"] = os.environ["CUDA_VISIBLE_DEVICES"] + record["cuda_visible_devices"] = os.environ["CUDA_VISIBLE_DEVICES"] + workdir = record.pop("workdir") + landing, binds = _landing(task, mode, candidate_patch, agent_command, root) + if landing is None: + record.update(status="skipped", reason="task ships no reference landing for this control") + return record + if agent_step: + # proot leaves the host filesystem visible, the suite clone included; cover the clone + # with an empty directory so the agent cannot read tests/ or solution/ from there. + hidden = out / "suite-hidden" + hidden.mkdir() + binds.append((hidden, str(task.suite_root))) + stage_env = {**env, "PHI_TASK": task.task_id, "PHI_INSTRUCTION": "/app/instruction.md"} + # proot passes its environment as argv, so a value put there is visible in `ps` on a + # shared host. Hand the agent step a mode-600 file inside its own root instead and + # remove it once the step is over. + env_file = root / "root" / ".phi-agent-env" + if agent_env: + env_file.write_text("".join(f"{name}={shlex.quote(value)}\n" + for name, value in sorted(agent_env.items())), + encoding="utf-8") + env_file.chmod(0o600) + landing = "set -a; . /root/.phi-agent-env; set +a; " + landing + record["landing"] = {"command": landing, **_run( + proot_argv(proot, root, landing, env=stage_env, cwd=workdir, extra_binds=binds), + out / "landing.log", _agent_timeout(task) if agent_step + else _CONTROL_LANDING_TIMEOUT if mode in phibench.CONTROLS else None)} + if env_file.exists(): + env_file.unlink() + if original_instruction is not None: + # Hand the grader the task's own statement, as without the InferRSI note. + (root / "app" / "instruction.md").write_text(original_instruction, encoding="utf-8") + capture_binds = [(task.package_root / "pre_artifacts.sh", "/phi/pre_artifacts.sh")] + record["capture"] = _run( + proot_argv(proot, root, "bash /phi/pre_artifacts.sh", env=env, cwd=workdir, + extra_binds=capture_binds), + out / "capture.log", None) + verifier = root / "logs" / "verifier" + if agent_step: + # Grade from a clean slate: nothing the agent wrote under /tests or /logs/verifier + # (a planted reward.json, say) may survive into the score. + shutil.rmtree(root / "tests", ignore_errors=True) + _copy(task.package_root / "tests", root / "tests") + shutil.rmtree(verifier, ignore_errors=True) + verifier.mkdir() + record["grade"] = _run(proot_argv(proot, root, "bash /tests/test.sh", env=env, cwd=workdir), + out / "verify.log", _verifier_timeout(task)) + record["artifacts"] = str(root / "logs" / "artifacts") + record["verifier_dir"] = str(verifier) + landed = record["landing"]["exit_code"] == 0 + if agent_step and not landed: + # The suite runner grades whatever an agent left, timed out or failed alike. + record["warnings"] = ["agent_timed_out" if record["landing"]["timed_out"] + else "agent_exited_nonzero"] + record["status"] = "graded" if landed or agent_step else "landing_failed" + return record + + +def docker_argv(task: phibench.PhiTask, mode: str, out: Path, *, python: str, + runner_args: list[str] = ()) -> list[str]: + if mode not in phibench.CONTROLS: + raise ValueError("The docker executor runs reference controls only; score candidates " + "with the suite runner's own --agent options via runner arguments") + return [python, str(task.suite_root / "scripts" / "run_task.py"), "--task", task.task_id, + "--agent", "oracle", "--oracle-variant", mode, "--runs-dir", str(out), + "--run-name", f"{task.name}-{mode}", *runner_args] + + +def run_docker(task: phibench.PhiTask, mode: str, out: Path, *, python: str, + runner_args: list[str] = ()) -> dict: + out.mkdir(parents=True, exist_ok=True) + record = {"executor": "docker", "fidelity": "suite-reference", + "grade": _run(docker_argv(task, mode, out, python=python, runner_args=runner_args), + out / "runner.log", None)} + run_dir = out / f"{task.name}-{mode}" + record["verifier_dir"] = str(run_dir / "verifier") + record["artifacts"] = str(run_dir / "artifacts") + run_json = run_dir / "run.json" + if run_json.is_file(): + runner = json.loads(run_json.read_text(encoding="utf-8")) + record["runner_status"] = runner.get("status") + # The runner keeps verifier_timed_out and its other stage failures in run.json, not in + # the verifier directory; carry them into the score. + record["runner_hard_fail_reasons"] = [str(r) for r in runner.get("hard_fail_reasons") + or []] + if runner.get("status") == "skipped": + record.update(status="skipped", reason=runner.get("skip_reason")) + return record + record["status"] = "graded" + return record + + +# --------------------------------------------------------------------------- entry points + + +def run_mode(task: phibench.PhiTask, mode: str, out: Path, *, executor: str, + proot: str | None = None, python: str | None = None, + python_env: Path | None = None, candidate_patch: Path | None = None, + agent_command: str | None = None, agent_env: dict[str, str] | None = None, + inferrsi_plugin: Path | None = None, runner_args: list[str] = ()) -> dict: + if mode not in MODES: + raise ValueError(f"Unknown mode: {mode}") + if executor not in EXECUTORS: + raise ValueError(f"Unknown executor: {executor}") + if (mode == "candidate") != (candidate_patch is not None): + raise ValueError("--candidate-patch is required for, and only for, mode candidate") + if (mode == "agent") != bool(agent_command): + raise ValueError("--agent-command is required for, and only for, mode agent") + if mode != "agent" and agent_env: + raise ValueError("--agent-env is only for mode agent") + if inferrsi_plugin is not None and (mode != "agent" or executor != "rootless"): + raise ValueError("--inferrsi-plugin is only for mode agent with the rootless executor") + python = python or sys.executable + out = Path(out) / mode + if out.exists(): + raise ValueError(f"Output directory already exists: {out}") + out.mkdir(parents=True) + if executor == "docker": + record = run_docker(task, mode, out, python=python, runner_args=list(runner_args)) + else: + if not proot or not shutil.which(proot): + raise ValueError("The rootless executor needs a proot binary (--proot)") + record = run_rootless(task, mode, out, proot=proot, python=python, python_env=python_env, + candidate_patch=candidate_patch, agent_command=agent_command, + agent_env=agent_env, inferrsi_plugin=inferrsi_plugin) + record = {"suite": phibench.SUITE, "task": task.describe(), "mode": mode, **record} + if record.get("status") == "graded": + record["score"] = phibench.read_reward(Path(record["verifier_dir"])) + reasons = record["score"]["hard_fail_reasons"] + grade = record["grade"] + # As the suite runner does (rc in 124/137): a grader cut off at its timeout, by us or + # by its own `timeout`/a kill, is a hard fail. + if ((grade.get("timed_out") or grade.get("exit_code") in (124, 137)) + and "verifier_timed_out" not in reasons): + reasons.append("verifier_timed_out") + reasons.extend(r for r in record.get("runner_hard_fail_reasons", ()) if r not in reasons) + if record["score"]["reward"] is None: + # As the suite runner does: no readable reward is a failed run, not a score. + if "no_reward_file" not in reasons: + reasons.append("no_reward_file") + if "verifier_timed_out" in reasons: + # A grader cut off at its timeout measured nothing, even when it left a reward + # behind: keep the raw score for audit, but never report it as a valid grade. + record["status"] = "verifier_timeout" + elif record["score"]["reward"] is None: + record["status"] = "no_reward" + patch = Path(record["artifacts"]) / "model.patch" + record["model_patch_bytes"] = patch.stat().st_size if patch.is_file() else None + (out / "result.json").write_text(json.dumps(record, indent=2, ensure_ascii=False), + encoding="utf-8") + return record + + +def selfcheck(task: phibench.PhiTask, out: Path, *, oracle_tolerance: float | None, + **options) -> dict: + """Run noop, negative and oracle, then judge them with the suite's expectations.""" + results = {control: run_mode(task, control, out, **options) + for control in phibench.CONTROLS} + assessment = phibench.assess_controls( + task, {control: result.get("score") for control, result in results.items()}, + oracle_tolerance=oracle_tolerance) + assessment["runs"] = { + control: {"status": result.get("status"), "score": result.get("score"), + "result": str(Path(out) / control / "result.json")} + for control, result in results.items()} + executor = options.get("executor") + assessment["executor"] = executor + if executor == "rootless": + assessment["fidelity_note"] = ("rootless replay of the task image; Dockerfile steps it " + "did not run are listed in each result.json") + Path(out, "selfcheck.json").write_text(json.dumps(assessment, indent=2, ensure_ascii=False), + encoding="utf-8") + return assessment + + +def list_command(root: Path) -> list[dict]: + return [task.describe() for task in phibench.list_tasks(root)] + + +def command(args) -> tuple[dict | list, int]: + """CLI adapter: returns (printable result, exit status).""" + root = Path(args.root) + if args.external_action == "list": + return list_command(root), 0 + task = phibench.get_task(root, args.task) + options = {"executor": args.executor, "proot": args.proot, "python": args.python, + "python_env": args.python_env, "runner_args": args.runner_arg or []} + agent_env = {} + for name in getattr(args, "agent_env", None) or []: + if name not in os.environ: + raise ValueError(f"--agent-env {name}: not set in this process") + agent_env[name] = os.environ[name] + if args.external_action == "selfcheck": + result = selfcheck(task, Path(args.output), oracle_tolerance=args.oracle_tolerance, + **options) + return result, 0 if result["verdict"] == "PASS" else 1 + result = run_mode(task, args.mode, Path(args.output), candidate_patch=args.candidate_patch, + agent_command=args.agent_command, agent_env=agent_env, + inferrsi_plugin=getattr(args, "inferrsi_plugin", None), **options) + return result, 0 if result.get("status") == "graded" else 1 + + +__all__ = ["EXECUTORS", "MODES", "command", "docker_argv", "list_command", "parse_dockerfile", + "proot_argv", "run_mode", "selfcheck", "stage_inferrsi_plugin", "stage_rootless"] diff --git a/src/inferrsi/benchmark/README.md b/src/inferrsi/benchmark/README.md index f84e6e1df..a156c0812 100644 --- a/src/inferrsi/benchmark/README.md +++ b/src/inferrsi/benchmark/README.md @@ -12,6 +12,9 @@ delivers Knowledge context where the workflow calls for it. - [`preparation.py`](preparation.py) exposes `PreparationService` to validate a frozen protocol and pin its resources. [`assessment.py`](assessment.py) exposes `AssessmentService` to assess fixed retained evidence offline. +- [`external/`](external/) reads public-suite task packages (Φ-Bench first) and + judges their graders' output; Apps runs them with `inferrsi benchmarks external`. + See [public benchmarks](../../../docs/benchmarks/public-benchmarks.md). - [`metrics.py`](metrics.py) reads and validates trial metrics. Task packages supply their own workload semantics and correctness rules. diff --git a/src/inferrsi/benchmark/external/__init__.py b/src/inferrsi/benchmark/external/__init__.py new file mode 100644 index 000000000..21eb623e3 --- /dev/null +++ b/src/inferrsi/benchmark/external/__init__.py @@ -0,0 +1,7 @@ +"""Adapters for public benchmark suites whose tasks and graders live outside InferRSI. + +A suite adapter reads one task package, names the reference controls the suite +ships, and judges the suite grader's own output. Executing a task (containers, +rootless staging, agents) belongs to Apps; see +``inferrsi.apps.workflows.external_benchmark``. +""" diff --git a/src/inferrsi/benchmark/external/phibench.py b/src/inferrsi/benchmark/external/phibench.py new file mode 100644 index 000000000..c68ba29d9 --- /dev/null +++ b/src/inferrsi/benchmark/external/phibench.py @@ -0,0 +1,223 @@ +"""Read Φ-Bench task packages and judge its grader output. + +Φ-Bench (arXiv:2609.10226, Apache-2.0) ships every task as a Docker build +context with a starting tree, a grader under ``tests/`` and reference landings +under ``solution/``. This module only reads a local clone of the suite; it +never builds, runs or edits a task. + +The control expectations follow the suite's own self-check (README "Important +Conventions" and SCORING.md): + +- ``noop`` leaves the starting tree alone and must score 0; +- ``negative`` lands a known-bad change and must score 0; +- ``oracle`` lands the reference change. Implementation tasks must score 1.0. + Performance tasks score 0 by design when they tie the calibrated anchor + (curve ``reward_md_log_speedup_v2_oracle_zero``), so the oracle is judged on + passing every gate and reproducing ``ref_speedup`` within a caller-supplied + relative tolerance. +""" + +from __future__ import annotations + +import json +import math +import re +from dataclasses import dataclass +from pathlib import Path + +SUITE = "phibench" +CONTROLS = ("noop", "negative", "oracle") +INDEX = "tasks_index.json" +_TASK_ID = re.compile(r"(kfc|lh|e2e)/[A-Za-z0-9][A-Za-z0-9_.-]*") + + +@dataclass(frozen=True) +class PhiTask: + """One task entry from ``tasks_index.json`` resolved against a local clone.""" + + suite_root: Path + bench: str + name: str + package_root: Path + gpus: int + reward_class: str + ref_speedup: float | None + primary_edit_paths: tuple[str, ...] + has_oracle: bool + max_submissions: int | None + + @property + def task_id(self) -> str: + return f"{self.bench}/{self.name}" + + def describe(self) -> dict: + return { + "suite": SUITE, + "task": self.task_id, + "package_root": str(self.package_root), + "gpus": self.gpus, + "reward_class": self.reward_class, + "ref_speedup": self.ref_speedup, + "primary_edit_paths": list(self.primary_edit_paths), + "has_oracle": self.has_oracle, + "max_submissions": self.max_submissions, + } + + +def _load_index(root: Path) -> dict: + path = root / INDEX + if not path.is_file(): + raise ValueError(f"Not a Φ-Bench clone (missing {INDEX}): {root}") + index = json.loads(path.read_text(encoding="utf-8")) + if not isinstance(index, dict) or not isinstance(index.get("tasks"), list): + raise ValueError(f"{path} has no task list") + return index + + +def _task(root: Path, entry: dict) -> PhiTask: + package = (root / entry["package_root"]).resolve() + if root.resolve() not in package.parents: + raise ValueError(f"Task package escapes the suite root: {entry['package_root']}") + ref = entry.get("ref_speedup") + return PhiTask( + suite_root=root.resolve(), + bench=entry["bench"], + name=entry["task"], + package_root=package, + gpus=int(entry.get("gpus") or 0), + reward_class=entry.get("reward_class") or "unknown", + ref_speedup=float(ref) if ref is not None else None, + primary_edit_paths=tuple(entry.get("primary_edit_paths") or ()), + has_oracle=bool(entry.get("has_oracle")), + max_submissions=entry.get("max_submissions"), + ) + + +def list_tasks(root: Path) -> list[PhiTask]: + root = Path(root) + return [_task(root, entry) for entry in _load_index(root)["tasks"]] + + +def get_task(root: Path, task_id: str) -> PhiTask: + if not _TASK_ID.fullmatch(task_id): + raise ValueError("Φ-Bench task IDs look like kfc/, lh/ or e2e/: " + f"{task_id!r}") + bench, name = task_id.split("/", 1) + for entry in _load_index(Path(root))["tasks"]: + if entry.get("bench") == bench and entry.get("task") == name: + task = _task(Path(root), entry) + if not (task.package_root / "task.toml").is_file(): + raise ValueError(f"Task package has no task.toml: {task.package_root}") + return task + raise ValueError(f"Unknown Φ-Bench task: {task_id}") + + +def _finite(value) -> float | None: + try: + number = float(value) + except (TypeError, ValueError): + return None + return number if math.isfinite(number) else None + + +def read_reward(verifier_dir: Path) -> dict: + """Read the grader's ``reward.json`` and hard-fail reasons, as Φ-Bench's runner does.""" + verifier_dir = Path(verifier_dir) + result = {"reward": None, "speedup": None, "ref_speedup": None, + "hard_fail_reasons": [], "schema_version": None, "source": None} + # The runner reads reward.json, then metrics.json: the first readable reward wins and + # hard-fail reasons from both are kept (some graders write them only to metrics.json). + for name in ("reward.json", "metrics.json"): + path = verifier_dir / name + if not path.is_file(): + continue + try: + data = json.loads(path.read_text(encoding="utf-8")) + except ValueError: + continue + if not isinstance(data, dict): + continue + if result["reward"] is None: + result["reward"] = _finite(data.get("reward")) + result["source"] = name if result["reward"] is not None else None + for key in ("speedup", "ref_speedup"): + if result[key] is None: + result[key] = _finite(data.get(key)) + if result["schema_version"] is None: + result["schema_version"] = data.get("schema_version") + for reason in data.get("hard_fail_reasons") or []: + if str(reason) not in result["hard_fail_reasons"]: + result["hard_fail_reasons"].append(str(reason)) + if result["reward"] is None and (verifier_dir / "reward.txt").is_file(): + text = re.sub(r"[^0-9eE.+-]", "", (verifier_dir / "reward.txt").read_text().strip()) + result["reward"] = _finite(text) + result["source"] = "reward.txt" if result["reward"] is not None else None + state = verifier_dir / "verifier_state.json" + if state.is_file(): + try: + data = json.loads(state.read_text(encoding="utf-8")) + except ValueError: + data = {} + for reason in (data.get("hard_fail_reasons") or []) if isinstance(data, dict) else []: + if str(reason) not in result["hard_fail_reasons"]: + result["hard_fail_reasons"].append(str(reason)) + return result + + +def judge_control(task: PhiTask, control: str, score: dict | None, *, + oracle_tolerance: float | None = None) -> dict: + """Judge one control against the suite's documented expectation. + + Returns ``{"control", "verdict", "reason"}`` with verdict PASS, FAIL or + INCONCLUSIVE. A missing score is INCONCLUSIVE, never PASS. + """ + if control not in CONTROLS: + raise ValueError(f"Unknown control: {control}") + if not score or score.get("reward") is None: + return {"control": control, "verdict": "INCONCLUSIVE", + "reason": "grader wrote no readable reward"} + reward = score["reward"] + if "verifier_timed_out" in score.get("hard_fail_reasons", ()): + # A grader cut off at its timeout measured nothing: its 0 is not a control result. + return {"control": control, "verdict": "INCONCLUSIVE", + "reason": "grader timed out before finishing"} + if control in ("noop", "negative"): + if reward == 0.0: + return {"control": control, "verdict": "PASS", "reason": "reward is 0 as expected"} + return {"control": control, "verdict": "FAIL", + "reason": f"{control} must score 0, got {reward}"} + if score["hard_fail_reasons"]: + return {"control": control, "verdict": "FAIL", + "reason": "oracle hit hard gates: " + ", ".join(score["hard_fail_reasons"])} + if task.reward_class == "implementation": + if reward == 1.0: + return {"control": control, "verdict": "PASS", "reason": "oracle scores 1.0"} + return {"control": control, "verdict": "FAIL", + "reason": f"implementation oracle must score 1.0, got {reward}"} + anchor = score.get("ref_speedup") or task.ref_speedup + if oracle_tolerance is None: + return {"control": control, "verdict": "INCONCLUSIVE", + "reason": "no oracle tolerance was frozen for this check"} + if score.get("speedup") is None or not anchor: + return {"control": control, "verdict": "INCONCLUSIVE", + "reason": "grader reported no speedup or anchor"} + ratio = score["speedup"] / anchor + if abs(ratio - 1.0) <= oracle_tolerance: + return {"control": control, "verdict": "PASS", + "reason": f"oracle speedup {score['speedup']} reproduces anchor {anchor} " + f"(ratio {ratio:.4f}, tolerance {oracle_tolerance})"} + return {"control": control, "verdict": "FAIL", + "reason": f"oracle speedup {score['speedup']} differs from anchor {anchor} " + f"(ratio {ratio:.4f}, tolerance {oracle_tolerance}); " + "re-calibrate on this host"} + + +def assess_controls(task: PhiTask, scores: dict[str, dict | None], *, + oracle_tolerance: float | None = None) -> dict: + """Combine the three control judgments into one self-check verdict.""" + checks = [judge_control(task, control, scores.get(control), + oracle_tolerance=oracle_tolerance) for control in CONTROLS] + verdicts = {check["verdict"] for check in checks} + verdict = next((v for v in ("FAIL", "INCONCLUSIVE") if v in verdicts), "PASS") + return {"suite": SUITE, "task": task.task_id, "verdict": verdict, + "oracle_tolerance": oracle_tolerance, "checks": checks} diff --git a/tests/benchmark/test_external_phibench.py b/tests/benchmark/test_external_phibench.py new file mode 100644 index 000000000..03fcb07c2 --- /dev/null +++ b/tests/benchmark/test_external_phibench.py @@ -0,0 +1,616 @@ +"""Φ-Bench adapter: package reading, control judgment and executor assembly (CPU only).""" + +import json +import os +import shutil +import subprocess +import sys +from pathlib import Path + +import pytest + +from inferrsi.apps.cli import main +from inferrsi.apps.workflows import external_benchmark as ext +from inferrsi.benchmark.external import phibench + +TASK = "kfc/fake-planner" + +DOCKERFILE = """# syntax=docker/dockerfile:1 +FROM python:3.11-slim-bookworm +ARG ARCH_LIST=8.9 +ENV DEBIAN_FRONTEND=noninteractive TZ=UTC \\ + PYTHONUNBUFFERED=1 +RUN apt-get update && apt-get install -y git +ENV VENV=/opt/kernelbench-venv +RUN python3 -m venv "$VENV" +ENV PATH=$VENV/bin:$PATH +RUN mkdir -p /app/repo /logs/verifier +COPY environment/repo/ /app/repo/ +COPY instruction.md /app/instruction.md +RUN cd /app/repo && git init -q && git add -A && git commit -qm baseline +RUN mkdir -p /opt/verifier-baseline \\ + && cp "/app/repo/planner.py" "/opt/verifier-baseline/planner.py" +RUN python - <<'PY' +COPY should-not-be-read /nowhere +PY +ENV PYTHONPATH=/app/repo ARCH=${ARCH_LIST} +WORKDIR /app/repo +""" + +# A grader that scores the planner's VALUE: 1 -> baseline, 4 -> reference, 0 -> broken. +TEST_SH = """#!/bin/bash +mkdir -p /logs/verifier +v=$(python3 -c 'import planner; print(planner.VALUE)') +base=$(python3 -c 'import runpy +print(runpy.run_path("/opt/verifier-baseline/planner.py")["VALUE"])') +python3 - "$v" "$base" <<'PY' +import json, sys +v, base = int(sys.argv[1]), int(sys.argv[2]) +hard = [] +if v == 0: + hard.append("hidden_correctness_failed") +speed = (v / base) if v else 1.0 +if speed <= 1 and not hard: + hard.append("speedup_not_above_baseline") +json.dump({"reward": 0.0, "speedup": speed, "ref_speedup": 4.0, + "hard_fail_reasons": hard}, open("/logs/verifier/reward.json", "w")) +PY +""" + +SOLVE_SH = """#!/bin/bash +case "${1:-}" in + --noop) exit 0 ;; + --negative) sed -i 's/VALUE = 1/VALUE = 0/' /app/repo/planner.py ;; + *) sed -i 's/VALUE = 1/VALUE = 4/' /app/repo/planner.py ;; +esac +""" + +PRE_ARTIFACTS = """#!/bin/bash +mkdir -p /logs/artifacts +git -C /app/repo diff > /logs/artifacts/model.patch +echo /app/repo/planner.py > /logs/artifacts/model_files.txt +""" + + +@pytest.fixture +def suite(tmp_path): + root = tmp_path / "phibench" + package = root / "tasks" / "kfc" / "fake-planner" / "task" + (package / "environment" / "repo").mkdir(parents=True) + (package / "environment" / "Dockerfile").write_text(DOCKERFILE) + (package / "environment" / "repo" / "planner.py").write_text("VALUE = 1\n") + (package / "instruction.md").write_text("Make VALUE larger.\n") + (package / "task.toml").write_text('[verifier]\ntimeout_sec = 60\n') + (package / "tests").mkdir() + (package / "tests" / "test.sh").write_text(TEST_SH) + (package / "solution").mkdir() + (package / "solution" / "solve.sh").write_text(SOLVE_SH) + (package / "pre_artifacts.sh").write_text(PRE_ARTIFACTS) + index = {"tasks": [{ + "bench": "kfc", "task": "fake-planner", + "package_root": "tasks/kfc/fake-planner/task", "gpus": 0, + "primary_edit_paths": ["/app/repo/planner.py"], "reward_class": "performance", + "ref_speedup": 4.0, "has_oracle": True, "max_submissions": 1, + }]} + (root / "tasks_index.json").write_text(json.dumps(index)) + return root + + +def score(reward, speedup=None, hard=(), ref=None): + return {"reward": reward, "speedup": speedup, "ref_speedup": ref, + "hard_fail_reasons": list(hard)} + + +def test_reads_task_from_index(suite): + task = phibench.get_task(suite, TASK) + assert task.task_id == TASK + assert task.package_root == (suite / "tasks/kfc/fake-planner/task").resolve() + assert task.reward_class == "performance" and task.ref_speedup == 4.0 + assert [t.task_id for t in phibench.list_tasks(suite)] == [TASK] + + +@pytest.mark.parametrize("task_id", ["fake-planner", "kfc/../x", "other/fake-planner"]) +def test_rejects_malformed_task_ids(suite, task_id): + with pytest.raises(ValueError): + phibench.get_task(suite, task_id) + + +def test_unknown_task_and_missing_index(suite, tmp_path): + with pytest.raises(ValueError, match="Unknown"): + phibench.get_task(suite, "kfc/absent") + with pytest.raises(ValueError, match="Not a Φ-Bench clone"): + phibench.list_tasks(tmp_path / "empty") + + +def test_package_root_cannot_escape_suite(suite): + index = json.loads((suite / "tasks_index.json").read_text()) + index["tasks"][0]["package_root"] = "../elsewhere" + (suite / "tasks_index.json").write_text(json.dumps(index)) + with pytest.raises(ValueError, match="escapes"): + phibench.get_task(suite, TASK) + + +def test_read_reward_merges_state_and_falls_back_to_text(tmp_path): + (tmp_path / "reward.json").write_text(json.dumps( + {"reward": 0.25, "speedup": 5.0, "ref_speedup": 4.0, "hard_fail_reasons": ["a"], + "schema_version": "v3"})) + (tmp_path / "verifier_state.json").write_text(json.dumps({"hard_fail_reasons": ["a", "b"]})) + result = phibench.read_reward(tmp_path) + assert result["reward"] == 0.25 and result["speedup"] == 5.0 + assert result["hard_fail_reasons"] == ["a", "b"] and result["source"] == "reward.json" + (tmp_path / "reward.json").write_text("{broken") + (tmp_path / "reward.txt").write_text("1.0\n") + assert phibench.read_reward(tmp_path)["reward"] == 1.0 + assert phibench.read_reward(tmp_path / "missing")["reward"] is None + + +def test_read_reward_also_reads_metrics_json_like_the_runner(tmp_path): + (tmp_path / "metrics.json").write_text(json.dumps( + {"reward": 0.0, "speedup": 2.0, "hard_fail_reasons": ["build_check_failed"]})) + (tmp_path / "reward.txt").write_text("0.0\n") + result = phibench.read_reward(tmp_path) + assert result["reward"] == 0.0 and result["source"] == "metrics.json" + assert result["speedup"] == 2.0 and result["hard_fail_reasons"] == ["build_check_failed"] + + +@pytest.mark.parametrize(("control", "value", "verdict"), [ + ("noop", score(0.0, 1.0, ["speedup_not_above_baseline"]), "PASS"), + ("noop", score(0.2, 5.0), "FAIL"), + ("negative", score(0.0, 1.0, ["hidden_correctness_failed"]), "PASS"), + ("negative", score(0.5), "FAIL"), + ("negative", None, "INCONCLUSIVE"), + ("oracle", score(0.0, 4.0001), "PASS"), + ("oracle", score(0.0, 3.0), "FAIL"), + ("oracle", score(0.0, 4.0, ["hidden_correctness_failed"]), "FAIL"), + ("oracle", score(0.0), "INCONCLUSIVE"), + ("noop", score(0.0, hard=["verifier_timed_out"]), "INCONCLUSIVE"), + ("negative", score(0.0, hard=["verifier_timed_out"]), "INCONCLUSIVE"), + ("oracle", score(0.0, 4.0, ["verifier_timed_out"]), "INCONCLUSIVE"), +]) +def test_judges_controls_against_suite_expectations(suite, control, value, verdict): + task = phibench.get_task(suite, TASK) + check = phibench.judge_control(task, control, value, oracle_tolerance=0.001) + assert check["verdict"] == verdict + + +def test_performance_oracle_without_frozen_tolerance_is_inconclusive(suite): + task = phibench.get_task(suite, TASK) + check = phibench.judge_control(task, "oracle", score(0.0, 4.0)) + assert check["verdict"] == "INCONCLUSIVE" + + +def test_implementation_oracle_must_score_one(suite): + task = phibench.get_task(suite, TASK) + task = phibench.PhiTask(**{**task.__dict__, "reward_class": "implementation"}) + assert phibench.judge_control(task, "oracle", score(1.0))["verdict"] == "PASS" + assert phibench.judge_control(task, "oracle", score(0.0))["verdict"] == "FAIL" + + +def test_assessment_takes_the_worst_verdict(suite): + task = phibench.get_task(suite, TASK) + good = {"noop": score(0.0), "negative": score(0.0), "oracle": score(0.0, 4.0)} + assert phibench.assess_controls(task, good, oracle_tolerance=0.0)["verdict"] == "PASS" + assert phibench.assess_controls(task, {**good, "noop": None}, + oracle_tolerance=0.0)["verdict"] == "INCONCLUSIVE" + assert phibench.assess_controls(task, {**good, "negative": score(1.0)}, + oracle_tolerance=0.0)["verdict"] == "FAIL" + + +def test_parse_dockerfile_keeps_replayable_steps_and_lists_the_rest(suite): + plan = ext.parse_dockerfile(suite / "tasks/kfc/fake-planner/task/environment/Dockerfile") + assert plan["copies"] == [("environment/repo/", "/app/repo/"), + ("instruction.md", "/app/instruction.md")] + assert plan["baseline_copies"] == [ + ("/app/repo/planner.py", "/opt/verifier-baseline/planner.py")] + assert plan["env"]["PATH"].startswith("/opt/kernelbench-venv/bin:/usr/local/sbin") + assert plan["env"]["PYTHONPATH"] == "/app/repo" and plan["env"]["TZ"] == "UTC" + assert "DEBIAN_FRONTEND" not in plan["env"] and plan["env"]["ARCH"] == "8.9" + assert "ARCH_LIST" not in plan["env"] + assert plan["workdir"] == "/app/repo" + assert any(step.startswith("RUN apt-get") for step in plan["unreplayed"]) + assert any(step.startswith("RUN python - <<") for step in plan["unreplayed"]) + + +def test_stage_rootless_rebuilds_the_image_layout(suite, tmp_path): + task = phibench.get_task(suite, TASK) + env_dir = tmp_path / "prepared-env" + env_dir.mkdir() + record = ext.stage_rootless(task, tmp_path / "root", python="python3", python_env=env_dir) + root = tmp_path / "root" + repo = root / "app" / "repo" + count = subprocess.run(["git", "-C", str(repo), "rev-list", "--count", "HEAD"], + capture_output=True, text=True, check=True).stdout.strip() + status = subprocess.run(["git", "-C", str(repo), "status", "--porcelain"], + capture_output=True, text=True, check=True).stdout + assert count == "1" and status == "" + assert (root / "opt/verifier-baseline/planner.py").read_text() == "VALUE = 1\n" + assert (root / "app/instruction.md").is_file() and (root / "tests/test.sh").is_file() + assert (root / "opt/kernelbench-venv").resolve() == env_dir.resolve() + assert record["fidelity"] == "approximate" and record["unreplayed_dockerfile_steps"] + with pytest.raises(ValueError, match="already exists"): + ext.stage_rootless(task, root, python="python3", python_env=env_dir) + + +def test_proot_argv_maps_container_paths(tmp_path): + argv = ext.proot_argv("proot", tmp_path, "bash /tests/test.sh", env={"A": "1"}, + cwd="/app/repo", extra_binds=[(tmp_path / "s", "/solution")]) + pairs = [argv[i + 1] for i, item in enumerate(argv) if item == "-b"] + assert f"{tmp_path.resolve() / 'app'}:/app" in pairs + assert f"{tmp_path.resolve() / 'tests'}:/tests" in pairs + assert f"{tmp_path.resolve() / 's'}:/solution" in pairs + assert argv[argv.index("-w") + 1] == "/app/repo" + assert argv[-4:] == ["HOME=/root", "bash", "-c", "bash /tests/test.sh"] + assert "A=1" in argv + + +def test_docker_executor_delegates_controls_to_the_suite_runner(suite, tmp_path): + task = phibench.get_task(suite, TASK) + argv = ext.docker_argv(task, "negative", tmp_path, python="python3", + runner_args=["--build-network", "host"]) + assert argv[1] == str(suite.resolve() / "scripts" / "run_task.py") + assert argv[argv.index("--oracle-variant") + 1] == "negative" + assert argv[argv.index("--agent") + 1] == "oracle" + assert argv[-2:] == ["--build-network", "host"] + with pytest.raises(ValueError, match="reference controls only"): + ext.docker_argv(task, "candidate", tmp_path, python="python3") + + +def test_docker_run_keeps_the_runners_hard_fails(suite, tmp_path): + # The runner writes verifier_timed_out into run.json, not into the verifier directory. + runner = suite / "scripts" / "run_task.py" + runner.parent.mkdir() + runner.write_text( + "import json, os, sys\n" + "a = sys.argv\n" + "run = os.path.join(a[a.index('--runs-dir') + 1], a[a.index('--run-name') + 1])\n" + "os.makedirs(os.path.join(run, 'verifier'))\n" + "json.dump({'reward': 0.0}, open(os.path.join(run, 'verifier', 'reward.json'), 'w'))\n" + "json.dump({'status': 'ok', 'hard_fail_reasons': ['verifier_timed_out']},\n" + " open(os.path.join(run, 'run.json'), 'w'))\n") + task = phibench.get_task(suite, TASK) + result = ext.run_mode(task, "noop", tmp_path / "out", executor="docker", + python=sys.executable) + assert result["status"] == "verifier_timeout" + assert result["score"]["hard_fail_reasons"] == ["verifier_timed_out"] + assert result["score"]["reward"] == 0.0 + assert phibench.judge_control(task, "noop", result["score"])["verdict"] == "INCONCLUSIVE" + + +@pytest.mark.parametrize(("mode", "options", "message"), [ + ("candidate", {}, "candidate-patch"), + ("oracle", {"candidate_patch": Path("x.patch")}, "candidate-patch"), + ("agent", {}, "agent-command"), + ("oracle", {"agent_env": {"A": "1"}}, "agent-env"), + ("bogus", {}, "Unknown mode"), +]) +def test_run_mode_validates_inputs(suite, tmp_path, mode, options, message): + task = phibench.get_task(suite, TASK) + with pytest.raises(ValueError, match=message): + ext.run_mode(task, mode, tmp_path / "out", executor="rootless", proot="proot", **options) + + +def test_agent_timeout_comes_from_the_task(suite): + task = phibench.get_task(suite, TASK) + assert ext._agent_timeout(task) == 5400.0 + (task.package_root / "task.toml").write_text( + "[agent]\ntimeout_sec = 21600\n\n[verifier]\ntimeout_sec = 60\n") + assert ext._agent_timeout(task) == 21600.0 + + +def test_timeouts_fall_back_like_the_suite_runner(suite): + # Most packages set no [verifier] timeout_sec; the runner then uses top-level + # timeout_sec or 3600 s, never "no limit". + task = phibench.get_task(suite, TASK) + (task.package_root / "task.toml").write_text("[verifier]\nentrypoint = \"tests/test.sh\"\n") + assert ext._verifier_timeout(task) == 3600.0 + (task.package_root / "task.toml").write_text( + "timeout_sec = 900\nagent_timeout_sec = 1200\n\n[verifier]\nmode = \"shared\"\n") + assert ext._verifier_timeout(task) == 900.0 and ext._agent_timeout(task) == 1200.0 + + +def test_timeouts_parse_like_the_suites_toml(suite): + # david6666666's regressions: TOML digit separators are one number, and an + # indented key inside [verifier] still counts instead of falling back. + task = phibench.get_task(suite, TASK) + (task.package_root / "task.toml").write_text("[verifier]\ntimeout_sec = 1_000\n") + assert ext._verifier_timeout(task) == 1000.0 + (task.package_root / "task.toml").write_text("[verifier]\n timeout_sec = 42\n") + assert ext._verifier_timeout(task) == 42.0 + (task.package_root / "task.toml").write_text( + "[verifier.environment]\ntimeout_sec = 7\n\n[verifier]\nmode = \"shared\"\n") + assert ext._verifier_timeout(task) == 3600.0 + # A comment after the table header and an exponent are ordinary TOML too. + (task.package_root / "task.toml").write_text("[verifier] # grader\n timeout_sec = 42\n") + assert ext._verifier_timeout(task) == 42.0 + (task.package_root / "task.toml").write_text("[verifier]\ntimeout_sec = 1e3\n") + assert ext._verifier_timeout(task) == 1000.0 + + +def test_cli_lists_suite_tasks(suite, capsys): + assert main(["benchmarks", "external", "list", "--root", str(suite)]) == 0 + assert [t["task"] for t in json.loads(capsys.readouterr().out)] == [TASK] + + +PROOT = os.environ.get("INFERRSI_TEST_PROOT") or shutil.which("proot") + + +@pytest.mark.skipif(not PROOT, reason="needs proot (set INFERRSI_TEST_PROOT)") +def test_rootless_selfcheck_and_candidate_end_to_end(suite, tmp_path): + task = phibench.get_task(suite, TASK) + options = {"executor": "rootless", "proot": PROOT, "python": "python3"} + result = ext.selfcheck(task, tmp_path / "out", oracle_tolerance=0.0, **options) + assert result["verdict"] == "PASS", result + assert result["runs"]["negative"]["score"]["hard_fail_reasons"] == ["hidden_correctness_failed"] + patch = tmp_path / "cand.patch" + patch.write_text((tmp_path / "out/oracle/root/logs/artifacts/model.patch").read_text()) + scored = ext.run_mode(task, "candidate", tmp_path / "out", candidate_patch=patch, **options) + assert scored["score"]["speedup"] == 4.0 and scored["model_patch_bytes"] > 0 + agent = ext.run_mode(task, "agent", tmp_path / "agent", **options, + agent_env={"PHI_TEST_TOKEN": "forwarded"}, + agent_command="test ! -e /tests && test ! -e /solution && " + "test \"$PHI_TEST_TOKEN\" = forwarded && " + "test -f $PHI_INSTRUCTION && " + "sed -i 's/VALUE = 1/VALUE = 2/' planner.py") + assert agent["score"]["speedup"] == 2.0 and agent["score"]["hard_fail_reasons"] == [] + assert agent["grading_assets_exposed_to_agent"] is False + assert (tmp_path / "agent/agent/root/tests/test.sh").is_file() + + + +@pytest.fixture(scope="module") +def plugin(tmp_path_factory): + """A real built InferRSI Codex plugin, as a user would install it.""" + out = tmp_path_factory.mktemp("plugin") / "inferrsi" + repo = Path(__file__).resolve().parents[2] + subprocess.run([sys.executable, str(repo / "tools" / "build_codex_plugin.py"), + "--output", str(out)], check=True, capture_output=True, text=True) + return out + + +def test_inferrsi_plugin_is_only_for_rootless_agent_mode(suite, tmp_path): + task = phibench.get_task(suite, TASK) + with pytest.raises(ValueError, match="inferrsi-plugin"): + ext.run_mode(task, "oracle", tmp_path / "a", executor="rootless", proot="proot", + inferrsi_plugin=Path("p")) + with pytest.raises(ValueError, match="inferrsi-plugin"): + ext.run_mode(task, "agent", tmp_path / "b", executor="docker", agent_command="true", + inferrsi_plugin=Path("p")) + + +def test_stage_inferrsi_plugin_rejects_an_unbuilt_template(suite, tmp_path): + task = phibench.get_task(suite, TASK) + root = tmp_path / "root" + ext.stage_rootless(task, root, python="python3", include_tests=False, + include_solution=False) + template = Path(__file__).resolve().parents[2] / "plugins" / "inferrsi" + with pytest.raises(ValueError, match="build_codex_plugin"): + ext.stage_inferrsi_plugin(root, template) + + +def test_stage_inferrsi_plugin_places_the_plugin_and_names_it(suite, tmp_path, plugin): + task = phibench.get_task(suite, TASK) + root = tmp_path / "root" + ext.stage_rootless(task, root, python="python3", include_tests=False, + include_solution=False) + original = (root / "app/instruction.md").read_text() + record = ext.stage_inferrsi_plugin(root, plugin) + assert record.pop("original_instruction") == original + staged = root / "opt/inferrsi-plugin" + launcher = staged / "skills/inferrsi/scripts/inferrsi.py" + assert (staged / "plugin.json").is_file() and launcher.is_file() + noted = (root / "app/instruction.md").read_text() + assert noted.startswith(original) and "Use InferRSI" in noted + assert "/opt/inferrsi-plugin/skills/inferrsi/SKILL.md" in noted + assert record["content_sha256"] and record["usage"] == "plugin directory + prompt" + info = subprocess.run([sys.executable, "-X", "utf8", str(launcher), "--plugin-info"], + check=True, capture_output=True, text=True) + assert json.loads(info.stdout)["content_sha256"] == record["content_sha256"] + + +@pytest.mark.skipif(not PROOT, reason="needs proot (set INFERRSI_TEST_PROOT)") +def test_rootless_agent_with_and_without_inferrsi(suite, tmp_path, plugin): + task = phibench.get_task(suite, TASK) + options = {"executor": "rootless", "proot": PROOT, "python": "python3"} + edit = "sed -i 's/VALUE = 1/VALUE = 2/' planner.py" + control = ext.run_mode(task, "agent", tmp_path / "control", **options, + agent_command="test ! -e /opt/inferrsi-plugin && " + "! grep -q InferRSI /app/instruction.md && " + edit) + launcher = "/opt/inferrsi-plugin/skills/inferrsi/scripts/inferrsi.py" + arm = ext.run_mode(task, "agent", tmp_path / "arm", **options, inferrsi_plugin=plugin, + agent_command="test ! -e /tests && test ! -e /solution && " + f"grep -q {launcher} /app/instruction.md && " + f"python3 -X utf8 {launcher} skills enter task-performance " + "> /tmp/enter.json && " + edit) + for result in (control, arm): + assert result["status"] == "graded", result + assert result["score"]["speedup"] == 2.0 + assert result["grading_assets_exposed_to_agent"] is False + assert "inferrsi" not in control and arm["inferrsi"]["mount"] == "/opt/inferrsi-plugin" + entered = json.loads((tmp_path / "arm/agent/root/tmp/enter.json").read_text()) + assert entered["name"] == "task-performance" + restored = (tmp_path / "arm/agent/root/app/instruction.md").read_text() + assert restored == (task.package_root / "instruction.md").read_text() + assert "inferrsi" not in (tmp_path / "arm/agent/root/logs/artifacts/model.patch").read_text() + + +def test_rootless_steps_keep_the_host_gpu_selection(suite, tmp_path, monkeypatch): + # `env -i` inside proot drops the caller's CUDA_VISIBLE_DEVICES: a run reserved on + # GPU 5 then sees all cards and lands on GPU 0, next to other people's jobs. + task = phibench.get_task(suite, TASK) + calls = [] + + def fake_run(argv, log, timeout): + calls.append(argv) + return {"exit_code": 0, "timed_out": False, "seconds": 0.0, "log": str(log)} + + monkeypatch.setattr(ext, "_run", fake_run) + monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "5") + ext.run_rootless(task, "agent", tmp_path / "out", proot="proot", python="python3", + agent_command="true") + assert len(calls) == 3 + for argv in calls: + assert "CUDA_VISIBLE_DEVICES=5" in argv + monkeypatch.delenv("CUDA_VISIBLE_DEVICES") + calls.clear() + ext.run_rootless(task, "agent", tmp_path / "out2", proot="proot", python="python3", + agent_command="true") + assert not any(arg.startswith("CUDA_VISIBLE_DEVICES=") for argv in calls for arg in argv) + + +def test_parse_dockerfile_unquotes_build_args(tmp_path): + # Docker strips the quotes of `ARG X="9.0"`; keeping them hands torch an arch + # list of `"9.0"`, which it rejects, so every CUDA-extension task fails to build. + dockerfile = tmp_path / "Dockerfile" + dockerfile.write_text('FROM x\nARG ARCH="9.0"\nARG EMPTY=\nARG BARE=1.2\n' + "ENV TORCH_CUDA_ARCH_LIST=${ARCH} A=${EMPTY}x B=$BARE\n") + env = ext.parse_dockerfile(dockerfile)["env"] + assert env["TORCH_CUDA_ARCH_LIST"] == "9.0" + assert env["A"] == "x" and env["B"] == "1.2" + + +def test_controls_see_the_package_at_task_and_the_agent_does_not(suite, tmp_path, monkeypatch): + # lh packages ship oracle.patch next to task.toml, and their solve.sh looks for it + # under /task (the suite mounts the package there for reference runs). + task = phibench.get_task(suite, TASK) + calls = [] + + def fake_run(argv, log, timeout): + calls.append(argv) + return {"exit_code": 0, "timed_out": False, "seconds": 0.0, "log": str(log)} + + monkeypatch.setattr(ext, "_run", fake_run) + mount = f"{task.package_root.resolve()}:/task" + ext.run_rootless(task, "oracle", tmp_path / "oracle", proot="proot", python="python3") + assert mount in calls[0] + calls.clear() + ext.run_rootless(task, "agent", tmp_path / "agent", proot="proot", python="python3", + agent_command="true") + assert not any(mount in argv for argv in calls) + # proot shows the agent the whole host filesystem, so the suite clone (tests/ and + # solution/ at their host path) is covered with an empty directory in its step only. + cover = f"{(tmp_path / 'agent/suite-hidden').resolve()}:{task.suite_root}" + assert cover in calls[0] and not any(cover in argv for argv in calls[1:]) + + +@pytest.mark.skipif(not PROOT, reason="needs proot (set INFERRSI_TEST_PROOT)") +def test_agent_step_cannot_plant_a_score(suite, tmp_path): + # /logs/verifier is shared with the grading step: nothing the agent writes there may + # reach the score. + task = phibench.get_task(suite, TASK) + agent = ext.run_mode(task, "agent", tmp_path / "out", executor="rootless", proot=PROOT, + python="python3", + agent_command="echo '{\"hard_fail_reasons\": [\"planted\"]}' " + "> /logs/verifier/verifier_state.json && " + "sed -i 's/VALUE = 1/VALUE = 2/' planner.py") + assert agent["landing"]["exit_code"] == 0, agent + assert agent["score"]["speedup"] == 2.0 and agent["score"]["hard_fail_reasons"] == [] + + +@pytest.mark.skipif(not PROOT, reason="needs proot (set INFERRSI_TEST_PROOT)") +def test_an_agent_that_fails_or_times_out_is_still_graded(suite, tmp_path): + # The suite runner grades the tree an agent leaves, whatever its exit; dropping those + # runs would score only the agents that finished cleanly. + task = phibench.get_task(suite, TASK) + agent = ext.run_mode(task, "agent", tmp_path / "out", executor="rootless", proot=PROOT, + python="python3", + agent_command="sed -i 's/VALUE = 1/VALUE = 2/' planner.py; exit 3") + assert agent["status"] == "graded" and agent["warnings"] == ["agent_exited_nonzero"] + assert agent["landing"]["exit_code"] == 3 and agent["score"]["speedup"] == 2.0 + (task.package_root / "task.toml").write_text( + "[agent]\ntimeout_sec = 1\n[verifier]\ntimeout_sec = 60\n") + late = ext.run_mode(task, "agent", tmp_path / "late", executor="rootless", proot=PROOT, + python="python3", + agent_command="sed -i 's/VALUE = 1/VALUE = 2/' planner.py; sleep 30") + assert late["status"] == "graded" and late["warnings"] == ["agent_timed_out"] + assert late["score"]["speedup"] == 2.0 + + +def test_a_grader_cut_off_at_its_timeout_is_a_hard_fail(suite, tmp_path, monkeypatch): + task = phibench.get_task(suite, TASK) + + def fake_run(argv, log, timeout): + timed_out = log.name == "verify.log" + return {"exit_code": None if timed_out else 0, "timed_out": timed_out, + "seconds": 0.0, "log": str(log)} + + monkeypatch.setattr(ext, "_run", fake_run) + result = ext.run_mode(task, "noop", tmp_path / "out", executor="rootless", + proot=sys.executable, python="python3") + assert result["score"]["hard_fail_reasons"] == ["verifier_timed_out", "no_reward_file"] + assert result["status"] == "verifier_timeout" + + +def test_a_grader_that_exits_124_itself_timed_out(suite, tmp_path, monkeypatch): + task = phibench.get_task(suite, TASK) + seen = {} + + def fake_run(argv, log, timeout): + seen[log.name] = timeout + if log.name == "verify.log": + verifier = log.parent / "root" / "logs" / "verifier" + (verifier / "reward.json").write_text('{"reward": 0.0}') + return {"exit_code": 124 if log.name == "verify.log" else 0, "timed_out": False, + "seconds": 0.0, "log": str(log)} + + monkeypatch.setattr(ext, "_run", fake_run) + result = ext.run_mode(task, "noop", tmp_path / "out", executor="rootless", + proot=sys.executable, python="python3") + assert result["score"]["hard_fail_reasons"] == ["verifier_timed_out"] + assert result["status"] == "verifier_timeout" and result["score"]["reward"] == 0.0 + assert phibench.judge_control(task, "noop", result["score"])["verdict"] == "INCONCLUSIVE" + assert seen["landing.log"] == 1800.0 + + +def test_a_timed_out_grader_with_a_reward_exits_nonzero(suite, tmp_path, monkeypatch): + def fake_run(argv, log, timeout): + if log.name == "verify.log": + verifier = log.parent / "root" / "logs" / "verifier" + (verifier / "reward.json").write_text('{"reward": 0.0}') + return {"exit_code": 124 if log.name == "verify.log" else 0, "timed_out": False, + "seconds": 0.0, "log": str(log)} + + monkeypatch.setattr(ext, "_run", fake_run) + monkeypatch.setattr(ext.shutil, "which", lambda name: name) + status = main(["benchmarks", "external", "run", "--root", str(suite), "--task", TASK, + "--executor", "rootless", "--proot", "proot", "--python", "python3", + "--mode", "noop", "--output", str(tmp_path / "out")]) + result = json.loads((tmp_path / "out" / "noop" / "result.json").read_text()) + assert result["status"] == "verifier_timeout" and status == 1 + # The raw score is kept for audit, not silently dropped. + assert result["score"]["reward"] == 0.0 + assert result["score"]["hard_fail_reasons"] == ["verifier_timed_out"] + + +def test_a_real_zero_from_a_clean_grader_is_still_a_control_pass(suite, tmp_path, monkeypatch): + task = phibench.get_task(suite, TASK) + + def fake_run(argv, log, timeout): + if log.name == "verify.log": + verifier = log.parent / "root" / "logs" / "verifier" + (verifier / "reward.json").write_text('{"reward": 0.0}') + return {"exit_code": 0, "timed_out": False, "seconds": 0.0, "log": str(log)} + + monkeypatch.setattr(ext, "_run", fake_run) + result = ext.run_mode(task, "noop", tmp_path / "out", executor="rootless", + proot=sys.executable, python="python3") + assert result["status"] == "graded" and result["score"]["reward"] == 0.0 + assert phibench.judge_control(task, "noop", result["score"])["verdict"] == "PASS" + + +def test_a_grader_that_writes_no_reward_is_not_a_score(suite, tmp_path, monkeypatch, capsys): + task = phibench.get_task(suite, TASK) + + def fake_run(argv, log, timeout): + return {"exit_code": 0, "timed_out": False, "seconds": 0.0, "log": str(log)} + + monkeypatch.setattr(ext, "_run", fake_run) + monkeypatch.setattr(ext.shutil, "which", lambda name: name) + status = main(["benchmarks", "external", "run", "--root", str(suite), "--task", TASK, + "--executor", "rootless", "--proot", "proot", "--python", "python3", + "--mode", "noop", "--output", str(tmp_path / "out")]) + result = json.loads((tmp_path / "out" / "noop" / "result.json").read_text()) + assert result["status"] == "no_reward" and status == 1 + assert result["score"]["hard_fail_reasons"] == ["no_reward_file"] + + selfcheck = phibench.assess_controls(task, {c: result["score"] for c in phibench.CONTROLS}) + assert selfcheck["verdict"] == "INCONCLUSIVE"