Skip to content

HarnessRouter Community Edition: the self-hosted, Apache-2.0 edition of the unified interface for agent harnesses. Run Codex, Claude Code, Hermes, PI, DSH, and more through one API, with sessions, streaming, files, cancellation, and failure handling. Implements the Unified Harness Protocol (UHP), an open standard. Your keys, your infrastructure.

benchmark: a dimension beside the matrix, harness x model on public task suites

Hao Lu7ce16e5b656c
diff --git a/docs/harness-verification.md b/docs/harness-verification.md
index 426e1523..d5cad286 100644
--- a/docs/harness-verification.md
+++ b/docs/harness-verification.md
@@ -196,6 +196,14 @@ and need no edit — they were hand-written lists once, and each silently missed
Its models must be honest: every id the picker offers must run as itself, and a turn that ran on a
different model fails rather than quietly succeeding.
+## Beyond working: the benchmark dimension
+
+The matrix asks whether a harness works. `scripts/benchmark` asks how well a harness × model
+does the same work, on public task suites whose grading is deterministic, one task per session,
+every number read from the turn record. Its rules are the matrix's rules 1 and 2 plus three of
+its own (a run that reached the network is a finding, tokens on one convention, no judge), stated
+and pinned in [scripts/benchmark/README.md](../scripts/benchmark/README.md).
+
## Console changes
Any change to a console surface must survive narrow widths. `scripts/responsive-audit.mjs` sweeps
diff --git a/scripts/benchmark/README.md b/scripts/benchmark/README.md
new file mode 100644
index 00000000..c66a80ac
--- /dev/null
+++ b/scripts/benchmark/README.md
@@ -0,0 +1,87 @@
+# Benchmark suite
+
+The support matrix proves a harness *works*. This suite measures how well a harness × model
+configuration does the same work: public task suites with deterministic grading, run through the
+instance's own API, one task per session, every number read from the turn record the runner
+already stores. The rules below decide a row; `test_run.py` pins them.
+
+## What is measured
+
+For every harness and model named, each task of a pack runs in a fresh session: the pack stages
+the task's files and instruction as the first turn, the turn runs, the files it produced come back
+from the session, and the suite's own grader decides. A record carries the verdict (`resolved`,
+`reward` in [0, 1], the grader's reason), wall time, tool calls and tool names, fresh / cached /
+output tokens, the connection and the served model the turn record stamps, and the files.
+
+Packs live in `packs/`, one module each, and never re-implement a grader: the suite's data and
+grader stay outside this repository, at `PACK_ROOT`, under the suite's own licence.
+
+| Pack | Suite | Grading | Needs on the grading machine |
+|---|---|---|---|
+| `spreadsheetbench` | [SpreadsheetBench Verified](https://github.com/RUCKBReasoning/SpreadsheetBench) (400 real spreadsheet-manipulation questions, NeurIPS 2024 D&B) | the suite's `evaluation.py`, cell by cell over the answer range | `openpyxl`; LibreOffice (`soffice`) so a workbook saved with formulas has values to compare |
+
+## The rules that decide a row
+
+**1. It ran where you said.** Set `EXPECT_CONNECTION` to the connection under test; a run whose turn
+record names another connection is a finding, never a score. The matrix's rule 1, unchanged.
+
+**2. It ran what you asked.** A served model other than the id asked for is a finding, judged by
+`samemodel.py` exactly as the matrix judges it: an aggregator's prefix or a provider's version
+suffix is the same model, another family, number or tier is not. A harness whose turn record
+carries no served model is scored, and the row says on how many runs rule 2 could not be checked.
+
+**3. It did the task, not a lookup.** The sandbox has internet. The first pilot's third task
+fetched its own ground truth from the suite's public data, because the task id was in a filename.
+So a pack names nothing — the workbook is `input.xlsx`, the answer `output.xlsx`, the prompt
+carries no id — and a run whose tool calls made a request (a web tool; `curl`, `wget`, `git clone`,
+`urllib.request`, `requests`, `httpx`, `aiohttp` in a shell or script) is a finding, never a
+score. Package installs are the sandbox's normal traffic and do not count; a URL merely spelled
+in code (an xlsx's XML namespaces) does not either. Disable the harness's web tools as well, on
+the harness or the connection: the rule catches what the switch missed.
+
+**4. Tokens on one convention.** Fresh input, cached input and output are reported apart and
+never summed: a cached read is the same prompt read again, not new input. The runner's contract
+is `input_tokens` = fresh input (codex, gemini and, since #209, cline are netted to it); an
+instance older than #209 reports cline's input gross, and its rows say so in their notes.
+
+**5. No judge.** A suite whose grading needs a model's opinion is not a pack. Findings and
+runner errors are listed under the table, not scored.
+
+## Running it
+
+```
+export BASE=http://127.0.0.1:3000/api/harness HR_API_KEY=... PROVIDER=deepseek EXPECT_CONNECTION=integration:deepseek
+export PACK=spreadsheetbench PACK_ROOT=/data/spreadsheetbench_verified_400 # dataset.json + spreadsheet/ + the suite's evaluation.py, open_spreadsheet.py
+HARNESSES=opencode=chrn_...,pi=chrn_...,cline=chrn_...,dsh=chrn_... MODELS=deepseek-v4.1-flash TASKS=first:50 \
+ RESULTS=results-deepseek.json LOG=log-deepseek.txt WORKERS=2 python3 run.py
+python3 render.py results-deepseek.json > ../../docs/benchmark.md
+```
+
+`HARNESSES` is `label=id`: a custom harness with its web tools off is its `chrn_` id, a built-in
+its backend name. `TASKS` is `first:N` or a comma list of ids; the default is the whole pack.
+Resumable: a task already recorded for a harness × model × pack is skipped, a record carrying
+`error` (this runner's own failure) is re-run. Sessions are deleted once graded, as the matrix
+does; `KEEP=1` leaves them. An instance whose console proxy cut a synchronous turn at five minutes
+(before #214) still ran it: the runner finds the session it opened and grades from the record.
+
+## The first slice
+
+Five tasks of SpreadsheetBench Verified, four harnesses with web tools off, `deepseek-v4.1-flash`
+through one custom connection, self-hosted CE 0.18.x, 2026-09-17. Twenty runs, under one US
+dollar of inference. The instance predated #209, so cline's row is netted by hand from the
+per-request records; every other row is as the turn record stored it.
+
+| Harness | Resolved | Wall (sum) | Tool calls | Fresh in | Cached in | Output |
+|---|---|---|---|---|---|---|
+| opencode | 4/5 | 563 s | 62 | 73k | 1.40M | 11k |
+| pi | 4/5 | 767 s | 80 | 74k | 2.33M | 143k |
+| dsh | 4/5 | 874 s | 95 | 89k | 2.37M | 143k |
+| cline | 4/5 | 998 s | 100 | 152k | 2.27M | 156k |
+
+All four resolve the same four tasks and fail the same one, so on this slice the harness shows in
+efficiency, not correctness: 1.8× in wall time, 1.6× in prompt volume, 14× in output tokens.
+Two things this slice found are now fixed upstream: cline's cached reads were counted as input
+(#209), and the console proxy cut synchronous turns at five minutes (#214). Two remain open:
+through a custom OpenAI-format connection, cline's and dsh's turn records carry no served model,
+so rule 2 cannot be checked on them; and one task in the first, un-anonymised run was answered by
+fetching the suite's ground truth, which is why rule 3 exists.
diff --git a/scripts/benchmark/packs/__init__.py b/scripts/benchmark/packs/__init__.py
new file mode 100644
index 00000000..a17e37f2
--- /dev/null
+++ b/scripts/benchmark/packs/__init__.py
@@ -0,0 +1,24 @@
+"""Task packs: public suites whose grading is deterministic, each in one module.
+
+A pack module exposes three functions and one string:
+
+ NAME the pack's name in results and tables
+ load(root) -> list of tasks, each a dict with at least "id"; "root" is where the suite's
+ data lives on this machine (never inside the repository)
+ stage(task, root) -> {"prompt": str, "files": [(filename, bytes), ...]}; the turn's first
+ message and the files it starts with. Nothing here may name the suite or
+ the task: an id in a filename is a search key, and a turn that looked its
+ task up is measured on the wrong thing (see README, rule 3)
+ grade(task, root, produced, workdir) -> {"reward": float in [0, 1], "resolved": bool,
+ "detail": str}; "produced" maps each file the turn produced to its local
+ path. The suite's own grader decides; a pack never re-implements one.
+"""
+from importlib import import_module
+
+PACKS = {"spreadsheetbench": "packs.spreadsheetbench"}
+
+
+def get(name: str):
+ if name not in PACKS:
+ raise SystemExit(f"unknown pack {name!r}; one of {sorted(PACKS)}")
+ return import_module(PACKS[name])
diff --git a/scripts/benchmark/packs/spreadsheetbench.py b/scripts/benchmark/packs/spreadsheetbench.py
new file mode 100644
index 00000000..05e80948
--- /dev/null
+++ b/scripts/benchmark/packs/spreadsheetbench.py
@@ -0,0 +1,95 @@
+"""SpreadsheetBench Verified (400) — RUCKBReasoning/SpreadsheetBench, NeurIPS 2024 D&B spotlight.
+
+Real spreadsheet-manipulation questions from Excel forums; each instruction carries an input
+workbook, a golden workbook and the cell range the answer must land in, and the suite's
+`evaluation.py` compares that range cell by cell (OJ-style). Sheet-level rows must match the whole
+range; cell-level rows the named cells.
+
+`root` is the extracted `spreadsheetbench_verified_400/` directory with the suite's
+`evaluation.py` and `open_spreadsheet.py` copied beside `dataset.json` — the grader is the suite's,
+imported from there, never a copy in this repository. Grading needs LibreOffice (`soffice`) on the
+grading machine, not in the sandbox: a workbook the agent saved with formulas has no cached values
+until a spreadsheet engine opens it, and openpyxl reads cached values only.
+"""
+import json
+import os
+import shutil
+import subprocess
+import sys
+
+NAME = "spreadsheetbench"
+
+INPUT = "input.xlsx"
+OUTPUT = "output.xlsx"
+
+# The suite's own framing (inference/prompt_format.py), addressed to an agent with a workspace
+# instead of a code generator: the file is there, the answer is a file, and the answer goes only
+# where the instruction says. VALUES rather than formulas keeps the grade about the task, not
+# about whether the grading machine's spreadsheet engine evaluates a function the same way.
+PROMPT = """You are working in a workspace that contains a spreadsheet file. Solve the spreadsheet manipulation task below by editing the workbook and saving the result to output_path inside the workspace. Python 3 is available; install packages with pip if you need them (openpyxl, pandas). Do not use the internet for anything other than pip: no web search, no fetching pages, no looking the task up. Write cell VALUES, not formulas, unless the instruction asks for formulas. Only modify cells inside answer_position on the answer sheet; leave everything else exactly as it is (other sheets, formatting, column widths). When the file is saved, reply with one line: done.
+
+### instruction
+{instruction}
+
+### spreadsheet_path
+{spreadsheet_path}
+
+### instruction_type
+{instruction_type}
+
+### answer_position
+{answer_sheet}!{answer_position}
+
+### output_path
+{output_path}
+"""
+
+
+def load(root: str) -> list[dict]:
+ return json.load(open(os.path.join(root, "dataset.json"), encoding="utf-8"))
+
+
+def stage(task: dict, root: str) -> dict:
+ init = os.path.join(root, "spreadsheet", task["id"], f"1_{task['id']}_init.xlsx")
+ with open(init, "rb") as f:
+ data = f.read()
+ prompt = PROMPT.format(instruction=task["instruction"], spreadsheet_path=INPUT,
+ instruction_type=task["instruction_type"], answer_sheet=task["answer_sheet"],
+ answer_position=task["answer_position"], output_path=OUTPUT)
+ return {"prompt": prompt, "files": [(INPUT, data)]}
+
+
+def _recalculate(path: str, workdir: str) -> bool:
+ soffice = shutil.which("soffice") or shutil.which("libreoffice")
+ if not soffice:
+ return False
+ tmp = os.path.join(workdir, "_recalc")
+ os.makedirs(tmp, exist_ok=True)
+ subprocess.run([soffice, "--headless", "--calc", "--convert-to", "xlsx", "--outdir", tmp, path],
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=180)
+ converted = os.path.join(tmp, os.path.basename(path))
+ if not os.path.exists(converted):
+ return False
+ shutil.move(converted, path)
+ return True
+
+
+def grade(task: dict, root: str, produced: dict[str, str], workdir: str) -> dict:
+ golden = os.path.join(root, "spreadsheet", task["id"], f"1_{task['id']}_golden.xlsx")
+ path = produced.get(OUTPUT)
+ if path is None:
+ # The agent may have saved under another name; one workbook that is not the input is it.
+ others = [p for n, p in produced.items() if n.endswith(".xlsx") and n != INPUT]
+ path = others[0] if len(others) == 1 else None
+ if path is None:
+ return {"reward": 0.0, "resolved": False, "detail": "no workbook produced"}
+ if root not in sys.path:
+ sys.path.insert(0, root)
+ from evaluation import compare_workbooks # the suite's grader, from the suite's own tree
+ recalculated = _recalculate(path, workdir)
+ try:
+ ok, detail = compare_workbooks(golden, path, task["instruction_type"], task["answer_position"])
+ except Exception as e: # noqa: BLE001 — a workbook the grader cannot open is a fail with its reason
+ return {"reward": 0.0, "resolved": False, "detail": f"grader: {e!r}"[:300]}
+ return {"reward": 1.0 if ok else 0.0, "resolved": bool(ok),
+ "detail": (str(detail)[:300] if detail else "") + ("" if recalculated else " (no soffice: formulas unevaluated)")}
diff --git a/scripts/benchmark/render.py b/scripts/benchmark/render.py
new file mode 100644
index 00000000..69de079d
--- /dev/null
+++ b/scripts/benchmark/render.py
@@ -0,0 +1,94 @@
+"""Render benchmark results as markdown: one table per provider x pack, a row per harness x model.
+
+A row's score counts only the runs that were what they claimed to be: a run served by another
+connection, served as another model, or that reached the network is a finding listed under the
+table and left out of the score, the matrix's rules 1 and 2 plus this suite's rule 3. Tokens are on
+one convention — fresh input, cached input and output reported apart — and never summed across
+the three, since a cached read is the same prompt read again, not new input.
+Usage: python3 render.py results.json [more.json ...] > ../../docs/benchmark.md
+"""
+import collections
+import json
+import statistics
+import sys
+
+
+def median(xs):
+ xs = [x for x in xs if isinstance(x, (int, float))]
+ return statistics.median(xs) if xs else None
+
+
+def fmt_s(x):
+ return "-" if x is None else f"{x:.0f} s"
+
+
+def fmt_k(n):
+ return "-" if n is None else (f"{n / 1e6:.2f}M" if n >= 1e6 else f"{n / 1e3:.0f}k")
+
+
+def render(records: list[dict]) -> str:
+ by = collections.defaultdict(list)
+ for r in records:
+ by[(r.get("provider", "?"), r.get("pack", "?"))].append(r)
+ out = ["# Harness benchmark", "",
+ "How a row is measured, and the rules that decide it, are in "
+ "[scripts/benchmark/README.md](../scripts/benchmark/README.md). One task is one session; "
+ "the pack's own grader decides; every number is read from the turn record.", ""]
+ for (prov, pack), rows in sorted(by.items()):
+ out += [f"## Provider: {prov} — pack: {pack}", "",
+ "| Harness | Model | Tasks | Resolved | Reward | Median wall | Median tool calls | Fresh in | Cached in | Output | Served by | Notes |",
+ "|---|---|---|---|---|---|---|---|---|---|---|---|"]
+ findings, errors = [], []
+ groups = collections.defaultdict(list)
+ for r in rows:
+ groups[(r.get("harness", "?"), r.get("model", "?"))].append(r)
+ for (h, m), rs in sorted(groups.items()):
+ ran = [r for r in rs if not r.get("error")]
+ errors += [f"{h} x {m} {r.get('task')}: {r['error'][:120]}" for r in rs if r.get("error")]
+ clean, notes = [], []
+ for r in ran:
+ why = []
+ if r.get("foreign"):
+ why.append(f"served by {r['foreign']}")
+ if r.get("substituted"):
+ why.append(f"served as {r.get('served')}")
+ if r.get("network"):
+ why.append("reached the network: " + "; ".join(str(x) for x in r["network"])[:120])
+ if why:
+ findings.append(f"{h} x {m} {r.get('task')}: " + ", ".join(why))
+ else:
+ clean.append(r)
+ unreported = sum(1 for r in ran if r.get("served_unreported"))
+ if unreported:
+ notes.append(f"served model unreported on {unreported} of {len(ran)} runs (rule 2 unverifiable there)")
+ if len(clean) < len(ran):
+ notes.append(f"{len(ran) - len(clean)} runs are findings, not counted")
+ u = [r.get("usage") or {} for r in clean]
+ served = sorted({str(r.get("connection") or "").replace("integration:", "") for r in ran if r.get("connection")}) or ["?"]
+ resolved = sum(1 for r in clean if r.get("resolved"))
+ reward = statistics.mean(float(r.get("reward") or 0) for r in clean) if clean else None
+ out.append(
+ f"| {h} | {m} | {len(clean)} | {resolved} ({100 * resolved / len(clean):.0f}%) | "
+ f"{'-' if reward is None else f'{reward:.2f}'} | {fmt_s(median(r.get('wall_s') for r in clean))} | "
+ f"{'-' if not clean else f'{median(r.get('tool_calls') for r in clean):.0f}'} | "
+ f"{fmt_k(sum(x.get('fresh_input', 0) for x in u)) if u else '-'} | "
+ f"{fmt_k(sum(x.get('cached_input', 0) for x in u)) if u else '-'} | "
+ f"{fmt_k(sum(x.get('output', 0) for x in u)) if u else '-'} | {', '.join(served)} | "
+ f"{' ; '.join(notes).replace('|', '/')} |"
+ if clean else
+ f"| {h} | {m} | 0 | - | - | - | - | - | - | - | {', '.join(served)} | {' ; '.join(notes) or 'no counted runs'} |")
+ out.append("")
+ if findings:
+ out += ["Findings, runs served by another connection, as another model, or that reached the network — listed, not scored:", ""]
+ out += [f"- {f}" for f in findings] + [""]
+ if errors:
+ out += ["Runner errors (the run never produced a record to judge; re-run them):", ""] + [f"- {e}" for e in errors] + [""]
+ return "\n".join(out)
+
+
+if __name__ == "__main__":
+ recs: list[dict] = []
+ for path in sys.argv[1:]:
+ data = json.load(open(path, encoding="utf-8"))
+ recs += list(data.values()) if isinstance(data, dict) else list(data)
+ print(render(recs))
diff --git a/scripts/benchmark/run.py b/scripts/benchmark/run.py
new file mode 100644
index 00000000..22209879
--- /dev/null
+++ b/scripts/benchmark/run.py
@@ -0,0 +1,261 @@
+"""Benchmark runner: harness x model x pack x task, through the instance's own API.
+
+One task is one session: the pack stages the files and the first message, the turn runs, the
+produced files come back from the session, the pack's grader decides, and every number in the
+record is read from the turn record the runner already stores. Nothing is instrumented here.
+Resumable: a task already recorded for a harness x model x pack is skipped; a record carrying
+`error` (this runner's own failure, not the turn's) is re-run.
+
+Env: BASE (the API base, e.g. http://127.0.0.1:3000/api/harness), HR_API_KEY, PACK, PACK_ROOT,
+HARNESSES (comma list of label=id; a custom harness is its chrn_ id, a built-in its backend name),
+MODELS (comma), PROVIDER (a label for the column), EXPECT_CONNECTION (the connection under test,
+integration:<name>; any other one is a finding), TASKS (first:N, or a comma list of ids; default
+all), RESULTS (json path), LOG (append log), WORKDIR (produced files), WORKERS (parallel tasks per
+harness, default 1), KEEP=1 to leave sessions on the instance (they are deleted once graded, as
+the support matrix does, since a pack's worth of workspaces fills a disk).
+"""
+import json
+import os
+import re
+import sys
+import threading
+import time
+import urllib.error
+import urllib.request
+from base64 import b64encode
+from concurrent.futures import ThreadPoolExecutor
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+sys.path.insert(0, HERE)
+sys.path.insert(0, os.path.join(HERE, "..", "support-matrix"))
+import packs # noqa: E402
+from samemodel import alias_of # noqa: E402 — the matrix's rule 2, verbatim
+
+BASE = os.environ.get("BASE", "http://127.0.0.1:3000/api/harness").rstrip("/")
+KEY = os.environ.get("HR_API_KEY", "")
+LOG = os.environ.get("LOG", "")
+_lock = threading.Lock()
+
+
+def log(s: str) -> None:
+ line = f"{time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())} {s}"
+ with _lock:
+ print(line, flush=True)
+ if LOG:
+ with open(LOG, "a", encoding="utf-8") as f:
+ f.write(line + "\n")
+
+
+def api(method: str, path: str, body=None, raw: bool = False, timeout: int = 1800):
+ req = urllib.request.Request(BASE + path, method=method, headers={"authorization": f"Bearer {KEY}"})
+ data = None
+ if body is not None:
+ req.add_header("content-type", "application/json")
+ data = json.dumps(body).encode()
+ with urllib.request.urlopen(req, data, timeout=timeout) as r:
+ return r.read() if raw else json.loads(r.read())
+
+
+# ── rule 3: a turn that reached the network is a finding, never a score ──────────────────────────
+# The first pilot's third task fetched its own ground truth from the suite's public data because
+# the task id was in a filename and the sandbox has internet. Packs anonymise; this reads the tool
+# calls the runner stored for the turn and names any that went out for anything but pip.
+WEB_TOOL = re.compile(r"web|fetch|search|browse|http", re.I)
+# What makes a request from a shell or a script, not what merely spells a URL: the XML namespaces
+# inside an xlsx are http:// strings, and a turn parsing one with zipfile went nowhere. Package
+# installs (pip, npm) are the sandbox's normal traffic and are not the task's answer.
+NET_IN_SHELL = re.compile(r"\b(curl|wget|git\s+clone)\b|\burllib\.request\b|\brequests\.(?:get|post|request|Session)\b"
+ r"|\bhttpx\.|\baiohttp\b", re.I)
+
+
+def network_use(tools: list[dict]) -> list[str]:
+ hits = []
+ for t in tools or []:
+ name = str(t.get("name") or "")
+ args = t.get("arguments") or ""
+ if WEB_TOOL.search(name):
+ hits.append(name)
+ continue
+ cmd = args
+ if isinstance(args, str) and args.startswith("{"):
+ try:
+ cmd = json.loads(args).get("command", "")
+ except ValueError:
+ cmd = args
+ if isinstance(cmd, str) and NET_IN_SHELL.search(cmd):
+ hits.append(f"{name}: {cmd[:120]}")
+ return hits
+
+
+# ── usage on one convention ───────────────────────────────────────────────────────────────────────
+# The runner's contract is input_tokens = fresh input, cache reads and writes beside it (codex,
+# gemini and, since #209, cline are netted to it). The table reports fresh, cached and output
+# separately and never adds a cached read to the input it was read from.
+def usage_of(u: dict | None) -> dict:
+ u = u or {}
+ fresh = int(u.get("input_tokens") or 0)
+ cached = int(u.get("cache_read_tokens") or 0)
+ written = int(u.get("cache_write_tokens") or 0)
+ out = int(u.get("output_tokens") or 0)
+ return {"fresh_input": fresh, "cached_input": cached, "cache_write": written, "output": out,
+ "prompt_total": fresh + cached + written}
+
+
+def recover_session(before: set[str], harness_id: str, prompt: str, t0: float, wait_s: int = 1800) -> dict | None:
+ """The session this harness opened for this prompt since t0 that was not there before, once
+ it has finished: an instance whose console proxy cuts a synchronous request at five minutes
+ (fixed by #214) still ran the turn, and the record is the record. With several workers the
+ prompt tells the sessions apart; a session whose stored prompt cannot be read is taken only
+ when it is the sole new one."""
+ deadline = t0 + wait_s
+ mark = prompt.strip()[-160:]
+ while time.time() < deadline:
+ new = [s for s in api("GET", "/v1/sessions?limit=100").get("sessions", [])
+ if s["session_id"] not in before and harness_id in (s.get("harness_id"), s.get("backend"))]
+ mine = [s for s in new if mark and mark in str(s.get("user_prompt") or "")]
+ if not mine and len(new) == 1:
+ mine = new
+ if not mine:
+ return None
+ if mine[0].get("status") not in ("running", "queued", None):
+ return mine[0]
+ time.sleep(10)
+ return None
+
+
+def run_task(pack, root: str, task: dict, label: str, harness_id: str, model: str, provider: str, workdir: str) -> dict:
+ staged = pack.stage(task, root)
+ content = [{"type": "input_text", "text": staged["prompt"]}]
+ for name, data in staged["files"]:
+ content.append({"type": "input_file", "filename": name,
+ "file_data": "data:application/octet-stream;base64," + b64encode(data).decode()})
+ body = {"input": [{"role": "user", "content": content}], "metadata": {"harness_id": harness_id},
+ "model": model, "stream": False}
+ rec = {"provider": provider, "harness": label, "harness_id": harness_id, "model": model, "pack": pack.NAME,
+ "task": task["id"], "at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())}
+ before = {s["session_id"] for s in api("GET", "/v1/sessions?limit=50").get("sessions", [])}
+ t0 = time.time()
+ sid = rid = None
+ try:
+ resp = api("POST", "/v1/responses", body)
+ rid = resp.get("id")
+ while resp.get("status") in ("in_progress", "queued"):
+ time.sleep(5)
+ resp = api("GET", f"/v1/responses/{rid}")
+ rec.update(status=resp.get("status"), wall_s=round(time.time() - t0, 1), sid=(resp.get("metadata") or {}).get("session_id"),
+ usage=usage_of(resp.get("usage")), turn_error=resp.get("error"))
+ sid = rec["sid"]
+ except (urllib.error.HTTPError, TimeoutError, OSError) as e:
+ err = f"{e.code} {e.read()[:200]!r}" if isinstance(e, urllib.error.HTTPError) else repr(e)[:200]
+ sess = recover_session(before, harness_id, staged["prompt"], t0)
+ if sess is None:
+ rec.update(error=f"request failed and no session found: {err}", wall_s=round(time.time() - t0, 1))
+ return rec
+ rec.update(status="completed" if sess.get("status") == "done" else sess.get("status"), recovered=err,
+ wall_s=sess.get("elapsed") or round(time.time() - t0, 1), sid=sess["session_id"],
+ usage=usage_of(sess.get("usage")), turn_error=None)
+ sid, rid = sess["session_id"], sess.get("last_response_id")
+ if not sid:
+ rec["error"] = "no session id on the response"
+ return rec
+ turns = api("GET", f"/v1/sessions/{sid}/turns").get("turns", [])
+ turn = next((t for t in turns if t.get("id") == rid), turns[-1] if turns else {})
+ tools = turn.get("tools") or []
+ served = str(turn.get("served_model") or "")
+ rec.update(connection=turn.get("connection"), served=served,
+ substituted=bool(served) and not alias_of(model, served),
+ served_unreported=not served,
+ tool_calls=len(tools), tools=sorted({str(t.get("name")) for t in tools}),
+ network=network_use(tools), files=[f.get("filename") for f in (turn.get("files") or [])],
+ assistant=(turn.get("assistant") or "")[:200])
+ if rec.get("turn_error") is None and turn.get("error"):
+ rec["turn_error"] = turn.get("error")
+ # the produced files, downloaded from the session so the pack grades what was stored
+ tdir = os.path.join(workdir, provider, label, model, pack.NAME, task["id"])
+ os.makedirs(tdir, exist_ok=True)
+ produced = {}
+ for f in turn.get("files") or []:
+ name = f.get("filename") or ""
+ if not name or f.get("download_url") is None:
+ continue
+ path = os.path.join(tdir, os.path.basename(name))
+ with open(path, "wb") as fh:
+ fh.write(api("GET", f["download_url"], raw=True))
+ produced[name] = path
+ g = pack.grade(task, root, produced, tdir)
+ rec.update(reward=g["reward"], resolved=bool(g["resolved"]), detail=g.get("detail", ""))
+ if os.environ.get("KEEP") != "1":
+ try:
+ api("DELETE", f"/v1/sessions/{sid}")
+ except Exception as e: # noqa: BLE001
+ rec["not_deleted"] = repr(e)[:80]
+ return rec
+
+
+def main() -> None:
+ pack = packs.get(os.environ["PACK"])
+ root = os.environ["PACK_ROOT"]
+ provider = os.environ.get("PROVIDER", "unlabelled")
+ expect = os.environ.get("EXPECT_CONNECTION", "")
+ results_path = os.environ.get("RESULTS", os.path.join(HERE, "results.json"))
+ workdir = os.environ.get("WORKDIR", os.path.join(HERE, "work"))
+ workers = int(os.environ.get("WORKERS", "1"))
+ harnesses = [(h.split("=", 1)[0], h.split("=", 1)[-1]) for h in os.environ["HARNESSES"].split(",") if h]
+ models = [m for m in os.environ["MODELS"].split(",") if m]
+ tasks = pack.load(root)
+ sel = os.environ.get("TASKS", "")
+ if sel.startswith("first:"):
+ tasks = tasks[:int(sel[6:])]
+ elif sel:
+ want = set(sel.split(","))
+ tasks = [t for t in tasks if t["id"] in want]
+
+ def load():
+ try:
+ return json.load(open(results_path, encoding="utf-8"))
+ except (OSError, ValueError):
+ return {}
+
+ def save(rec):
+ with _lock:
+ res = load()
+ res[key(rec)] = rec
+ json.dump(res, open(results_path, "w", encoding="utf-8"), indent=1)
+
+ def key(rec):
+ return f"{rec['provider']}|{rec['harness']}|{rec['model']}|{rec['pack']}|{rec['task']}"
+
+ for label, hid in harnesses:
+ for model in models:
+ todo = []
+ res = load()
+ for t in tasks:
+ k = f"{provider}|{label}|{model}|{pack.NAME}|{t['id']}"
+ if k in res and not res[k].get("error"):
+ continue
+ todo.append(t)
+ log(f"HARNESS {label} ({hid}) x {model}: {len(todo)} of {len(tasks)} tasks to run")
+
+ def one(t):
+ try:
+ rec = run_task(pack, root, t, label, hid, model, provider, workdir)
+ except Exception as e: # noqa: BLE001 — this runner's own failure, re-run next launch
+ rec = {"provider": provider, "harness": label, "harness_id": hid, "model": model,
+ "pack": pack.NAME, "task": t["id"], "error": repr(e)[:300]}
+ if expect and rec.get("connection") and rec["connection"] != expect:
+ rec["foreign"] = rec["connection"]
+ save(rec)
+ verdict = ("ERROR " + rec["error"][:80]) if rec.get("error") else \
+ ("FINDING network" if rec.get("network") else "FINDING foreign" if rec.get("foreign") else
+ "FINDING substituted" if rec.get("substituted") else
+ ("pass" if rec.get("resolved") else f"FAIL {rec.get('detail', '')[:60]}"))
+ log(f"TASK {label} x {model} {t['id']}: {verdict} {rec.get('wall_s', '?')}s tools={rec.get('tool_calls', '?')} "
+ f"served={rec.get('served') or 'unreported'} tokens={json.dumps(rec.get('usage') or {})}")
+
+ with ThreadPoolExecutor(max_workers=max(1, workers)) as ex:
+ list(ex.map(one, todo))
+ log("DONE")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/benchmark/test_run.py b/scripts/benchmark/test_run.py
new file mode 100644
index 00000000..cda364db
--- /dev/null
+++ b/scripts/benchmark/test_run.py
@@ -0,0 +1,84 @@
+"""The rules a benchmark row is decided by, pinned.
+
+Rule 3 exists because the first pilot's third task found its own ground truth online: the tool
+calls the runner stores for a turn say whether it went out, and a run that did is a finding, not
+a score. The usage convention exists because a cached read counted as input made one harness
+read as 30x another on the same task (#209)."""
+import json
+import os
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from render import render # noqa: E402
+from run import network_use, usage_of # noqa: E402
+
+
+def test_a_web_tool_or_a_shell_that_reaches_out_is_network_use():
+ assert network_use([{"name": "webfetch", "arguments": '{"url": "https://x"}'}]) == ["webfetch"]
+ assert network_use([{"name": "WebSearch", "arguments": "{}"}]) == ["WebSearch"]
+ hits = network_use([{"name": "bash", "arguments": json.dumps({"command": "curl -s https://example.com/answer.json"})}])
+ assert hits and hits[0].startswith("bash: curl")
+ assert network_use([{"name": "bash", "arguments": json.dumps({"command": "wget http://h/x"})}])
+
+
+def test_pip_and_local_work_are_not_network_use():
+ assert network_use([{"name": "bash", "arguments": json.dumps({"command": "pip install openpyxl pandas"})}]) == []
+ assert network_use([{"name": "bash", "arguments": json.dumps({"command": "python3 -m pip install openpyxl && python3 solve.py"})}]) == []
+ assert network_use([{"name": "bash", "arguments": json.dumps({"command": "ls -la && python3 solve.py"})}]) == []
+ assert network_use([{"name": "read", "arguments": '{"filePath": "/workspace/input.xlsx"}'}]) == []
+ assert network_use([]) == []
+
+
+def test_a_url_spelled_in_code_is_not_network_use():
+ """Measured: a turn that parsed the workbook with zipfile named the sheet XML's namespace,
+ http://schemas.openxmlformats.org/spreadsheetml/2006/main, in a python heredoc and went
+ nowhere; the first cut of this rule matched the string and called it a finding."""
+ cmd = ("cd /data/workspaces/x && python3 << 'EOF'\nimport zipfile, xml.etree.ElementTree as ET\n"
+ "ns = {'m': 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'}\nEOF")
+ assert network_use([{"name": "bash", "arguments": json.dumps({"command": cmd})}]) == []
+ assert network_use([{"name": "bash", "arguments": json.dumps({"command": "python3 -c 'import urllib.request; urllib.request.urlopen(\"http://x\")'"})}])
+ assert network_use([{"name": "bash", "arguments": json.dumps({"command": "python3 -c 'import requests; requests.get(\"http://x\")'"})}])
+
+
+def test_usage_keeps_fresh_cached_and_output_apart():
+ u = usage_of({"input_tokens": 14847, "output_tokens": 3623, "cache_read_tokens": 288000})
+ assert u == {"fresh_input": 14847, "cached_input": 288000, "cache_write": 0, "output": 3623, "prompt_total": 302847}
+ assert usage_of(None)["prompt_total"] == 0
+
+
+def _rec(**kw):
+ base = {"provider": "deepseek", "pack": "spreadsheetbench", "harness": "opencode", "model": "m", "task": "t",
+ "resolved": True, "reward": 1.0, "wall_s": 10.0, "tool_calls": 3, "connection": "integration:deepseek",
+ "served": "deepseek-flash", "usage": {"fresh_input": 100, "cached_input": 1000, "output": 10}}
+ base.update(kw)
+ return base
+
+
+def test_a_finding_is_listed_and_left_out_of_the_score():
+ md = render([_rec(task="a"), _rec(task="b", network=["webfetch"], resolved=True),
+ _rec(task="c", foreign="integration:other"), _rec(task="d", substituted=True, served="gpt-5.5")])
+ row = next(line for line in md.splitlines() if line.startswith("| opencode |"))
+ assert "| 1 | 1 (100%) |" in row, row # one counted run of four
+ assert "3 runs are findings, not counted" in row
+ assert "reached the network: webfetch" in md and "served by integration:other" in md and "served as gpt-5.5" in md
+
+
+def test_an_unreported_served_model_is_noted_not_scored_against():
+ md = render([_rec(served="", served_unreported=True)])
+ row = next(line for line in md.splitlines() if line.startswith("| opencode |"))
+ assert "| 1 | 1 (100%) |" in row
+ assert "served model unreported on 1 of 1 runs" in row
+
+
+def test_tokens_are_reported_apart_never_summed():
+ md = render([_rec(usage={"fresh_input": 1500, "cached_input": 2_000_000, "output": 700})])
+ row = next(line for line in md.splitlines() if line.startswith("| opencode |"))
+ assert "| 2k | 2.00M | 1k |" in row, row
+
+
+def test_a_runner_error_is_listed_as_an_error_not_a_fail():
+ md = render([_rec(task="a"), {"provider": "deepseek", "pack": "spreadsheetbench", "harness": "opencode", "model": "m",
+ "task": "b", "error": "request failed and no session found: 502"}])
+ assert "Runner errors" in md and "opencode x m b: request failed" in md
+ row = next(line for line in md.splitlines() if line.startswith("| opencode |"))
+ assert "| 1 | 1 (100%) |" in row