From f7349b77b832751fb8836a405e92ea4586958690 Mon Sep 17 00:00:00 2001 From: dengyunyang <584797741@qq.com> Date: Wed, 25 Nov 2026 18:37:30 +0800 Subject: [PATCH 01/14] =?UTF-8?q?Run=20=CE=A6-Bench=20tasks=20and=20score?= =?UTF-8?q?=20them=20with=20the=20suite's=20grader?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add `inferrsi benchmarks external list|run|selfcheck`. Benchmark reads a Φ-Bench task package and the grader's reward.json and judges the noop, negative and oracle controls against the suite's documented expectations. Apps lands a control, a candidate patch or one agent command, captures the patch with the package's pre_artifacts.sh and runs its tests/test.sh. 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 or user namespaces and records the Dockerfile steps it did not replay. A performance oracle ties its anchor and scores 0 under the suite's v2 curve, so it is judged on its gates and measured speedup within a caller-supplied tolerance; without one it is INCONCLUSIVE. Agent-assisted-by: Claude Code / claude-opus-5-5 (author) Signed-off-by: dengyunyang <584797741@qq.com> Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 10 + docs/benchmarks/engineering-benchmarks.md | 2 + docs/benchmarks/public-benchmarks.md | 86 ++++ docs/guides/operations.md | 1 + src/inferrsi/apps/cli/__init__.py | 6 + src/inferrsi/apps/cli/arguments.py | 37 ++ .../apps/workflows/external_benchmark.py | 372 ++++++++++++++++++ src/inferrsi/benchmark/README.md | 3 + src/inferrsi/benchmark/external/__init__.py | 7 + src/inferrsi/benchmark/external/phibench.py | 209 ++++++++++ tests/benchmark/test_external_phibench.py | 279 +++++++++++++ 11 files changed, 1012 insertions(+) create mode 100644 docs/benchmarks/public-benchmarks.md create mode 100644 src/inferrsi/apps/workflows/external_benchmark.py create mode 100644 src/inferrsi/benchmark/external/__init__.py create mode 100644 src/inferrsi/benchmark/external/phibench.py create mode 100644 tests/benchmark/test_external_phibench.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 6384c20ae..dbdf5f47b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,16 @@ ## [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). + ### 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..98cc791f9 --- /dev/null +++ b/docs/benchmarks/public-benchmarks.md @@ -0,0 +1,86 @@ +# 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`. + +## 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. 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. + +## Scope of this slice + +This entry checks that a suite task, its controls and its grader work on a +host. 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)`) and calibration on our hardware +are later slices. Φ-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/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..fc4208616 100644 --- a/src/inferrsi/apps/cli/arguments.py +++ b/src/inferrsi/apps/cli/arguments.py @@ -441,6 +441,43 @@ 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)") + 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..44c99d11c --- /dev/null +++ b/src/inferrsi/apps/workflows/external_benchmark.py @@ -0,0 +1,372 @@ +"""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. +""" + +from __future__ import annotations + +import json +import re +import shlex +import shutil +import subprocess +import sys +import time +from pathlib import Path + +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"} + + +# --------------------------------------------------------------------------- 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("=") + build_args[key] = 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) -> dict: + """Recreate the task image layout under ``root``; return the replay record.""" + 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)) + _copy(package / "tests", root / "tests") + if (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 _verifier_timeout(task: phibench.PhiTask) -> float | None: + text = (task.package_root / "task.toml").read_text(encoding="utf-8") + section = re.search(r"^\[verifier\](.*?)(?=^\[|\Z)", text, re.S | re.M) + match = section and re.search(r"^timeout_sec\s*=\s*([0-9.]+)", section.group(1), re.M) + return float(match.group(1)) if match else None + + +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")) + 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 + + +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) -> dict: + root = out / "root" + record = stage_rootless(task, root, python=python, python_env=python_env) + env = dict(record.pop("env")) + 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 + stage_env = {**env, "PHI_TASK": task.task_id, "PHI_INSTRUCTION": "/app/instruction.md"} + record["landing"] = {"command": landing, **_run( + proot_argv(proot, root, landing, env=stage_env, cwd=workdir, extra_binds=binds), + out / "landing.log", None)} + 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) + 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(root / "logs" / "verifier") + record["status"] = "graded" if record["landing"]["exit_code"] == 0 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") + 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, 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") + 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) + record = {"suite": phibench.SUITE, "task": task.describe(), "mode": mode, **record} + if record.get("status") == "graded": + record["score"] = phibench.read_reward(Path(record["verifier_dir"])) + 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 []} + 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, **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_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..5c816d662 --- /dev/null +++ b/src/inferrsi/benchmark/external/phibench.py @@ -0,0 +1,209 @@ +"""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} + path = verifier_dir / "reward.json" + if path.is_file(): + try: + data = json.loads(path.read_text(encoding="utf-8")) + except ValueError: + data = None + if isinstance(data, dict): + result["reward"] = _finite(data.get("reward")) + result["source"] = "reward.json" if result["reward"] is not None else None + result["speedup"] = _finite(data.get("speedup")) + result["ref_speedup"] = _finite(data.get("ref_speedup")) + result["schema_version"] = data.get("schema_version") + result["hard_fail_reasons"] = [str(r) for r in data.get("hard_fail_reasons") or []] + 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 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..e2f6aaf24 --- /dev/null +++ b/tests/benchmark/test_external_phibench.py @@ -0,0 +1,279 @@ +"""Φ-Bench adapter: package reading, control judgment and executor assembly (CPU only).""" + +import json +import os +import shutil +import subprocess +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 + + +@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"), +]) +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") + + +@pytest.mark.parametrize(("mode", "options", "message"), [ + ("candidate", {}, "candidate-patch"), + ("oracle", {"candidate_patch": Path("x.patch")}, "candidate-patch"), + ("agent", {}, "agent-command"), + ("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_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_command="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"] == [] From 4be133411aaa3ba1513afe3f08cac181a4adbb5e Mon Sep 17 00:00:00 2001 From: dengyunyang <584797741@qq.com> Date: Wed, 25 Nov 2026 21:02:55 +0800 Subject: [PATCH 02/14] Keep a suite's grading assets out of the agent step MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Agent mode now stages tests/ and solution/ only after the agent has finished, matching the suite's mount-for-grading-only split, forwards named environment variables into that one step with --agent-env, and bounds it with the task's [agent] timeout_sec. Refs #688. Agent-assisted-by: 鲸鱼娘 / deepseek-v4.1-flash (author) Signed-off-by: dengyunyang <584797741@qq.com> --- CHANGELOG.md | 4 ++ docs/benchmarks/public-benchmarks.md | 43 ++++++++++-- src/inferrsi/apps/cli/arguments.py | 3 + .../apps/workflows/external_benchmark.py | 69 ++++++++++++++++--- tests/benchmark/test_external_phibench.py | 16 ++++- 5 files changed, 120 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dbdf5f47b..80efe6d7f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,10 @@ 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`. ### Fixed diff --git a/docs/benchmarks/public-benchmarks.md b/docs/benchmarks/public-benchmarks.md index 98cc791f9..3fea89f3e 100644 --- a/docs/benchmarks/public-benchmarks.md +++ b/docs/benchmarks/public-benchmarks.md @@ -41,6 +41,15 @@ inferrsi benchmarks external run --root phibench --task kfc/ \ 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. `--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`. + ## Executors - `docker` delegates to the suite's `scripts/run_task.py`, which builds the @@ -76,11 +85,37 @@ Without `--oracle-tolerance` a performance oracle is `INCONCLUSIVE`. Anchors wer 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. It does not yet score InferRSI against the suite. Scoring under the +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)`) and calibration on our hardware -are later slices. Φ-Bench's hidden cases are public, so its results count as a -public set only. +(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/src/inferrsi/apps/cli/arguments.py b/src/inferrsi/apps/cli/arguments.py index fc4208616..4ed636b15 100644 --- a/src/inferrsi/apps/cli/arguments.py +++ b/src/inferrsi/apps/cli/arguments.py @@ -473,6 +473,9 @@ def parser(*, parser_class=argparse.ArgumentParser) -> argparse.ArgumentParser: 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") else: action.add_argument("--oracle-tolerance", type=float, help="Allowed relative deviation of the oracle speedup from " diff --git a/src/inferrsi/apps/workflows/external_benchmark.py b/src/inferrsi/apps/workflows/external_benchmark.py index 44c99d11c..61c7fc369 100644 --- a/src/inferrsi/apps/workflows/external_benchmark.py +++ b/src/inferrsi/apps/workflows/external_benchmark.py @@ -19,11 +19,16 @@ (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``. """ from __future__ import annotations import json +import os import re import shlex import shutil @@ -134,8 +139,14 @@ def _git(repo: Path, *args: str) -> None: def stage_rootless(task: phibench.PhiTask, root: Path, *, python: str, - python_env: Path | None = None) -> dict: - """Recreate the task image layout under ``root``; return the replay record.""" + 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(): @@ -163,8 +174,9 @@ def stage_rootless(task: phibench.PhiTask, root: Path, *, python: str, shutil.rmtree(repo / ".git" / "logs", ignore_errors=True) for src, dst in plan["baseline_copies"]: _copy(_host(root, src), _host(root, dst)) - _copy(package / "tests", root / "tests") - if (package / "solution").is_dir(): + 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: @@ -215,6 +227,13 @@ def _verifier_timeout(task: phibench.PhiTask) -> float | None: return float(match.group(1)) if match else None +def _agent_timeout(task: phibench.PhiTask) -> float | None: + text = (task.package_root / "task.toml").read_text(encoding="utf-8") + section = re.search(r"^\[agent\](.*?)(?=^\[|\Z)", text, re.S | re.M) + match = section and re.search(r"^timeout_sec\s*=\s*([0-9.]+)", section.group(1), re.M) + return float(match.group(1)) if match else None + + def _landing(task, mode, candidate_patch, agent_command, root): binds = [] if mode in phibench.CONTROLS: @@ -232,9 +251,16 @@ def _landing(task, mode, candidate_patch, agent_command, root): 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) -> dict: + agent_command: str | None = None, + agent_env: dict[str, str] | None = None) -> dict: root = out / "root" - record = stage_rootless(task, root, python=python, python_env=python_env) + # 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 env = dict(record.pop("env")) workdir = record.pop("workdir") landing, binds = _landing(task, mode, candidate_patch, agent_command, root) @@ -242,14 +268,28 @@ def run_rootless(task: phibench.PhiTask, mode: str, out: Path, *, proot: str, py record.update(status="skipped", reason="task ships no reference landing for this control") return record 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", None)} + out / "landing.log", _agent_timeout(task) if agent_step else None)} + if env_file.exists(): + env_file.unlink() 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) + if agent_step: + _copy(task.package_root / "tests", root / "tests") 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") @@ -294,7 +334,8 @@ def run_docker(task: phibench.PhiTask, mode: str, out: Path, *, python: str, 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, runner_args: list[str] = ()) -> dict: + agent_command: str | None = None, agent_env: dict[str, str] | None = None, + runner_args: list[str] = ()) -> dict: if mode not in MODES: raise ValueError(f"Unknown mode: {mode}") if executor not in EXECUTORS: @@ -303,6 +344,8 @@ def run_mode(task: phibench.PhiTask, mode: str, out: Path, *, executor: str, 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") python = python or sys.executable out = Path(out) / mode if out.exists(): @@ -314,7 +357,8 @@ def run_mode(task: phibench.PhiTask, mode: str, out: Path, *, executor: str, 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) + candidate_patch=candidate_patch, agent_command=agent_command, + agent_env=agent_env) record = {"suite": phibench.SUITE, "task": task.describe(), "mode": mode, **record} if record.get("status") == "graded": record["score"] = phibench.read_reward(Path(record["verifier_dir"])) @@ -359,12 +403,17 @@ def command(args) -> tuple[dict | list, int]: 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, **options) + agent_command=args.agent_command, agent_env=agent_env, **options) return result, 0 if result.get("status") == "graded" else 1 diff --git a/tests/benchmark/test_external_phibench.py b/tests/benchmark/test_external_phibench.py index e2f6aaf24..31798b87a 100644 --- a/tests/benchmark/test_external_phibench.py +++ b/tests/benchmark/test_external_phibench.py @@ -246,6 +246,7 @@ def test_docker_executor_delegates_controls_to_the_suite_runner(suite, tmp_path) ("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): @@ -254,6 +255,14 @@ def test_run_mode_validates_inputs(suite, tmp_path, mode, options, 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) is None + (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_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] @@ -274,6 +283,11 @@ def test_rootless_selfcheck_and_candidate_end_to_end(suite, tmp_path): 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_command="test -f $PHI_INSTRUCTION && " + 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() From e68792fcf55fa5e3237ab77205dd6c6b1ecc5c62 Mon Sep 17 00:00:00 2001 From: dengyunyang <584797741@qq.com> Date: Thu, 26 Nov 2026 00:58:03 +0800 Subject: [PATCH 03/14] =?UTF-8?q?Stage=20InferRSI=20knowledge=20for=20a=20?= =?UTF-8?q?=CE=A6-Bench=20agent=20run=20with=20--with-inferrsi?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add an opt-in agent-mode switch to the rootless Φ-Bench executor. Before the agent step, InferRSI collect ranks its packaged knowledge cards, skills and cases against the task statement, each ranked item is written whole under /app/inferrsi with an INDEX.md, and a note is appended to the instruction; the original instruction is restored before grading. Without the switch the run is unchanged, so it serves as the plain-agent control. Agent-assisted-by: Claude Code / claude-opus-5-5 (author) Signed-off-by: dengyunyang <584797741@qq.com> Co-Authored-By: Claude Opus 5.5 --- docs/benchmarks/public-benchmarks.md | 12 ++ src/inferrsi/apps/cli/arguments.py | 4 + .../apps/workflows/external_benchmark.py | 104 +++++++++++++++++- tests/benchmark/test_external_phibench.py | 54 +++++++++ 4 files changed, 169 insertions(+), 5 deletions(-) diff --git a/docs/benchmarks/public-benchmarks.md b/docs/benchmarks/public-benchmarks.md index 3fea89f3e..a94de8d1d 100644 --- a/docs/benchmarks/public-benchmarks.md +++ b/docs/benchmarks/public-benchmarks.md @@ -50,6 +50,18 @@ 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`. +`--with-inferrsi` (agent mode, rootless executor) makes the same run an InferRSI +arm: before the agent step, InferRSI's `collect` ranks its packaged knowledge +cards, skills and cases against the task's `instruction.md` (`cuda` backend for +GPU tasks), writes each ranked item whole under `/app/inferrsi/` with an +`INDEX.md`, and appends a short note pointing there to `/app/instruction.md`. +After the agent step the original instruction is restored; `tests/` and +`solution/` stay out of the agent's step as before. `result.json` records the +delivered items under `inferrsi_knowledge` (ref, exact revision, bytes, files). +Without the flag the run is unchanged, so a run without it is the plain-agent +control for one with it: keep the task, model, effort, timeout and run count +identical between the two. + ## Executors - `docker` delegates to the suite's `scripts/run_task.py`, which builds the diff --git a/src/inferrsi/apps/cli/arguments.py b/src/inferrsi/apps/cli/arguments.py index 4ed636b15..29f010507 100644 --- a/src/inferrsi/apps/cli/arguments.py +++ b/src/inferrsi/apps/cli/arguments.py @@ -476,6 +476,10 @@ def parser(*, parser_class=argparse.ArgumentParser) -> argparse.ArgumentParser: 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("--with-inferrsi", action="store_true", + help="Mode agent, rootless: stage InferRSI knowledge retrieved " + "for the task statement under /app/inferrsi and note it in " + "/app/instruction.md for the agent step") else: action.add_argument("--oracle-tolerance", type=float, help="Allowed relative deviation of the oracle speedup from " diff --git a/src/inferrsi/apps/workflows/external_benchmark.py b/src/inferrsi/apps/workflows/external_benchmark.py index 61c7fc369..f07b155a2 100644 --- a/src/inferrsi/apps/workflows/external_benchmark.py +++ b/src/inferrsi/apps/workflows/external_benchmark.py @@ -23,6 +23,8 @@ 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``. +``with_inferrsi`` additionally stages InferRSI's retrieved knowledge for that step +(rootless only), so one run differs from its control only by that knowledge. """ from __future__ import annotations @@ -249,10 +251,91 @@ def _landing(task, mode, candidate_patch, agent_command, root): return agent_command, binds +_KNOWLEDGE_DIR = "inferrsi" +_KNOWLEDGE_NOTE = """ + +## InferRSI knowledge + +InferRSI retrieved {count} knowledge cards, skills and cases for this task statement +and placed them under `/app/{directory}/`. Start with `/app/{directory}/INDEX.md`, which +lists each item and its files. They are general optimization experience retrieved by text +match, not task answers: read what applies and ignore the rest. +""" + + +def _safe_name(identity: str) -> str: + return re.sub(r"[^A-Za-z0-9_.-]+", "_", identity).strip("._") or "item" + + +def stage_inferrsi_knowledge(task: phibench.PhiTask, root: Path) -> dict: + """Retrieve InferRSI knowledge for the task statement and stage it in the agent's tree. + + Ranking is InferRSI's own ``collect`` over the full instruction text. Each ranked item + is written whole under ``/app/inferrsi`` (the agent reads on demand), and a short + note appended to ``/app/instruction.md`` tells the agent where it is. Returns the + record of what was delivered; the original instruction is returned for restoring. + """ + # Lazy import: the reader loads the packaged corpus, which other modes never need. + from inferrsi.apps.workflows.benchmark_compare import KNOWLEDGE_CONTEXT_BYTES + from inferrsi.knowledge.knowledge_operations import KnowledgeReader + + instruction_path = root / "app" / "instruction.md" + instruction = instruction_path.read_text(encoding="utf-8") + backend = "cuda" if task.gpus else None + reader = KnowledgeReader() + ranked = reader.collect(instruction, backend=backend, context_bytes=KNOWLEDGE_CONTEXT_BYTES) + revisions = {item["ref"]: item["revision"] for item in ranked["retrieval"]["items"]} + contexts = {context["ref"]: context for context in ranked["contexts"]} + for omission in ranked["context_omissions"]: + # Over the shared context budget: read that one item whole at its exact revision, + # sized by the bytes collect reported it needs. + ref = omission["ref"] + single = reader.collect(ids=[ref], revisions={ref: revisions[ref]}, + context_bytes=omission["required_bytes"]) + contexts.update({context["ref"]: context for context in single["contexts"]}) + target = root / "app" / _KNOWLEDGE_DIR + target.mkdir(parents=True, exist_ok=False) + items, index = [], ["# InferRSI knowledge for this task", "", + "Ranked by InferRSI `collect` (Find lexical ranking) over the task " + "statement. Each directory holds one item's files.", ""] + for rank, entry in enumerate(ranked["retrieval"]["items"], start=1): + ref = entry["ref"] + context = contexts.get(ref) + if context is None: + items.append({"rank": rank, "ref": ref, "revision": entry["revision"], + "delivered": False}) + continue + directory = target / f"{rank:02d}-{_safe_name(ref.split(':', 1)[-1])}" + files = [] + for resource in context["resources"]: + path = (directory / resource["path"]).resolve() + if directory.resolve() not in path.parents: + raise ValueError(f"Knowledge resource escapes its directory: {resource['path']}") + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(resource["content"], encoding="utf-8") + files.append(resource["path"]) + items.append({"rank": rank, "ref": ref, "revision": entry["revision"], + "delivered": True, "bytes": context["content_bytes"], + "directory": f"/app/{_KNOWLEDGE_DIR}/{directory.name}", "files": files}) + index.append(f"{rank}. `{ref}` ({context['content_bytes']} bytes) -> " + f"`{directory.name}/`: " + ", ".join(f"`{name}`" for name in files)) + (target / "INDEX.md").write_text("\n".join(index) + "\n", encoding="utf-8") + delivered = [item for item in items if item["delivered"]] + instruction_path.write_text(instruction + _KNOWLEDGE_NOTE.format( + count=len(delivered), directory=_KNOWLEDGE_DIR), encoding="utf-8") + return {"query": "task instruction.md", "backend": backend, + "ranking": ranked["selection"]["method"], + "implementation": ranked["retrieval"]["implementation"], + "directory": f"/app/{_KNOWLEDGE_DIR}", "items": items, + "delivered_bytes": sum(item["bytes"] for item in delivered), + "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) -> dict: + agent_env: dict[str, str] | None = None, + with_inferrsi: bool = False) -> 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 @@ -261,6 +344,11 @@ def run_rootless(task: phibench.PhiTask, mode: str, out: Path, *, proot: str, py 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 with_inferrsi: + knowledge = stage_inferrsi_knowledge(task, root) + original_instruction = knowledge.pop("original_instruction") + record["inferrsi_knowledge"] = knowledge env = dict(record.pop("env")) workdir = record.pop("workdir") landing, binds = _landing(task, mode, candidate_patch, agent_command, root) @@ -283,6 +371,9 @@ def run_rootless(task: phibench.PhiTask, mode: str, out: Path, *, proot: str, py out / "landing.log", _agent_timeout(task) if agent_step 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 knowledge 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, @@ -335,7 +426,7 @@ 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, - runner_args: list[str] = ()) -> dict: + with_inferrsi: bool = False, runner_args: list[str] = ()) -> dict: if mode not in MODES: raise ValueError(f"Unknown mode: {mode}") if executor not in EXECUTORS: @@ -346,6 +437,8 @@ def run_mode(task: phibench.PhiTask, mode: str, out: Path, *, executor: str, 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 with_inferrsi and (mode != "agent" or executor != "rootless"): + raise ValueError("--with-inferrsi is only for mode agent with the rootless executor") python = python or sys.executable out = Path(out) / mode if out.exists(): @@ -358,7 +451,7 @@ def run_mode(task: phibench.PhiTask, mode: str, out: Path, *, executor: str, 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) + agent_env=agent_env, with_inferrsi=with_inferrsi) record = {"suite": phibench.SUITE, "task": task.describe(), "mode": mode, **record} if record.get("status") == "graded": record["score"] = phibench.read_reward(Path(record["verifier_dir"])) @@ -413,9 +506,10 @@ def command(args) -> tuple[dict | list, int]: **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, **options) + agent_command=args.agent_command, agent_env=agent_env, + with_inferrsi=getattr(args, "with_inferrsi", False), **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_rootless"] + "proot_argv", "run_mode", "selfcheck", "stage_inferrsi_knowledge", "stage_rootless"] diff --git a/tests/benchmark/test_external_phibench.py b/tests/benchmark/test_external_phibench.py index 31798b87a..83ea43d9b 100644 --- a/tests/benchmark/test_external_phibench.py +++ b/tests/benchmark/test_external_phibench.py @@ -291,3 +291,57 @@ def test_rootless_selfcheck_and_candidate_end_to_end(suite, tmp_path): 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() + + +def test_with_inferrsi_is_only_for_rootless_agent_mode(suite, tmp_path): + task = phibench.get_task(suite, TASK) + with pytest.raises(ValueError, match="with-inferrsi"): + ext.run_mode(task, "oracle", tmp_path / "a", executor="rootless", proot="proot", + with_inferrsi=True) + with pytest.raises(ValueError, match="with-inferrsi"): + ext.run_mode(task, "agent", tmp_path / "b", executor="docker", agent_command="true", + with_inferrsi=True) + + +def test_stage_inferrsi_knowledge_writes_ranked_items_and_notes_them(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) + original = (root / "app/instruction.md").read_text() + record = ext.stage_inferrsi_knowledge(task, root) + assert record.pop("original_instruction") == original + delivered = [item for item in record["items"] if item["delivered"]] + assert delivered and record["delivered_bytes"] == sum(i["bytes"] for i in delivered) + index = (root / "app/inferrsi/INDEX.md").read_text() + for item in delivered: + assert item["ref"] in index + directory = root / item["directory"].lstrip("/") + assert all((directory / name).is_file() for name in item["files"]) + noted = (root / "app/instruction.md").read_text() + assert noted.startswith(original) and "/app/inferrsi/INDEX.md" in noted + assert record["backend"] is None # the fake task declares no GPU + assert not (root / "tests").exists() and not (root / "solution").exists() + + +@pytest.mark.skipif(not PROOT, reason="needs proot (set INFERRSI_TEST_PROOT)") +def test_rootless_agent_with_and_without_inferrsi(suite, tmp_path): + 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 /app/inferrsi && " + "! grep -q InferRSI /app/instruction.md && " + edit) + arm = ext.run_mode(task, "agent", tmp_path / "arm", **options, with_inferrsi=True, + agent_command="test ! -e /tests && test ! -e /solution && " + "test -f /app/inferrsi/INDEX.md && " + "grep -q /app/inferrsi/INDEX.md /app/instruction.md && " + + 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_knowledge" not in control and arm["inferrsi_knowledge"]["items"] + 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() From 8072fab063c1a7b007d658afd48e1352db833d1f Mon Sep 17 00:00:00 2001 From: dengyunyang <584797741@qq.com> Date: Thu, 26 Nov 2026 01:43:07 +0800 Subject: [PATCH 04/14] =?UTF-8?q?Run=20the=20=CE=A6-Bench=20InferRSI=20arm?= =?UTF-8?q?=20through=20the=20Codex=20plugin?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replace --with-inferrsi (adapter-side collect into /app/inferrsi) with --inferrsi-plugin DIR: the built InferRSI Codex plugin is placed at /opt/inferrsi-plugin and the instruction gains a note to use InferRSI through its SKILL.md and launcher, the plugin's standard directory-plus-prompt use. The agent chooses skills and searches knowledge itself. Agent-assisted-by: Claude Code / claude-opus-5-5 (author) Signed-off-by: dengyunyang <584797741@qq.com> Co-Authored-By: Claude Opus 5.5 --- docs/benchmarks/public-benchmarks.md | 25 ++-- src/inferrsi/apps/cli/arguments.py | 8 +- .../apps/workflows/external_benchmark.py | 128 +++++++----------- tests/benchmark/test_external_phibench.py | 72 ++++++---- 4 files changed, 112 insertions(+), 121 deletions(-) diff --git a/docs/benchmarks/public-benchmarks.md b/docs/benchmarks/public-benchmarks.md index a94de8d1d..594661613 100644 --- a/docs/benchmarks/public-benchmarks.md +++ b/docs/benchmarks/public-benchmarks.md @@ -50,17 +50,20 @@ 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`. -`--with-inferrsi` (agent mode, rootless executor) makes the same run an InferRSI -arm: before the agent step, InferRSI's `collect` ranks its packaged knowledge -cards, skills and cases against the task's `instruction.md` (`cuda` backend for -GPU tasks), writes each ranked item whole under `/app/inferrsi/` with an -`INDEX.md`, and appends a short note pointing there to `/app/instruction.md`. -After the agent step the original instruction is restored; `tests/` and -`solution/` stay out of the agent's step as before. `result.json` records the -delivered items under `inferrsi_knowledge` (ref, exact revision, bytes, files). -Without the flag the run is unchanged, so a run without it is the plain-agent -control for one with it: keep the task, model, effort, timeout and run count -identical between the two. +`--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 diff --git a/src/inferrsi/apps/cli/arguments.py b/src/inferrsi/apps/cli/arguments.py index 29f010507..63124a6e8 100644 --- a/src/inferrsi/apps/cli/arguments.py +++ b/src/inferrsi/apps/cli/arguments.py @@ -476,10 +476,10 @@ def parser(*, parser_class=argparse.ArgumentParser) -> argparse.ArgumentParser: 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("--with-inferrsi", action="store_true", - help="Mode agent, rootless: stage InferRSI knowledge retrieved " - "for the task statement under /app/inferrsi and note it in " - "/app/instruction.md for the agent step") + 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 " diff --git a/src/inferrsi/apps/workflows/external_benchmark.py b/src/inferrsi/apps/workflows/external_benchmark.py index f07b155a2..71a9b34a0 100644 --- a/src/inferrsi/apps/workflows/external_benchmark.py +++ b/src/inferrsi/apps/workflows/external_benchmark.py @@ -23,8 +23,9 @@ 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``. -``with_inferrsi`` additionally stages InferRSI's retrieved knowledge for that step -(rootless only), so one run differs from its control only by that knowledge. +``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 @@ -251,83 +252,46 @@ def _landing(task, mode, candidate_patch, agent_command, root): return agent_command, binds -_KNOWLEDGE_DIR = "inferrsi" -_KNOWLEDGE_NOTE = """ +_PLUGIN_MOUNT = "/opt/inferrsi-plugin" +_PLUGIN_NOTE = """ -## InferRSI knowledge +## InferRSI -InferRSI retrieved {count} knowledge cards, skills and cases for this task statement -and placed them under `/app/{directory}/`. Start with `/app/{directory}/INDEX.md`, which -lists each item and its files. They are general optimization experience retrieved by text -match, not task answers: read what applies and ignore the rest. +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 _safe_name(identity: str) -> str: - return re.sub(r"[^A-Za-z0-9_.-]+", "_", identity).strip("._") or "item" +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. - -def stage_inferrsi_knowledge(task: phibench.PhiTask, root: Path) -> dict: - """Retrieve InferRSI knowledge for the task statement and stage it in the agent's tree. - - Ranking is InferRSI's own ``collect`` over the full instruction text. Each ranked item - is written whole under ``/app/inferrsi`` (the agent reads on demand), and a short - note appended to ``/app/instruction.md`` tells the agent where it is. Returns the - record of what was delivered; the original instruction is returned for restoring. + 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. """ - # Lazy import: the reader loads the packaged corpus, which other modes never need. - from inferrsi.apps.workflows.benchmark_compare import KNOWLEDGE_CONTEXT_BYTES - from inferrsi.knowledge.knowledge_operations import KnowledgeReader - + 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") - backend = "cuda" if task.gpus else None - reader = KnowledgeReader() - ranked = reader.collect(instruction, backend=backend, context_bytes=KNOWLEDGE_CONTEXT_BYTES) - revisions = {item["ref"]: item["revision"] for item in ranked["retrieval"]["items"]} - contexts = {context["ref"]: context for context in ranked["contexts"]} - for omission in ranked["context_omissions"]: - # Over the shared context budget: read that one item whole at its exact revision, - # sized by the bytes collect reported it needs. - ref = omission["ref"] - single = reader.collect(ids=[ref], revisions={ref: revisions[ref]}, - context_bytes=omission["required_bytes"]) - contexts.update({context["ref"]: context for context in single["contexts"]}) - target = root / "app" / _KNOWLEDGE_DIR - target.mkdir(parents=True, exist_ok=False) - items, index = [], ["# InferRSI knowledge for this task", "", - "Ranked by InferRSI `collect` (Find lexical ranking) over the task " - "statement. Each directory holds one item's files.", ""] - for rank, entry in enumerate(ranked["retrieval"]["items"], start=1): - ref = entry["ref"] - context = contexts.get(ref) - if context is None: - items.append({"rank": rank, "ref": ref, "revision": entry["revision"], - "delivered": False}) - continue - directory = target / f"{rank:02d}-{_safe_name(ref.split(':', 1)[-1])}" - files = [] - for resource in context["resources"]: - path = (directory / resource["path"]).resolve() - if directory.resolve() not in path.parents: - raise ValueError(f"Knowledge resource escapes its directory: {resource['path']}") - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(resource["content"], encoding="utf-8") - files.append(resource["path"]) - items.append({"rank": rank, "ref": ref, "revision": entry["revision"], - "delivered": True, "bytes": context["content_bytes"], - "directory": f"/app/{_KNOWLEDGE_DIR}/{directory.name}", "files": files}) - index.append(f"{rank}. `{ref}` ({context['content_bytes']} bytes) -> " - f"`{directory.name}/`: " + ", ".join(f"`{name}`" for name in files)) - (target / "INDEX.md").write_text("\n".join(index) + "\n", encoding="utf-8") - delivered = [item for item in items if item["delivered"]] - instruction_path.write_text(instruction + _KNOWLEDGE_NOTE.format( - count=len(delivered), directory=_KNOWLEDGE_DIR), encoding="utf-8") - return {"query": "task instruction.md", "backend": backend, - "ranking": ranked["selection"]["method"], - "implementation": ranked["retrieval"]["implementation"], - "directory": f"/app/{_KNOWLEDGE_DIR}", "items": items, - "delivered_bytes": sum(item["bytes"] for item in delivered), + 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} @@ -335,7 +299,7 @@ def run_rootless(task: phibench.PhiTask, mode: str, out: Path, *, proot: str, py python_env: Path | None = None, candidate_patch: Path | None = None, agent_command: str | None = None, agent_env: dict[str, str] | None = None, - with_inferrsi: bool = False) -> dict: + 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 @@ -345,10 +309,10 @@ def run_rootless(task: phibench.PhiTask, mode: str, out: Path, *, proot: str, py include_tests=not agent_step, include_solution=not agent_step) record["grading_assets_exposed_to_agent"] = not agent_step original_instruction = None - if with_inferrsi: - knowledge = stage_inferrsi_knowledge(task, root) - original_instruction = knowledge.pop("original_instruction") - record["inferrsi_knowledge"] = knowledge + 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")) workdir = record.pop("workdir") landing, binds = _landing(task, mode, candidate_patch, agent_command, root) @@ -372,7 +336,7 @@ def run_rootless(task: phibench.PhiTask, mode: str, out: Path, *, proot: str, py if env_file.exists(): env_file.unlink() if original_instruction is not None: - # Hand the grader the task's own statement, as without the knowledge note. + # 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( @@ -426,7 +390,7 @@ 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, - with_inferrsi: bool = False, runner_args: list[str] = ()) -> dict: + 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: @@ -437,8 +401,8 @@ def run_mode(task: phibench.PhiTask, mode: str, out: Path, *, executor: str, 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 with_inferrsi and (mode != "agent" or executor != "rootless"): - raise ValueError("--with-inferrsi is only for mode agent with the rootless executor") + 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(): @@ -451,7 +415,7 @@ def run_mode(task: phibench.PhiTask, mode: str, out: Path, *, executor: str, 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, with_inferrsi=with_inferrsi) + 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"])) @@ -507,9 +471,9 @@ def command(args) -> tuple[dict | list, int]: 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, - with_inferrsi=getattr(args, "with_inferrsi", False), **options) + 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_knowledge", "stage_rootless"] + "proot_argv", "run_mode", "selfcheck", "stage_inferrsi_plugin", "stage_rootless"] diff --git a/tests/benchmark/test_external_phibench.py b/tests/benchmark/test_external_phibench.py index 83ea43d9b..a3a37a0a3 100644 --- a/tests/benchmark/test_external_phibench.py +++ b/tests/benchmark/test_external_phibench.py @@ -4,6 +4,7 @@ import os import shutil import subprocess +import sys from pathlib import Path import pytest @@ -293,55 +294,78 @@ def test_rootless_selfcheck_and_candidate_end_to_end(suite, tmp_path): assert (tmp_path / "agent/agent/root/tests/test.sh").is_file() -def test_with_inferrsi_is_only_for_rootless_agent_mode(suite, tmp_path): + +@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="with-inferrsi"): + with pytest.raises(ValueError, match="inferrsi-plugin"): ext.run_mode(task, "oracle", tmp_path / "a", executor="rootless", proot="proot", - with_inferrsi=True) - with pytest.raises(ValueError, match="with-inferrsi"): + inferrsi_plugin=Path("p")) + with pytest.raises(ValueError, match="inferrsi-plugin"): ext.run_mode(task, "agent", tmp_path / "b", executor="docker", agent_command="true", - with_inferrsi=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_knowledge_writes_ranked_items_and_notes_them(suite, tmp_path): +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_knowledge(task, root) + record = ext.stage_inferrsi_plugin(root, plugin) assert record.pop("original_instruction") == original - delivered = [item for item in record["items"] if item["delivered"]] - assert delivered and record["delivered_bytes"] == sum(i["bytes"] for i in delivered) - index = (root / "app/inferrsi/INDEX.md").read_text() - for item in delivered: - assert item["ref"] in index - directory = root / item["directory"].lstrip("/") - assert all((directory / name).is_file() for name in item["files"]) + 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 "/app/inferrsi/INDEX.md" in noted - assert record["backend"] is None # the fake task declares no GPU - assert not (root / "tests").exists() and not (root / "solution").exists() + 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): +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 /app/inferrsi && " + agent_command="test ! -e /opt/inferrsi-plugin && " "! grep -q InferRSI /app/instruction.md && " + edit) - arm = ext.run_mode(task, "agent", tmp_path / "arm", **options, with_inferrsi=True, + 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 && " - "test -f /app/inferrsi/INDEX.md && " - "grep -q /app/inferrsi/INDEX.md /app/instruction.md && " - + edit) + 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_knowledge" not in control and arm["inferrsi_knowledge"]["items"] + 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() From 7f5587b370e8346b94e6fdde8d775f46fcc5fa4e Mon Sep 17 00:00:00 2001 From: dengyunyang <584797741@qq.com> Date: Thu, 26 Nov 2026 02:49:02 +0800 Subject: [PATCH 05/14] =?UTF-8?q?Keep=20the=20host=20GPU=20selection=20ins?= =?UTF-8?q?ide=20rootless=20=CE=A6-Bench=20steps?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit proot runs each step under env -i, so CUDA_VISIBLE_DEVICES from a GPU reservation was dropped and every task ran on GPU 0. Agent-assisted-by: Claude Code / claude-opus-5-5 (author) Signed-off-by: dengyunyang <584797741@qq.com> Co-Authored-By: Claude Opus 5.5 --- .../apps/workflows/external_benchmark.py | 6 +++++ tests/benchmark/test_external_phibench.py | 24 +++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/src/inferrsi/apps/workflows/external_benchmark.py b/src/inferrsi/apps/workflows/external_benchmark.py index 71a9b34a0..2f968589f 100644 --- a/src/inferrsi/apps/workflows/external_benchmark.py +++ b/src/inferrsi/apps/workflows/external_benchmark.py @@ -314,6 +314,12 @@ def run_rootless(task: phibench.PhiTask, mode: str, out: Path, *, proot: str, py 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: diff --git a/tests/benchmark/test_external_phibench.py b/tests/benchmark/test_external_phibench.py index a3a37a0a3..76160afeb 100644 --- a/tests/benchmark/test_external_phibench.py +++ b/tests/benchmark/test_external_phibench.py @@ -369,3 +369,27 @@ def test_rootless_agent_with_and_without_inferrsi(suite, tmp_path, plugin): 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) From 5f7fd4a196e3c5cabdb6e82146164dbf86b3aede Mon Sep 17 00:00:00 2001 From: dengyunyang <584797741@qq.com> Date: Thu, 26 Nov 2026 02:55:25 +0800 Subject: [PATCH 06/14] Unquote Dockerfile build-arg defaults like Docker does ARG TORCH_CUDA_ARCH_LIST="9.0" reached the task as a quoted value, which torch rejects, so CUDA-extension tasks could not build. Agent-assisted-by: Claude Code / claude-opus-5-5 (author) Signed-off-by: dengyunyang <584797741@qq.com> Co-Authored-By: Claude Opus 5.5 --- src/inferrsi/apps/workflows/external_benchmark.py | 3 ++- tests/benchmark/test_external_phibench.py | 11 +++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/src/inferrsi/apps/workflows/external_benchmark.py b/src/inferrsi/apps/workflows/external_benchmark.py index 2f968589f..bcf69ead0 100644 --- a/src/inferrsi/apps/workflows/external_benchmark.py +++ b/src/inferrsi/apps/workflows/external_benchmark.py @@ -92,7 +92,8 @@ def parse_dockerfile(path: Path) -> dict: word = word.upper() if word == "ARG": key, _, value = rest.strip().partition("=") - build_args[key] = value + # 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] diff --git a/tests/benchmark/test_external_phibench.py b/tests/benchmark/test_external_phibench.py index 76160afeb..d51c63e27 100644 --- a/tests/benchmark/test_external_phibench.py +++ b/tests/benchmark/test_external_phibench.py @@ -393,3 +393,14 @@ def fake_run(argv, log, timeout): 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" From 3995c637267eededc2aa73f181282c1fc77a25c9 Mon Sep 17 00:00:00 2001 From: dengyunyang <584797741@qq.com> Date: Thu, 26 Nov 2026 06:49:11 +0800 Subject: [PATCH 07/14] =?UTF-8?q?Mount=20the=20task=20package=20at=20/task?= =?UTF-8?q?=20for=20=CE=A6-Bench=20reference=20runs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit lh packages keep oracle.patch next to task.toml and their solve.sh looks for it under /task, so every lh reference run failed to land. Agent-assisted-by: Claude Code / claude-opus-5-5 (author) Signed-off-by: dengyunyang <584797741@qq.com> Co-Authored-By: Claude Opus 5.5 --- .../apps/workflows/external_benchmark.py | 3 +++ tests/benchmark/test_external_phibench.py | 20 +++++++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/src/inferrsi/apps/workflows/external_benchmark.py b/src/inferrsi/apps/workflows/external_benchmark.py index bcf69ead0..dee3fce76 100644 --- a/src/inferrsi/apps/workflows/external_benchmark.py +++ b/src/inferrsi/apps/workflows/external_benchmark.py @@ -244,6 +244,9 @@ def _landing(task, mode, candidate_patch, agent_command, root): 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() diff --git a/tests/benchmark/test_external_phibench.py b/tests/benchmark/test_external_phibench.py index d51c63e27..0d9bba4a6 100644 --- a/tests/benchmark/test_external_phibench.py +++ b/tests/benchmark/test_external_phibench.py @@ -404,3 +404,23 @@ def test_parse_dockerfile_unquotes_build_args(tmp_path): 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) From 0c54aaba95274bf664a593d86d4f12d2144d56e2 Mon Sep 17 00:00:00 2001 From: dengyunyang <584797741@qq.com> Date: Thu, 26 Nov 2026 08:17:52 +0800 Subject: [PATCH 08/14] =?UTF-8?q?Grade=20every=20=CE=A6-Bench=20agent=20ru?= =?UTF-8?q?n=20from=20a=20clean=20slate,=20as=20the=20suite=20runner=20doe?= =?UTF-8?q?s?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An agent that exited non-zero or hit its timeout was recorded as landing_failed and never scored, while the suite runner grades the tree it left. The rootless agent step could also read the suite clone at its host path (proot shares the host filesystem) and leave files under /logs/verifier for the grader. Cover the clone with an empty directory in the agent step, re-stage tests/ and clear /logs/verifier before grading, and mark a grader cut off at its timeout verifier_timed_out. Agent-assisted-by: Claude Code / claude-opus-5-5 (author) Signed-off-by: dengyunyang <584797741@qq.com> Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 5 +- docs/benchmarks/public-benchmarks.md | 14 +++-- .../apps/workflows/external_benchmark.py | 24 ++++++++- tests/benchmark/test_external_phibench.py | 51 +++++++++++++++++++ 4 files changed, 88 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 80efe6d7f..7432448fd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,7 +14,10 @@ - `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`. + 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`; the rootless agent step cannot see the suite clone and + cannot leave files for the grading step under `/tests` or `/logs/verifier`. ### Fixed diff --git a/docs/benchmarks/public-benchmarks.md b/docs/benchmarks/public-benchmarks.md index 594661613..1ceeae7f8 100644 --- a/docs/benchmarks/public-benchmarks.md +++ b/docs/benchmarks/public-benchmarks.md @@ -43,7 +43,14 @@ 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. `--agent-env NAME` forwards an +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`. `--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 @@ -76,8 +83,9 @@ identical between the two arms. `/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. Provide a Python environment with the task's dependencies - through `--python-env`; otherwise it creates an empty venv, which is enough + 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. diff --git a/src/inferrsi/apps/workflows/external_benchmark.py b/src/inferrsi/apps/workflows/external_benchmark.py index dee3fce76..477259b1e 100644 --- a/src/inferrsi/apps/workflows/external_benchmark.py +++ b/src/inferrsi/apps/workflows/external_benchmark.py @@ -329,6 +329,12 @@ def run_rootless(task: phibench.PhiTask, mode: str, out: Path, *, proot: str, py 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 @@ -353,13 +359,24 @@ def run_rootless(task: phibench.PhiTask, mode: str, out: Path, *, proot: str, py 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(root / "logs" / "verifier") - record["status"] = "graded" if record["landing"]["exit_code"] == 0 else "landing_failed" + 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 @@ -429,6 +446,9 @@ def run_mode(task: phibench.PhiTask, mode: str, out: Path, *, executor: str, record = {"suite": phibench.SUITE, "task": task.describe(), "mode": mode, **record} if record.get("status") == "graded": record["score"] = phibench.read_reward(Path(record["verifier_dir"])) + if record["grade"].get("timed_out"): + # As the suite runner does: a grader cut off at its timeout is a hard fail. + record["score"]["hard_fail_reasons"].append("verifier_timed_out") 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), diff --git a/tests/benchmark/test_external_phibench.py b/tests/benchmark/test_external_phibench.py index 0d9bba4a6..f96d7e849 100644 --- a/tests/benchmark/test_external_phibench.py +++ b/tests/benchmark/test_external_phibench.py @@ -424,3 +424,54 @@ def fake_run(argv, log, timeout): 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"] From d2a985e98eec0f3c3ff73bf951aa5ac575641363 Mon Sep 17 00:00:00 2001 From: dengyunyang <584797741@qq.com> Date: Thu, 26 Nov 2026 19:29:34 +0800 Subject: [PATCH 09/14] =?UTF-8?q?Judge=20=CE=A6-Bench=20runs=20the=20way?= =?UTF-8?q?=20the=20suite=20runner=20does=20when=20the=20grader=20falls=20?= =?UTF-8?q?short?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A rootless step now falls back to the runner's limits when task.toml sets none (55 of the 85 packages set no [verifier] timeout_sec), so a hung grader is cut off at 3600 s instead of running forever. A run whose grader leaves no readable reward gets the hard fail no_reward_file, status no_reward and a non-zero exit instead of "graded". A control whose grader timed out is INCONCLUSIVE rather than a PASS on its 0. Rewards are also read from metrics.json, as the runner does, so hard fails written only there count. Refs #688. Agent-assisted-by: Claude Code / claude-opus-5-5 (author) Signed-off-by: dengyunyang <584797741@qq.com> Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 +- docs/benchmarks/public-benchmarks.md | 2 +- .../apps/workflows/external_benchmark.py | 31 ++++++++---- src/inferrsi/benchmark/external/phibench.py | 30 ++++++++---- tests/benchmark/test_external_phibench.py | 47 ++++++++++++++++++- 5 files changed, 93 insertions(+), 21 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7432448fd..32d34e9c3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,7 +16,9 @@ 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`; the rootless agent step cannot see the suite clone and + `verifier_timed_out` (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; the rootless agent step cannot see the suite clone and cannot leave files for the grading step under `/tests` or `/logs/verifier`. ### Fixed diff --git a/docs/benchmarks/public-benchmarks.md b/docs/benchmarks/public-benchmarks.md index 1ceeae7f8..eaab39555 100644 --- a/docs/benchmarks/public-benchmarks.md +++ b/docs/benchmarks/public-benchmarks.md @@ -50,7 +50,7 @@ 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`. `--agent-env NAME` forwards an +at its own timeout adds the hard fail `verifier_timed_out`, 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. Without a `timeout_sec` in `task.toml` the steps use the suite runner's defaults (agent 5400 s, grader 3600 s). `--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 diff --git a/src/inferrsi/apps/workflows/external_benchmark.py b/src/inferrsi/apps/workflows/external_benchmark.py index 477259b1e..5a7f458d7 100644 --- a/src/inferrsi/apps/workflows/external_benchmark.py +++ b/src/inferrsi/apps/workflows/external_benchmark.py @@ -224,18 +224,27 @@ def _run(argv: list[str], log: Path, timeout: float | None) -> dict: "seconds": round(time.monotonic() - started, 1), "log": str(log)} -def _verifier_timeout(task: phibench.PhiTask) -> float | None: +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.""" text = (task.package_root / "task.toml").read_text(encoding="utf-8") - section = re.search(r"^\[verifier\](.*?)(?=^\[|\Z)", text, re.S | re.M) - match = section and re.search(r"^timeout_sec\s*=\s*([0-9.]+)", section.group(1), re.M) - return float(match.group(1)) if match else None + body = re.search(rf"^\[{section}\](.*?)(?=^\[|\Z)", text, re.S | re.M) + match = body and re.search(r"^timeout_sec\s*=\s*([0-9.]+)", body.group(1), re.M) + if not match: + head = re.split(r"^\[", text, maxsplit=1, flags=re.M)[0] + match = re.search(rf"^{top_key}\s*=\s*([0-9.]+)", head, re.M) + return float(match.group(1)) if match else default -def _agent_timeout(task: phibench.PhiTask) -> float | None: - text = (task.package_root / "task.toml").read_text(encoding="utf-8") - section = re.search(r"^\[agent\](.*?)(?=^\[|\Z)", text, re.S | re.M) - match = section and re.search(r"^timeout_sec\s*=\s*([0-9.]+)", section.group(1), re.M) - return float(match.group(1)) if match else None +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): @@ -449,6 +458,10 @@ def run_mode(task: phibench.PhiTask, mode: str, out: Path, *, executor: str, if record["grade"].get("timed_out"): # As the suite runner does: a grader cut off at its timeout is a hard fail. record["score"]["hard_fail_reasons"].append("verifier_timed_out") + if record["score"]["reward"] is None: + # As the suite runner does: no readable reward is a failed run, not a score. + record["score"]["hard_fail_reasons"].append("no_reward_file") + 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), diff --git a/src/inferrsi/benchmark/external/phibench.py b/src/inferrsi/benchmark/external/phibench.py index 5c816d662..c68ba29d9 100644 --- a/src/inferrsi/benchmark/external/phibench.py +++ b/src/inferrsi/benchmark/external/phibench.py @@ -125,19 +125,29 @@ def read_reward(verifier_dir: Path) -> dict: verifier_dir = Path(verifier_dir) result = {"reward": None, "speedup": None, "ref_speedup": None, "hard_fail_reasons": [], "schema_version": None, "source": None} - path = verifier_dir / "reward.json" - if path.is_file(): + # 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: - data = None - if isinstance(data, dict): + continue + if not isinstance(data, dict): + continue + if result["reward"] is None: result["reward"] = _finite(data.get("reward")) - result["source"] = "reward.json" if result["reward"] is not None else None - result["speedup"] = _finite(data.get("speedup")) - result["ref_speedup"] = _finite(data.get("ref_speedup")) + 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") - result["hard_fail_reasons"] = [str(r) for r in data.get("hard_fail_reasons") or []] + 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) @@ -167,6 +177,10 @@ def judge_control(task: PhiTask, control: str, score: dict | 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"} diff --git a/tests/benchmark/test_external_phibench.py b/tests/benchmark/test_external_phibench.py index f96d7e849..563854a35 100644 --- a/tests/benchmark/test_external_phibench.py +++ b/tests/benchmark/test_external_phibench.py @@ -144,6 +144,15 @@ def test_read_reward_merges_state_and_falls_back_to_text(tmp_path): 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"), @@ -154,6 +163,9 @@ def test_read_reward_merges_state_and_falls_back_to_text(tmp_path): ("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) @@ -258,12 +270,23 @@ def test_run_mode_validates_inputs(suite, tmp_path, mode, options, message): def test_agent_timeout_comes_from_the_task(suite): task = phibench.get_task(suite, TASK) - assert ext._agent_timeout(task) is None + 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_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] @@ -474,4 +497,24 @@ def fake_run(argv, log, timeout): 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["score"]["hard_fail_reasons"] == ["verifier_timed_out", "no_reward_file"] + assert result["status"] == "no_reward" + + +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" From eda109ba051b42e9b96c46836eb33d96a5507af9 Mon Sep 17 00:00:00 2001 From: dengyunyang <584797741@qq.com> Date: Thu, 26 Nov 2026 19:30:35 +0800 Subject: [PATCH 10/14] =?UTF-8?q?Carry=20the=20=CE=A6-Bench=20runner's=20h?= =?UTF-8?q?ard=20fails=20into=20a=20docker=20run's=20score?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The suite runner records verifier_timed_out and its other stage failures in run.json, not in the verifier directory the adapter reads, so a docker noop or negative whose grader timed out still judged PASS on its 0. Merge the runner's reasons into the score. Refs #688. Agent-assisted-by: Claude Code / claude-opus-5-5 (author) Signed-off-by: dengyunyang <584797741@qq.com> Co-Authored-By: Claude Opus 5.5 --- .../apps/workflows/external_benchmark.py | 11 ++++++++-- tests/benchmark/test_external_phibench.py | 20 +++++++++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/src/inferrsi/apps/workflows/external_benchmark.py b/src/inferrsi/apps/workflows/external_benchmark.py index 5a7f458d7..fd7f568c7 100644 --- a/src/inferrsi/apps/workflows/external_benchmark.py +++ b/src/inferrsi/apps/workflows/external_benchmark.py @@ -412,6 +412,10 @@ def run_docker(task: phibench.PhiTask, mode: str, out: Path, *, python: str, 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 @@ -455,12 +459,15 @@ def run_mode(task: phibench.PhiTask, mode: str, out: Path, *, executor: str, 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"] if record["grade"].get("timed_out"): # As the suite runner does: a grader cut off at its timeout is a hard fail. - record["score"]["hard_fail_reasons"].append("verifier_timed_out") + 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. - record["score"]["hard_fail_reasons"].append("no_reward_file") + if "no_reward_file" not in reasons: + reasons.append("no_reward_file") record["status"] = "no_reward" patch = Path(record["artifacts"]) / "model.patch" record["model_patch_bytes"] = patch.stat().st_size if patch.is_file() else None diff --git a/tests/benchmark/test_external_phibench.py b/tests/benchmark/test_external_phibench.py index 563854a35..dda697423 100644 --- a/tests/benchmark/test_external_phibench.py +++ b/tests/benchmark/test_external_phibench.py @@ -255,6 +255,26 @@ def test_docker_executor_delegates_controls_to_the_suite_runner(suite, tmp_path) 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"] == "graded" + assert result["score"]["hard_fail_reasons"] == ["verifier_timed_out"] + 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"), From 2d6072b91a100d1c48c8f801cc390e49440c31c5 Mon Sep 17 00:00:00 2001 From: dengyunyang <584797741@qq.com> Date: Thu, 26 Nov 2026 20:58:25 +0800 Subject: [PATCH 11/14] =?UTF-8?q?Count=20a=20=CE=A6-Bench=20grader's=20own?= =?UTF-8?q?=20124/137=20exit=20as=20a=20timeout=20and=20cap=20control=20la?= =?UTF-8?q?ndings?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The suite runner marks verifier_timed_out on exit code 124 or 137, but the rootless adapter only did so when its own host timeout fired, so a noop whose grader killed itself at its timeout still judged PASS. Match the runner, and add the reason once only. Reference landings now stop at 1800 s, as the suite's oracle stage does, instead of hanging a selfcheck forever. Refs #688. Agent-assisted-by: Claude Code / claude-opus-5-5 (author) Signed-off-by: dengyunyang <584797741@qq.com> Co-Authored-By: Claude Opus 5.5 --- docs/benchmarks/public-benchmarks.md | 2 +- .../apps/workflows/external_benchmark.py | 13 +++++++++--- tests/benchmark/test_external_phibench.py | 20 +++++++++++++++++++ 3 files changed, 31 insertions(+), 4 deletions(-) diff --git a/docs/benchmarks/public-benchmarks.md b/docs/benchmarks/public-benchmarks.md index eaab39555..280c3126a 100644 --- a/docs/benchmarks/public-benchmarks.md +++ b/docs/benchmarks/public-benchmarks.md @@ -50,7 +50,7 @@ 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`, 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. Without a `timeout_sec` in `task.toml` the steps use the suite runner's defaults (agent 5400 s, grader 3600 s). `--agent-env NAME` forwards an +at its own timeout adds the hard fail `verifier_timed_out`, 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. 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 diff --git a/src/inferrsi/apps/workflows/external_benchmark.py b/src/inferrsi/apps/workflows/external_benchmark.py index fd7f568c7..e4da8a2f8 100644 --- a/src/inferrsi/apps/workflows/external_benchmark.py +++ b/src/inferrsi/apps/workflows/external_benchmark.py @@ -46,6 +46,9 @@ 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 @@ -357,7 +360,8 @@ def run_rootless(task: phibench.PhiTask, mode: str, out: Path, *, proot: str, py 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 None)} + 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: @@ -460,8 +464,11 @@ def run_mode(task: phibench.PhiTask, mode: str, out: Path, *, executor: str, if record.get("status") == "graded": record["score"] = phibench.read_reward(Path(record["verifier_dir"])) reasons = record["score"]["hard_fail_reasons"] - if record["grade"].get("timed_out"): - # As the suite runner does: a grader cut off at its timeout is a hard fail. + 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: diff --git a/tests/benchmark/test_external_phibench.py b/tests/benchmark/test_external_phibench.py index dda697423..e62783b4b 100644 --- a/tests/benchmark/test_external_phibench.py +++ b/tests/benchmark/test_external_phibench.py @@ -521,6 +521,26 @@ def fake_run(argv, log, timeout): assert result["status"] == "no_reward" +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 phibench.judge_control(task, "noop", result["score"])["verdict"] == "INCONCLUSIVE" + assert seen["landing.log"] == 1800.0 + + def test_a_grader_that_writes_no_reward_is_not_a_score(suite, tmp_path, monkeypatch, capsys): task = phibench.get_task(suite, TASK) From 37a0f77578b48c54caf21e8bd88fc60b48545046 Mon Sep 17 00:00:00 2001 From: Dong1017 <55723162+Dong1017@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:09:32 +0800 Subject: [PATCH 12/14] Report a timed-out grader as verifier_timeout even when it wrote a reward --- CHANGELOG.md | 4 +- docs/benchmarks/public-benchmarks.md | 5 ++- .../apps/workflows/external_benchmark.py | 5 +++ tests/benchmark/test_external_phibench.py | 42 ++++++++++++++++++- 4 files changed, 52 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 32d34e9c3..c07d42420 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,7 +16,9 @@ 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` (a control judged on it is `INCONCLUSIVE`); a run with no readable + `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; the rootless agent step cannot see the suite clone and cannot leave files for the grading step under `/tests` or `/logs/verifier`. diff --git a/docs/benchmarks/public-benchmarks.md b/docs/benchmarks/public-benchmarks.md index 280c3126a..bd033619f 100644 --- a/docs/benchmarks/public-benchmarks.md +++ b/docs/benchmarks/public-benchmarks.md @@ -50,7 +50,10 @@ 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`, 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. 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 +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. 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 diff --git a/src/inferrsi/apps/workflows/external_benchmark.py b/src/inferrsi/apps/workflows/external_benchmark.py index e4da8a2f8..3bf8a748f 100644 --- a/src/inferrsi/apps/workflows/external_benchmark.py +++ b/src/inferrsi/apps/workflows/external_benchmark.py @@ -475,6 +475,11 @@ def run_mode(task: phibench.PhiTask, mode: str, out: Path, *, executor: str, # 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 diff --git a/tests/benchmark/test_external_phibench.py b/tests/benchmark/test_external_phibench.py index e62783b4b..d9e09f90e 100644 --- a/tests/benchmark/test_external_phibench.py +++ b/tests/benchmark/test_external_phibench.py @@ -270,8 +270,9 @@ def test_docker_run_keeps_the_runners_hard_fails(suite, tmp_path): task = phibench.get_task(suite, TASK) result = ext.run_mode(task, "noop", tmp_path / "out", executor="docker", python=sys.executable) - assert result["status"] == "graded" + 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" @@ -518,7 +519,7 @@ def fake_run(argv, log, timeout): 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"] == "no_reward" + assert result["status"] == "verifier_timeout" def test_a_grader_that_exits_124_itself_timed_out(suite, tmp_path, monkeypatch): @@ -537,10 +538,47 @@ def fake_run(argv, log, timeout): 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) From d53d15e6c5ffb9958eddd7628fc8b2f2b746eda0 Mon Sep 17 00:00:00 2001 From: Dong1017 <55723162+Dong1017@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:12:59 +0800 Subject: [PATCH 13/14] Read task.toml timeouts the way the suite's TOML parser does --- .../apps/workflows/external_benchmark.py | 35 +++++++++++++++---- tests/benchmark/test_external_phibench.py | 13 +++++++ 2 files changed, 42 insertions(+), 6 deletions(-) diff --git a/src/inferrsi/apps/workflows/external_benchmark.py b/src/inferrsi/apps/workflows/external_benchmark.py index 3bf8a748f..b4e721642 100644 --- a/src/inferrsi/apps/workflows/external_benchmark.py +++ b/src/inferrsi/apps/workflows/external_benchmark.py @@ -231,12 +231,35 @@ 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.""" text = (task.package_root / "task.toml").read_text(encoding="utf-8") - body = re.search(rf"^\[{section}\](.*?)(?=^\[|\Z)", text, re.S | re.M) - match = body and re.search(r"^timeout_sec\s*=\s*([0-9.]+)", body.group(1), re.M) - if not match: - head = re.split(r"^\[", text, maxsplit=1, flags=re.M)[0] - match = re.search(rf"^{top_key}\s*=\s*([0-9.]+)", head, re.M) - return float(match.group(1)) if match else default + value = _toml_timeout(text, section, "timeout_sec") + if value is None: + value = _toml_timeout(text, None, top_key) + return default if value is None else value + + +def _toml_timeout(text: str, section: str | None, key: str) -> float | None: + """Read one integer/float timeout the way the suite runner's TOML parser does. + + The suite parses task.toml with tomllib/tomli, so ``1_000`` is a thousand and a + key may be indented. Read the same subset here: only inside ``[section]`` (or + before the first table header for the top level), accepting TOML digit + separators. + """ + if section is None: + body = re.split(r"^[ \t]*\[", text, maxsplit=1, flags=re.M)[0] + else: + table = re.search(rf"^[ \t]*\[{re.escape(section)}\][ \t]*$", text, re.M) + if table is None: + return None + body = text[table.end():] + following = re.search(r"^[ \t]*\[", body, re.M) + if following is not None: + body = body[:following.start()] + match = re.search(rf"^[ \t]*{re.escape(key)}[ \t]*=[ \t]*([0-9][0-9_]*(?:\.[0-9_]+)?)", + body, re.M) + if match is None: + return None + return float(match.group(1).replace("_", "")) def _verifier_timeout(task: phibench.PhiTask) -> float: diff --git a/tests/benchmark/test_external_phibench.py b/tests/benchmark/test_external_phibench.py index d9e09f90e..36c8901ea 100644 --- a/tests/benchmark/test_external_phibench.py +++ b/tests/benchmark/test_external_phibench.py @@ -308,6 +308,19 @@ def test_timeouts_fall_back_like_the_suite_runner(suite): 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 + + 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] From 6f0e6c0122e73d7a07bb28ccfb4d36e1a511a4b8 Mon Sep 17 00:00:00 2001 From: Dong1017 <55723162+Dong1017@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:58:39 +0800 Subject: [PATCH 14/14] Parse task.toml with the suite's own TOML parser A comment after [verifier] and an exponent such as 1e3 changed the execution budget under the numeric-prefix regex. Read the file with tomllib, or tomli on Python 3.10, and cover both as regressions. --- CHANGELOG.md | 3 +- docs/benchmarks/public-benchmarks.md | 2 +- pyproject.toml | 2 +- .../apps/workflows/external_benchmark.py | 46 ++++++++----------- tests/benchmark/test_external_phibench.py | 5 ++ 5 files changed, 27 insertions(+), 31 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c07d42420..857ecc3d5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,7 +20,8 @@ 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; the rootless agent step cannot see the suite clone and + 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 diff --git a/docs/benchmarks/public-benchmarks.md b/docs/benchmarks/public-benchmarks.md index bd033619f..b60c7d8b9 100644 --- a/docs/benchmarks/public-benchmarks.md +++ b/docs/benchmarks/public-benchmarks.md @@ -53,7 +53,7 @@ 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. 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 +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 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/workflows/external_benchmark.py b/src/inferrsi/apps/workflows/external_benchmark.py index b4e721642..356f13d28 100644 --- a/src/inferrsi/apps/workflows/external_benchmark.py +++ b/src/inferrsi/apps/workflows/external_benchmark.py @@ -40,6 +40,11 @@ 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") @@ -229,37 +234,22 @@ def _run(argv: list[str], log: Path, timeout: float | None) -> dict: 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.""" - text = (task.package_root / "task.toml").read_text(encoding="utf-8") - value = _toml_timeout(text, section, "timeout_sec") - if value is None: - value = _toml_timeout(text, None, top_key) - return default if value is None else value + """``[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 _toml_timeout(text: str, section: str | None, key: str) -> float | None: - """Read one integer/float timeout the way the suite runner's TOML parser does. - The suite parses task.toml with tomllib/tomli, so ``1_000`` is a thousand and a - key may be indented. Read the same subset here: only inside ``[section]`` (or - before the first table header for the top level), accepting TOML digit - separators. - """ - if section is None: - body = re.split(r"^[ \t]*\[", text, maxsplit=1, flags=re.M)[0] - else: - table = re.search(rf"^[ \t]*\[{re.escape(section)}\][ \t]*$", text, re.M) - if table is None: - return None - body = text[table.end():] - following = re.search(r"^[ \t]*\[", body, re.M) - if following is not None: - body = body[:following.start()] - match = re.search(rf"^[ \t]*{re.escape(key)}[ \t]*=[ \t]*([0-9][0-9_]*(?:\.[0-9_]+)?)", - body, re.M) - if match is None: - return None - return float(match.group(1).replace("_", "")) +def _is_number(value: object) -> bool: + return isinstance(value, (int, float)) and not isinstance(value, bool) def _verifier_timeout(task: phibench.PhiTask) -> float: diff --git a/tests/benchmark/test_external_phibench.py b/tests/benchmark/test_external_phibench.py index 36c8901ea..03fcb07c2 100644 --- a/tests/benchmark/test_external_phibench.py +++ b/tests/benchmark/test_external_phibench.py @@ -319,6 +319,11 @@ def test_timeouts_parse_like_the_suites_toml(suite): (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):