diff --git a/.env.example b/.env.example
index b53b61c..7c9db33 100644
--- a/.env.example
+++ b/.env.example
@@ -1,51 +1,18 @@
-# llm-bench configuration.
-# Copy to .env and edit. Env vars already in your shell take precedence
+# llm-bench configuration. Copy to .env and edit. Env vars already in your shell take precedence
# over values here (so you can override per-run without editing the file).
-# The OpenAI-compatible chat-completions URL of the model you're testing.
-# Examples:
-# LM Studio (local): http://127.0.0.1:1234/v1/chat/completions
-# Ollama (local): http://127.0.0.1:11434/v1/chat/completions
-# vLLM / llama-server: http://127.0.0.1:8000/v1/chat/completions
-# Ollama Cloud: https://api.ollama-cloud.com/v1/chat/completions
-# OpenAI: https://api.openai.com/v1/chat/completions
-ENDPOINT=http://127.0.0.1:1234/v1/chat/completions
-
-# The model id the endpoint expects in the "model" field of requests.
-# For LM Studio this is the load identifier; for Ollama it's the tag;
-# for vLLM/llama-server it's the served model name; for cloud it's the
-# API model string (e.g. "gpt-4o", "claude-sonnet-5" via a compat layer).
-MODEL=local
-
-# Bearer token, sent as "Authorization: Bearer <key>" if non-empty.
-# Leave blank for local endpoints (LM Studio, local Ollama, local vLLM).
-# Set for cloud endpoints or any endpoint that requires auth.
-API_KEY=
-
-# Per-turn generation cap (max_tokens in the request body).
-# Coding suite default is 8000; agentic benches default to 16000.
-MAX_TOKENS=8000
-
-# Sampling temperature. 0 = greedy (deterministic, recommended for
-# coding/tool-use benchmarks). Higher = more creative/noise.
-TEMPERATURE=0
-
-# Per-request wall timeout in seconds. Bump for slow local models.
-HTTP_TIMEOUT=900
-
-# Agentic loop cap — max turns the agent can take before giving up.
-# Only used by agentic-fix, agentic-build, agentic-multitask.
-MAX_TURNS=40
-
-# Suppress reasoning/thinking via an empty <think></think> assistant
-# prefill. Works on Qwen3-family and other models that use the think-tag
-# convention. Set to "1" to enable. Some backends also honor a
-# chat_template_kwargs.enable_thinking field (the no-think instrument
-# tests both paths).
-NOTHINK=
-
-# --- build/test timeouts (agentic benches) ---
-BUILD_TIMEOUT=180
-TEST_TIMEOUT=180
-SHELL_TIMEOUT=60
-SERVER_TIMEOUT=20
\ No newline at end of file
+# Lane profile, required for anything that calls a model: LANE=<id> -> lanes/<id>.json (endpoint,
+# model, sampler, max_tokens, thinking on/off, provider pinning, auth, cost cap). A lane with
+# "auth": {"env": "<VAR>"} reads its key from that variable, which can be set here too.
+LANE=
+
+# --- optional; uncomment to override ---
+# Agentic loop cap: the default of --max-turns (unset: 40, agentic-fix 24).
+# MAX_TURNS=40
+# Agentic tool + gate timeouts (s). Unset = per language: Go build/test/shell 180/180/60,
+# Rust 600/600/60, TS 120/120/300.
+# BUILD_TIMEOUT=180
+# TEST_TIMEOUT=180
+# SHELL_TIMEOUT=60
+# Spend-cap override for paid lanes (unset: the lane's cost.cap_usd).
+# LEDGER_CAP_USD=5
diff --git a/.gitignore b/.gitignore
index f12a21f..1d01288 100644
--- a/.gitignore
+++ b/.gitignore
@@ -15,6 +15,10 @@ bench/results/
# don't commit LLM_Memory files
.LLM_Memory
+# Fetched benchmark datasets — never commit (licenses: bench/data/reasoning/README.md)
+bench/data/reasoning/cache/
+bench/data/sleuth/cache/
+
# Local config — don't commit your endpoint/key
.env
diff --git a/CONTRACT.md b/CONTRACT.md
new file mode 100644
index 0000000..108b45a
--- /dev/null
+++ b/CONTRACT.md
@@ -0,0 +1,63 @@
+# Instrument contract
+
+Every instrument under `bench/tasks/` follows these rules so results from different lanes
+(model × quant × runtime × settings) can be joined item-by-item. Core lives in
+`bench/core/` — `lane.py`, `client.py`, `results.py`, `ledger.py`, `mockserver.py`.
+
+## Requests
+
+- Get the lane with `bench.core.lane.current()`; send every request through
+ `client.call_model(...)`. Never build an HTTP request yourself.
+- Do not read sampler or thinking settings from the environment. The lane owns the
+ sampler, `max_tokens`, thinking on/off and the no-think mechanism. Pass instrument defaults as
+ `max_tokens=` / `temperature=` kwargs — the lane overrides them. Use `override=` only when the
+ measurement itself requires a setting (e.g. greedy for a determinism probe), and record that.
+- Pass `item_id=` and `run_id=` to `call_model` so paid calls land in the spend ledger by item.
+- Message history: append the assistant message you got back (content + tool_calls) as-is. The
+ client strips reasoning fields and repairs non-JSON tool arguments before sending. Never put
+ reasoning text into `content`.
+- Catch `client.CallError` per item. Record it with `**client.error_meta(e, dt)` and move on.
+ `budget_stop` means stop the run (write what you have, `finish(complete=False)`).
+ `results.call_attempt(...)` does all of this for a single-call attempt.
+
+## Results
+
+- One `results.RunStore(instrument, item_set=..., args=...)` per run; `results.run_attempts(...)`
+ opens or resumes it, schedules the (item, sample) attempts and writes the summary. `item_set` =
+ `"<name>@<sha256 of the item definitions>[:12]"` so a changed task set never silently compares
+ against an old one.
+- One `store.add(...)` per attempt:
+ `store.add(item_id=..., sample_idx=..., category=..., correct=..., score=..., **client.meta(resp, dt), **extra)`
+ - `item_id`: stable string, never positional, the same on every lane.
+ - `category`: the capability-profile bucket (`easy/go`, `hard/rust`, `judge/shell`,
+ `rerank/logs`, `cs`, `needle/64k/decoy` …).
+ - `correct`: bool when graded; leave `None` when the attempt failed for infra reasons
+ (`RunStore.add` forces this for infra statuses).
+ - `score`: float in [0,1] for partial credit (e.g. agentic-multitask's fraction of gates passed), else omit.
+ - Grade truncated answers (`status: truncated`) on whatever content exists — usually wrong —
+ but keep the status; the report shows truncation rate separately.
+ - `status: empty` with ≥16 answer tokens generated (completion − reported reasoning) becomes
+ `stripped` (infra): the server ate the output. `RunStore.add` and the report both apply
+ `results.effective_status`, so already-stored rows reclassify on read.
+- Large per-item artifacts (turn logs, raw answers) go in `store.sidecar(name, obj)`; put the
+ returned file name in the row.
+- `store.finish(summary)` at the end. A run without `complete: true` is ignored by reports.
+
+## CLI conventions
+
+`run` accepts (`results.add_run_args`): `--samples K` (default 1), `--concurrency N`
+(≤ `lane.max_concurrency`), `--items id1,id2` (filter), `--resume RUN_DIR` (skip
+`store.done_keys()`; the run keeps the args recorded in its run.json and refuses a changed
+item_set). `validate` checks the item set offline (no model).
+
+## Isolation
+
+Work dirs live under `work/<run_id>/<item_id>-<sample_idx>/`. Subprocesses run in their own
+session (`start_new_session=True`) and are killed as a process group on timeout. Never bind a
+fixed port without checking it is free; release it before returning.
+
+## Testing
+
+No instrument change is tested against a live endpoint first. Use `bench.core.mockserver`
+(`MockServer`, `chat()`, `tool_call()`) and put tests in `tests/`. Python 3.9, stdlib only.
+Run: `python3 -m unittest discover -s tests`.
diff --git a/README.md b/README.md
index bd7ae63..2c90c76 100644
--- a/README.md
+++ b/README.md
@@ -1,17 +1,23 @@
# llm-bench
-A local LLM coding-model benchmark suite. Point it at any OpenAI-compatible
-endpoint, pick an instrument, and run. Pure stdlib Python — no packages needed.
+A local LLM benchmark suite: coding, reasoning, retrieval and troubleshooting. Point it at any
+OpenAI-compatible endpoint, pick an instrument, and run. Pure stdlib Python — no packages needed.
## Quick start
```bash
-cp .env.example .env # set ENDPOINT + MODEL for your model
-python bench.py coding-suite validate # prove tasks are well-formed (no model needed)
-python bench.py coding-suite run # run all 24 tasks against the model
+export LANE=example-lmstudio # a lane = endpoint + model + sampler + thinking + provenance (lanes/*.json)
+python3 bench.py conformance # preflight: rule out non-model problems (also runs before every `run`)
+python3 bench.py agentic-fix validate # prove tasks are well-formed (no model needed)
+python3 bench.py agentic-fix run --tier easy --samples 2
+python3 bench.py sleuth run --samples 3
+python3 bench.py report --out report.md # capability profile across lanes
```
-Results land in `results/` as JSONL + JSON. Work dirs in `work/` (both gitignored).
+Every run writes `bench/results/<instrument>/<lane_id>/<run_id>/{run.json, items.jsonl, summary.json}`
+(append-only, never overwritten; `run.json` carries the lane record, a server snapshot and the
+harness git sha). Work dirs live in `work/<run_id>/…`. Both are gitignored. How instruments must use
+the core is in [CONTRACT.md](CONTRACT.md).
## Instruments
@@ -21,55 +27,300 @@ python bench.py <instrument> <command> [args...]
| Instrument | Command(s) | What it measures |
|---|---|---|
-| `coding-suite` | `validate` / `run` / `report` | 24 single-turn bug-fix + tool-calling tasks, real toolchain (Go/Rust/Swift/TS) |
-| `agentic-fix` | `validate` / `run` | Multi-turn tool loop — find a cross-file bug in a small Go codebase |
-| `agentic-build` | `validate` / `run` | Build a Go+SQLite web app end-to-end (4 product gates: build/test/serve/persist) |
-| `agentic-multitask` | `validate <task>` / `run <task>` / `cohort <t1> <t2> ...` | Multi-task gauntlet: Go+HTMX, Rust CLI, Next.js+Prisma |
-| `router` | `validate` / `run` / `report` | Dispatch/router eval (26 ROUTE + 8 ORCH, deterministic scoring, privacy axis) |
-| `needle` | `run [--depths 1000,16000 --needles 3 --repeats 2]` | Needle-in-a-haystack retrieval + speed per depth |
-| `loop-battery` | `run` | CoT runaway probes (5 prompts × N runs, repetition scoring) |
-| `no-think` | `run` | Latency win from suppressing reasoning (think vs no-think A/B) |
+| `agentic-fix` | `validate` / `run [--tier easy\|hard\|all] [item ...]` | Bug fixes. easy: single-turn fixes run against hidden tests with the real toolchain (Go, Rust, TS, Python, shell, SQL; Swift on macOS only). hard: cross-file bugs in small projects, read-only tools + one submit_fix |
+| `agentic-multitask` | `validate` / `run [--tier easy\|hard\|all] [task ...]` / `cohort <t> ...` | Build real small apps through tools. easy: Go+HTMX, Next.js+Prisma; hard: Rust CLI |
+| `sleuth` | `validate [case]` / `run [case]` | Troubleshoot a broken Linux host through a root shell in a container: right culprit, right fix, evidence actually seen, and how many checks it took vs an expert path |
+| `router` | `validate` / `run [--families route,orch,judge,rerank]` / `report` | Small helper models: dispatch (26 route + 8 orch, privacy axis), judging technical work (24 verdict + 8 pairwise, both orders), reranking (16 queries; top-1, MRR, NDCG@5) |
+| `needle` | `validate` / `run [--depths 1000,16000 --positions 0.5 --variants plain,decoy --seeds N]` / `report` | Needle-in-a-haystack retrieval (plain / decoy / multikey) + prefill speed per depth |
+| `loop-battery` | `run` / `report` | CoT runaway probes (5 prompts × N samples, repetition scoring) |
+| `reasoning` | `fetch` / `validate` / `run` | Computing knowledge: 60 MMLU-Pro computer-science questions, graded on content |
+| `conformance` | (none) `[--checks ...]` | Per-lane preflight: sampler vs model card, think-tag parsing, tool-call and JSON probes, provider swallowing output. FAIL = non-model problem (exit 1); WARN = the model's miss. Runs automatically before every `run` (cached 24 h per lane settings; `BENCH_PREFLIGHT=0` skips) |
+| `report` | (none) `[--ref LANE --out PATH.md]` | Capability profile across lanes from stored runs (CIs, paired deltas, status, cost/speed) |
+| `oracle` | (none) `--order cheapest,...,priciest [--simulate]` | Per-item cheapest-passing-lane labels + routing-policy simulation |
+
+Every `run` takes `--samples K`, `--concurrency N`, `--items id1,id2` and `--resume RUN_DIR` (a
+resumed run keeps the settings recorded in its run.json and retries only infra failures).
### Examples
```bash
-# Coding suite (single-turn, ~5-15 min)
-python bench.py coding-suite run
+# Bug fixes: the easy tier only, then one hard item
+python3 bench.py agentic-fix run --tier easy
+python3 bench.py agentic-fix run --tier hard rust-allowlist
-# Agentic build (multi-turn, ~10-40 min)
-python bench.py agentic-build run
+# App builds: both tiers (easy then hard), 3 samples each
+python3 bench.py agentic-multitask run --samples 3
-# Full gauntlet — all three real-app tasks, sequential
-python bench.py agentic-multitask cohort go_htmx rust_cli ts_next
-
-# Router/dispatch eval
-python bench.py router run
+# Small-model helpers: judge and rerank only
+python3 bench.py router run --families judge,rerank
# Needle retrieval at specific depths
-python bench.py needle run --depths 1000,16000,64000
+python3 bench.py needle run --depths 1000,16000,64000
-# Override config per-run without editing .env
-ENDPOINT=http://10.0.0.40:8000/v1/chat/completions \
-MODEL=qwen3.8-27b \
-MAX_TOKENS=16000 \
-python bench.py agentic-build run
+# The Claude reference on sleuth (subscription, no API key)
+LANE=claude-opus python3 bench.py sleuth run --samples 3
```
+## Bench details
+
+What each instrument asks, how it grades, and what is in it. Grading is mechanical everywhere
+(hidden tests, gates, regexes, gold labels); no model judges another. Item content is frozen: a run
+records its item set as `<name>@<hash of the items>`, so editing an item starts a new item set, and
+a report never pools two versions of one. The `max_tokens` / temperature / turn numbers below are
+instrument defaults; a lane's own settings win. Which file holds what: see Project layout below.
+
+### agentic-fix — bug fixes
+
+The model fixes a bug, and the fix runs against tests it never sees. Two tiers, run separately
+(`--tier easy|hard|all`, default all).
+
+**easy** — 28 items, four per language. Item set `fix-easy@…`, category `easy/<lang>`. One message
+holds the symptom and the whole buggy file (SQL: the schema and one query); the model answers with
+the corrected file in a single fenced block. No tools, one turn, `max_tokens` 8000. The runner
+builds it and runs the hidden test with the real toolchain; SQL runs the query on a fixture DB in
+sqlite3 and compares the CSV output. Swift needs Xcode: elsewhere its rows are `skipped` (infra),
+never a fail.
+
+| Item | The bug |
+|---|---|
+| `go-average` | integer division before the float conversion truncates the mean |
+| `go-nilmap` | writes into a nil map (panic) |
+| `go-json-tags` | missing `json:"name"` tag, unexported `age` field |
+| `go-generics` | `make([]U, len)` then `append` leaves leading zero values |
+| `rust-sumeven` | filters odd numbers instead of even |
+| `rust-safediv` | divides by zero instead of returning `None` |
+| `rust-sumall` | unconstrained generic `T` can't be summed (doesn't compile) |
+| `rust-dedup` | removes from the vector while indexing it (out of bounds) |
+| `ts-sort` | default `sort()` compares numbers as strings |
+| `ts-reduce` | `reduce` without an initial value throws on `[]` |
+| `ts-matrix-alias` | `fill(new Array(...))` makes every row the same array |
+| `ts-closure-var` | `var` loop variable shared by every closure |
+| `swift-parseage` | force-unwraps a failed `Int()` parse |
+| `swift-median` | takes the middle element without sorting |
+| `swift-generic-max` | unconstrained generic `T` can't be compared (doesn't compile) |
+| `swift-mutating` | struct method mutates without `mutating`; caller holds a `let` |
+| `python-mutable-default` | mutable default argument keeps results between calls |
+| `python-strip-domain` | `rstrip(domain)` strips characters, not a suffix |
+| `python-df-columns` | `split(" ")` breaks on the runs of spaces in `df` output |
+| `python-prune-in-place` | removes from a list while iterating it, skipping items |
+| `sh-rotate-spaces` | unquoted paths break on spaces |
+| `sh-disk-threshold` | `[[ $used > $limit ]]` compares as strings |
+| `sh-failed-summary` | counter set inside a pipeline subshell is lost |
+| `sh-comment-out` | `read` without `-r` drops backslashes |
+| `sql-null-compare` | `= NULL` instead of `IS NULL` |
+| `sql-failure-rate` | integer division rounds every rate to 0 |
+| `sql-open-alerts` | a `WHERE` on the left-joined table drops hosts with no alerts |
+| `sql-public-disk` | a join fans out on hosts with two public addresses, double-counting disk |
+
+**hard** — 7 items, one small project per language (6-8 files, tests included). Item set
+`fix-hard@…`, category `hard/<lang>`. The model sees the failing test output, explores with
+read-only tools (`list_files`, `read_file`, `search`), then calls `submit_fix` once with the
+complete new contents of one file. The gate merges that file, restores the tests as written (so
+rewriting a test can't pass), and runs the project's test command: it must exit 0 with every named
+test passing. Explaining the bug takes reading at least two files, and no comment or name points at
+it. Each item ships plausible wrong fixes (usually the obvious patch at the symptom site, which
+breaks another test) that `validate` proves the gate rejects. 24 turns, `max_tokens` 4000.
+
+| Item | Project | Root cause | Tests | Wrong fixes |
+|---|---|---|---|---|
+| `go-kvstore-ttl` | in-memory TTL cache | `Set()` stores `expireAt = now` instead of `now + ttl`, so a `Get()` right after `Set()` misses | 3 | 1 |
+| `python-logrotate` | logrotate-style rotation planner | the config parser hands `maxage N` to a duration parser that reads a bare number as seconds, not days, so every rotated copy is deleted | 12 | 3 |
+| `rust-allowlist` | IPv4 allowlist merged into half-open spans | `Cidr::to_range` returns the block's last address as the exclusive end: each CIDR loses its last address and a /32 is empty | 9 | 3 |
+| `ts-cidr-allowlist` | CIDR allowlist, most specific / latest rule wins | a range's half-open end is passed on as an inclusive last address, so each range also allows the next address and a pinned deny flips to allow | 12 | 3 |
+| `sh-backup-retention` | backup retention pruner (keep daily / weekly / monthly / within) | `[ "$(is_leap "$y")" ]` is true for "0" too, so every year gets a Feb 29 and a keep-within window across a common-year February drops a 7-day-old archive | 13 | 3 |
+| `sql-backup-rpo` | backup-monitoring views (RPO verdicts, maintenance windows) | the maintenance view yields a NULL `host_id` for site windows, so the alert's `NOT IN` returns nothing | 6 | 3 |
+| `swift-engine-pin` | engine-pin OTA updater | `SemVer` declares `Comparable` without its own `==`; the synthesized one compares build metadata, so the updater reinstalls forever | 9 | 4 |
+
+### agentic-multitask — app builds
+
+The model builds a small, real app from a written plan, starting from a scaffold. Tools:
+`list_files`, `read_file`, `write_file`, `edit_file`, `search`, `run_build`, `run_test`,
+`run_shell`. It says `DONE` when finished; the harness then kills whatever it left running and runs
+the gates itself. Item sets `multitask-easy@…` / `multitask-hard@…`, category `<tier>/<go|ts|rust>`.
+correct = every gate passed; score = the fraction that passed. Rows record why the loop stopped
+(`done`, `max_turns`, `gave_up`, an error label) and a per-turn log. 40 turns, `max_tokens` 16000.
+
+| Task | Tier | What it builds | Gates |
+|---|---|---|---|
+| `go_htmx` | easy | Go web app: html/template + HTMX partials, embedded SQLite with a multi-table schema and a recursive-CTE location tree, assets via `go:embed` | build; test (≥1 passing Go test); serves (GET / has the tree and htmx); persists (a POSTed location shows in the fragment, a later GET / and the SQLite file) |
+| `ts_next` | easy | Next.js App Router + Prisma (SQLite), a Zod-validated API route, a server-rendered page | install; typecheck (`tsc --noEmit`); test (≥1 vitest test); serves (GET / 200, valid POST 201, invalid POST 400, GET lists the new item) |
+| `rust_cli` | hard | Rust CLI (tokio + reqwest + quick-xml) that fetches an XML device list behind HTTP Digest auth and prints `id\|name\|ip` | build; test (≥1 passing cargo test); fetches (prints the expected lines and the harness's mock served the XML to an authorized request) |
+
+`ts_next` resolves npm packages as of a fixed date (`npm_config_before`), so every run installs the
+same versions. The `rust_cli` mock checks Digest (MD5, MD5-sess, SHA-256, with or without qop) and
+also accepts Basic, which the plan mentions; the row records which scheme worked.
+
+### sleuth — troubleshooting
+
+The model gets the owner's complaint and a root shell on a broken machine: a throwaway Docker
+container with no network. Tools: `run(command)` (60 s per command) and
+`submit_findings(culprit, root_cause, fix)`, which ends the attempt. 40 turns, `max_tokens` 8000.
+
+- **live** case: a really broken install (flattened image, no break script left behind). The model
+ must fix it; afterwards the case's hidden check must pass.
+- **snapshot** case: a captured host (its files plus canned output for commands that need its
+ kernel) entered with chroot. Diagnose only; the fix is graded by pattern.
+
+correct = three gates. **culprit**: every culprit pattern matches the culprit + root cause, and no
+reject pattern matches the culprit (so a shotgun list of suspects fails). **fix**: live, the check
+passes; snapshot, a fix pattern matches. **seen**: the key evidence was in output the model was
+actually shown before it submitted. Rows also measure how directly it got there: `checks`
+(commands run), `first_key_check` (the command that first showed the evidence), `expert_checks`
+(an expert's shortest path) and `investigate_s`.
+
+| Case | Kind | Complaint | What's actually wrong |
+|---|---|---|---|
+| `cpufreq-driver` (`sleuth/kernel`) | snapshot | Gentoo desktop sluggish after a hand-trimmed kernel rebuild | `CONFIG_X86_INTEL_PSTATE` went out with the trimmed options; acpi-cpufreq plus the powersave governor (chosen for intel_pstate) pins every core at 800 MHz |
+| `ingest-disk` (`sleuth/live`) | live | ingest stopped queueing batches, restarting it didn't help | /srv is full while `du` finds little: rotation deleted metricsd's log while metricsd still holds it open. Fixed by restarting metricsd |
+| `ramsleuth-channel` (`sleuth/code`) | snapshot | RamSleuth 2.4.14 reports a dual-channel kit as single-channel | `collect_from` reads `/sys/firmware/dmi/entries/17-N`, a directory, and `Err(_) => continue` swallows the EISDIR, so the SMBIOS dual-channel override never fires |
+| `ramsleuth-mts` (`sleuth/code`) | snapshot | RamSleuth says DDR4-3600 runs at 7200 MT/s | `decode_mclk` takes Alder Lake's MC_BIOS_REQ ratio × refclk, already the data rate, as the memory clock; the reports double it |
+
+The snapshot cases model a real Gentoo desktop (i5-12600KF, RX 9060 XT). The RamSleuth cases run
+the real source at a pinned commit (v2.4.14), with ground truth from the upstream 2.4.15 fixes.
+Needs a running Docker daemon; each case's image is built once and cached.
+
+### router — small helper models
+
+Four families, each its own item set (`router-<family>@…`), picked with `--families` (default
+all). Every answer is a JSON object or array.
+
+- **route** (26 items, `route/<cat>`): pick one worker for a request from a menu: `local_small`
+ (~4B), `local_large` (~27-35B), `cloud_ollama`, `cloud_claude`, or `clarify` (ask first). Reply
+ `{"target", "reason", "confidence"}`. correct = target in the item's acceptable set with no
+ privacy violation (a local-only request sent to a cloud worker). Rows also record exact match,
+ format fidelity and escalation error (> 0 over-escalated, < 0 under). Categories: trivial 4,
+ simple 4, code 4, reason 2, hard 3, longdoc 2, overflow 1, privacy 3, clarify 3.
+- **orch** (8 items, `orch`): split a compound request ("summarize this error log, write a parser
+ for it, draft a Slack message about the root cause") into steps, each with a kind (chat,
+ extract, classify, summarize, math, code, debug, reason, longdoc, draft_message, web_search), a
+ worker and dependencies. correct = every required kind present, every step on a capable worker,
+ every required ordering reachable, no privacy violation.
+- **judge** (32 items): a small model grading computing work. 24 **verdict** items
+ (`judge/<cat>`): does this candidate meet the task, pass or fail? 12 pass / 12 fail; the fails
+ are near-misses (an off-by-one negative slice, `find -mtime -7`, `grep -c` under `set -e`,
+ `COUNT(bool)`, a join missing its key, an invented log event, `proxy_pass` without a URI, cron's
+ day-of-month OR day-of-week rule), the passes include terse or unusual correct answers. Reports
+ false-pass and false-fail rates. 8 **pairwise** items (`pairwise/<cat>`): which of two
+ candidates is better, asked in both orders (`<id>/ab`, `<id>/ba`) for position bias. Categories:
+ code (Python, Go, Rust) 9, shell 7, sql 4, logs 4, config 4, answer 4. Code, shell and SQL gold
+ labels were verified by running them.
+- **rerank** (16 items, `rerank/<cat>`): order 7-8 candidates by relevance to a query,
+ `{"ranking": [ids]}`. correct = the one top-grade candidate ranked first; rows add MRR and NDCG@5
+ over graded relevance (0-3). Each item has hard negatives that share the query's keywords and a
+ relevant candidate with little keyword overlap. Categories: code 4, logs 3, docs 3, commands 3,
+ errors 3.
+
+### needle — long-context retrieval
+
+A haystack of neutral office-log filler hides an access code; the model must return it. An item is
+(depth, position, seed, variant), category `needle/<depth>/<variant>` (e.g. `needle/16k/decoy`).
+
+- **plain**: one code for one place.
+- **decoy**: an old, rotated-out code for the same place plus the current one; asks for the current.
+- **multikey**: five places with codes at five positions; asks for one.
+
+correct = the gold code is in the answer content and no decoy or other-key code is. Default run:
+depths 1k, 4k, 16k, 32k, 64k tokens × positions 0.1 / 0.5 / 0.9 × 3 variants × 1 seed = 45 items.
+Depth is built at an estimated 4.4 chars per token (`--cpt`); the server's `prompt_tokens` is
+recorded next to it, so a different tokenizer shows. Prefill speed per depth is averaged over
+uncached rows (llama-server lanes turn the prompt cache off).
+
+### loop-battery — runaway reasoning
+
+Five prompts built to provoke over-thinking, 8 samples each by default (category `loop/<probe>`;
+temperature 0.6, `max_tokens` 16000). Rows record whether the answer ran to the token cap, the
+highest repeat count of any 10-word run (a hard loop scores high), and counts of re-derivation
+markers ("wait", "hmm", "let me reconsider", …) in the reasoning. correct = under the cap and the
+answer passes a deliberately loose acceptance rule (a floor for "didn't just comply", not a grader).
+
+| Probe | The trap | Accepted |
+|---|---|---|
+| `self-ref-wordcount` | state your answer's own word count | the stated number matches the word count |
+| `underdetermined-ages` | product-36 ages puzzle, sum never given | ages 2, 2, 9, or says information is missing |
+| `prove-false` | "prove every odd integer > 2 is prime" | says it's false or gives a counterexample |
+| `conflicting-opt` | the one language optimal on every axis | says there isn't one / trade-offs |
+| `ambiguous-pronoun-math` | fruit prices the last sentence contradicts | flags the contradiction, or answers 1.40 |
+
+### reasoning — computing knowledge
+
+60 MMLU-Pro computer-science questions (TIGER-Lab/MMLU-Pro test split, MIT), ten options A-J,
+category `cs`, item ids `mmlu-pro-cs/<question_id>`. Run `fetch` once first: it downloads the set,
+picks the items deterministically (first 60 by `sha256("mmlu-pro-cs:<question_id>")`) and caches
+them (gitignored); a committed manifest pins a hash per item, and `run` refuses a drifted cache.
+Graded on the last `ANSWER: <letter>` in the content, never the reasoning. Details:
+[bench/data/reasoning/README.md](bench/data/reasoning/README.md).
+
+### conformance — preflight (not a bench)
+
+Rules out non-model problems before a run. FAIL = the lane's settings are wrong or the pipeline
+lost or mangled the answer (blocks the run, exit 1); WARN = the model got a probe wrong but the
+answer arrived intact (recorded only; `report` lists each lane's latest WARNs). Runs automatically before every `run`, cached 24 h per lane
+settings in `bench/results/_preflight/`; `--resume` never re-checks, `BENCH_PREFLIGHT=0` skips.
+`--checks` picks groups by short name (`--list` shows them).
+
+| Check (`--checks` group) | What it verifies |
+|---|---|
+| `sampler_card` (sampler) | no request: the sampler the lane sends matches its model card in `lanes/cards.json`, unless `sampler_overrides` records the value and why |
+| `basic_reply` (basic) | a trivial question gets non-empty content |
+| `max_tokens` (maxtok) | `max_tokens=64` is honoured |
+| `reasoning_field` / `no_reasoning` (thinking) | thinking on: which field carries the reasoning (FAIL if none); thinking off: none leaks |
+| `system_messages` (system) | two system messages + a user message succeed |
+| `tool_roundtrip` (tools) | calls a tool with valid JSON arguments, then answers after the result |
+| `tc-*` (toolcalls) | 8 probes: a native call, a plain-text `<tool_call>` with no tools declared, bare JSON output, a question that needs no tool, two parallel calls, picking one of three tools, nested JSON, an argument derived from wording ("two and a half minutes"). FAIL when a call came back as text or the provider ate the output; WARN when a well-formed answer is wrong |
+| `think_tags` (think_tags) | no `<think>` tags left in the content, none unclosed, the answer not stuck in the reasoning |
+| `provider_pin` (provider) | OpenRouter lanes: every response came from the pinned provider |
+| `determinism` (determinism) | INFO, not in the preflight: two temperature-0 runs identical? |
+| `server_snapshot` (server) | INFO, not in the preflight: n_ctx, slots, model ids |
+
+### report and oracle — reading results
+
+**report** builds a capability profile from stored runs: rows are (instrument, category), columns
+are lanes. A cell is the mean over items of each item's mean score (or pass rate), with a 95% CI
+over items (Wilson when every item is pass/fail, else bootstrap). Sections: the profile; paired deltas against `--ref LANE` on shared
+items (with McNemar; default `claude-opus`, so deltas appear only where Opus has runs: the agentic
+instruments); preflight (each lane's latest conformance run, with its WARN and FAIL checks
+named; conformance never enters the profile); status per lane (truncation and infra rates); cost
+and speed; provenance.
+Only complete runs count unless `--include-incomplete`. Runs of one item set pool; two versions of
+one item set never do (they become separate columns, with a warning). `--out` writes markdown,
+`--json` / `--csv` the numbers.
+
+**oracle** labels each item with the lanes that pass it (pass rate ≥ `--theta`, default 0.67) and
+the cheapest passing lane in `--order` (or, with `--lambda-usd`, by measured time plus cost);
+`--simulate` replays routing policies over those labels.
+
## Configuration
-Copy `.env.example` to `.env` and edit. Env vars win over `.env`, so you
-can override per-run (see the last example above).
+**Lanes.** `LANE=<id>` loads `lanes/<id>.json`, which owns the endpoint, model id, the
+full sampler, `max_tokens`, thinking on/off and the no-think mechanism, OpenRouter provider pinning,
+auth (`keychain_service` or `env`, never a literal key), the spend cap, and provenance (quant,
+runtime, ctx, KV). The client merges the lane into every request, strips reasoning from history and
+repairs non-JSON tool arguments before sending, retries 429/5xx-transient with backoff, and labels
+failures (`http_<code>`, `timeout`, `oom`, `ctx_overflow`, `budget_stop`, …) so infra problems are
+never scored as wrong answers. Paid lanes go through `bench/results/_ledger/<name>.jsonl` with a
+spend cap; it is a soft cap (concurrent calls can each pass the check and overshoot it). `LANE` is
+required for anything that calls a model; see `bench/core/lane.py` for every key. Each lane names its
+model card (`card`, a key of `lanes/cards.json`, which pins the card revision and its recommended
+sampler per thinking mode); `conformance` FAILs a lane whose sampler differs unless
+`sampler_overrides` records the sent value and a reason. A changed sampler is a new lane id: reports
+group by lane id.
+
+**Claude reference.** `LANE=claude-opus` (`"runner": "claude-cli"`) runs the agentic instruments
+(sleuth, agentic-*) on headless `claude -p` on the subscription: the instrument's own tools are
+served to Claude over MCP (`bench/core/claude_cli.py` + `claude_mcp.py`) and run in the bench
+process, so gates and rows are the same as for an HTTP lane. No built-in tools, settings, skills or
+CLAUDE.md; Claude Code sets its own sampler. Other instruments refuse a runner lane.
+
+**Environment** (copy `.env.example` to `.env`; env vars win over `.env`):
| Var | Default | What |
|---|---|---|
-| `ENDPOINT` | `http://127.0.0.1:1234/v1/chat/completions` | OpenAI-compat chat URL |
-| `MODEL` | `local` | model id |
-| `API_KEY` | (blank) | bearer token (if endpoint needs auth) |
-| `MAX_TOKENS` | `8000` | per-turn generation cap |
-| `TEMPERATURE` | `0` | sampling temp (0 = greedy, recommended) |
-| `MAX_TURNS` | `40` | agentic loop cap |
-| `HTTP_TIMEOUT` | `900` | per-request wall timeout (s) |
-| `NOTHINK` | (blank) | `1` = suppress reasoning via empty think prefill |
+| `LANE` | (none) | lane id (`lanes/<id>.json`) or path to a lane file |
+| `MAX_TURNS` | per instrument (40; agentic-fix hard 24) | default of the agentic `--max-turns` |
+| `BENCH_PREFLIGHT` | `1` | `0` skips the automatic preflight before a run |
+| `BUILD_TIMEOUT` / `TEST_TIMEOUT` / `SHELL_TIMEOUT` | per language (Go 180/180/60, Rust 600/600/60, TS 120/120/300) | agentic tool + gate timeouts (s) |
+| `LEDGER_CAP_USD` | lane `cost.cap_usd` | override the spend cap |
+| `BENCH_RESULTS_DIR` / `BENCH_WORK_DIR` | `bench/results` / `work` | where runs and work dirs go |
### Compatible endpoints
@@ -81,64 +332,85 @@ Anything that speaks OpenAI `/v1/chat/completions`:
- **Ollama Cloud** — `https://api.ollama-cloud.com/v1/chat/completions`
- **OpenAI** — `https://api.openai.com/v1/chat/completions`
-Tool-calling tasks use the OpenAI `tools` param. The XML/JSON tool-calling
-tasks use freeform text, so they work even on backends without native
-function-calling.
+The preflight's tool-call probes use the OpenAI `tools` param; its XML/JSON probes use freeform
+text, so they work even on backends without native function-calling.
## Requirements
-- Python 3.10+
+- Python 3.9+
- Language toolchains for the tasks you want to run:
| Toolchain | Needed for |
|---|---|
-| Go 1.22+ | agentic-fix, agentic-build, go_htmx, go bug-fixes |
-| Rust 1.70+ | rust_cli, rust bug-fixes |
-| bun 1.0+ | ts bug-fixes |
+| Go 1.22+ | go fixes, go_htmx |
+| Rust 1.70+ (cargo) | rust fixes, rust_cli |
+| bun 1.0+ | ts fixes |
| Node.js 18+ + npm | ts_next |
-| Swift / Xcode | swift bug-fixes (macOS only; skipped gracefully elsewhere) |
+| python3, bash, sqlite3 | python / shell / sql fixes (shell items stay bash-3.2-safe) |
+| Swift / Xcode | swift fixes (macOS only; skipped gracefully elsewhere) |
+| Docker | sleuth (a running daemon; first build pulls the pinned base images) |
No Python packages needed — everything uses the stdlib.
## Adding your own tasks
-**Coding suite** — add a dict to `BUGFIX_T1` / `BUGFIX_T2` / `TOOLCALL` in
-`bench/tasks/coding_suite.py`. Bug-fix tasks need: `id`, `lang`, `symptom`,
-`buggy`, `fix`, `test`. `validate` proves buggy fails + fix passes.
+**Bug fix, easy** — add a dict to `ITEMS` in `bench/tasks/fix_easy/<lang>.py` (fields in that
+package's `__init__.py`). `validate --tier easy` proves buggy fails + fix passes. **Bug fix, hard** —
+add a module to `bench/tasks/fix_hard/` (contract in its `__init__.py`): a small project, the hidden
+tests, a one-file FIX and plausible WRONG fixes; `validate --tier hard` proves the gate accepts the fix
+and rejects the bug, a test rewrite and every WRONG. Any edit forks that tier's item set.
-**Multitask gauntlet** — drop a `.py` file in `bench/tasks/multitask/`
-exposing `TASK_NAME`, `PLAN`, `STARTER`, `REFERENCE`, `validate(work_dir)`,
-`gates(work_dir)`. Auto-discovered. See `go_htmx.py` for the shape.
+**Multitask gauntlet** — drop a `.py` file in `bench/tasks/multitask/` exposing what
+`bench/tasks/multitask/__init__.py` lists (`TASK_NAME`, `CATEGORY`, `PLAN`, `STARTER`,
+`REFERENCE`, `TOOLSET`, `GATES`, `gates(ws, port)`, ...). Auto-discovered. See `go_htmx.py`.
+
+**Sleuth case** — add a `.py` file in `bench/tasks/sleuth_cases/` exposing `CASES` (fields in
+that package's `__init__.py`). A live case is a Dockerfile for a really broken box plus a hidden
+`check`; a snapshot case is files + canned command output via `sleuth.snapshot()`. Never put the
+cause in the complaint or leave the break script in the image. `validate` proves the expert path
+shows the evidence, the reference passes and every wrong answer fails.
**New instrument** — add a module under `bench/tasks/` with a `main()`
-function, register it in `INSTRUMENTS` in `bench.py`. Import from
-`bench.core` (`client`, `runners`, `tools`, `reporting`).
+function, register it in `INSTRUMENTS` in `bench.py`, and follow [CONTRACT.md](CONTRACT.md)
+(`bench.core` `lane`, `client`, `results`).
## Project layout
+File by file; tests are named after the module they cover (`tests/test_<module>.py`).
+
```
llm-bench/
├── bench.py # CLI entry point
-├── .env.example # config template
+├── CONTRACT.md # rules every instrument follows
+├── LICENSE.md # the Slop License
+├── .env.example # LANE + optional knobs
+├── lanes/ # lane profiles (*.json) + cards.json (model-card samplers)
+├── tests/ # offline tests (MockServer) — python3 -m unittest discover -s tests
├── bench/
-│ ├── core/ # client, runners, tools, reporting
+│ ├── core/ # lane, client, results, ledger, stats, mockserver, runners, tools
+│ ├── data/reasoning/ # mmlu-pro-cs manifest (cache/ is fetched, gitignored)
+│ ├── results/ # generated (gitignored)
│ └── tasks/ # instruments (one per file)
-│ ├── coding_suite.py
-│ ├── agentic_fix.py
-│ ├── agentic_build.py
-│ ├── agentic_multitask.py
-│ ├── router.py
+│ ├── conformance.py # per-lane preflight (+ toolcall_probes.py)
+│ ├── reasoning.py # MMLU-Pro computer science
+│ ├── report.py # capability profile across lanes
+│ ├── oracle.py # per-item oracle lane labels + policy simulation
+│ ├── agentic_fix.py # bug fixes, both tiers
+│ ├── fix_easy/ # easy-tier items, one file per language
+│ ├── fix_hard/ # hard-tier items, one project per file
+│ ├── agentic_multitask.py # app builds + the agentic harness
+│ ├── multitask/ # app-build tasks (auto-discovered): go_htmx, ts_next, rust_cli
+│ ├── sleuth.py # troubleshooting in throwaway containers
+│ ├── sleuth_cases/ # sleuth cases (auto-discovered; _* files are shared helpers)
+│ ├── router.py # route / orch items + scoring
+│ ├── router_sets.py # judge / rerank items
│ ├── needle.py
-│ ├── loop_battery.py
-│ ├── no_think.py
-│ └── multitask/ # gauntlet task modules (auto-discovered)
-│ ├── go_htmx.py
-│ ├── rust_cli.py
-│ └── ts_next.py
-├── results/ # generated (gitignored)
+│ └── loop_battery.py
└── work/ # generated (gitignored)
```
## License
-MIT. See LICENSE.
\ No newline at end of file
+Released under the Slop License — see [LICENSE.md](LICENSE.md).
+
+MIT.
\ No newline at end of file
diff --git a/bench.py b/bench.py
index 1f34ebd..e509e4d 100755
--- a/bench.py
+++ b/bench.py
@@ -1,41 +1,11 @@
#!/usr/bin/env python3
-"""
-llm-bench — a local LLM coding-model benchmark suite.
-
-Unified CLI entry point. Point it at any OpenAI-compatible endpoint via .env
-(or env vars), pick an instrument, and run. Instruments live under
-bench/tasks/ as importable modules.
-
-Usage:
- python bench.py <instrument> <command> [args...]
-
- python bench.py coding-suite validate
- python bench.py coding-suite run
- python bench.py agentic-fix validate
- python bench.py agentic-fix run
- python bench.py agentic-build validate
- python bench.py agentic-build run
- python bench.py agentic-multitask validate go_htmx
- python bench.py agentic-multitask run go_htmx
- python bench.py agentic-multitask cohort go_htmx rust_cli ts_next
- python bench.py router validate
- python bench.py router run
- python bench.py needle run --depths 1000,16000
- python bench.py loop-battery run
- python bench.py no-think run
+"""llm-bench CLI: python3 bench.py <instrument> <command> [args...] (each takes --help)
-Config (via .env in the repo root, or env vars):
- ENDPOINT OpenAI chat-completions URL
- MODEL model id
- API_KEY bearer token (if your endpoint needs auth)
- MAX_TOKENS per-turn generation cap
- TEMPERATURE sampling temperature
- MAX_TURNS agentic loop cap (for multi-turn instruments)
- HTTP_TIMEOUT per-request wall timeout
- NOTHINK "1" = suppress reasoning via empty think prefill
-
-See .env.example for all options.
+LANE=<id> selects lanes/<id>.json (endpoint, model, sampler, max_tokens, thinking on/off, auth,
+cost cap, provenance); see bench/core/lane.py and CONTRACT.md. Values in .env fill in what the
+environment does not set.
"""
+import importlib
import os
import sys
@@ -67,25 +37,27 @@ def _load_dotenv():
# Instrument name -> module path (under bench/tasks/)
INSTRUMENTS = {
- "coding-suite": "bench.tasks.coding_suite",
- "agentic-fix": "bench.tasks.agentic_fix",
- "agentic-build": "bench.tasks.agentic_build",
- "agentic-multitask": "bench.tasks.agentic_multitask",
- "router": "bench.tasks.router",
+ "agentic-fix": "bench.tasks.agentic_fix", # bug fixes: easy single-turn / hard cross-file
+ "agentic-multitask": "bench.tasks.agentic_multitask", # app builds: easy Go+TS / hard Rust
+ "router": "bench.tasks.router", # small helpers: route / orch / judge / rerank
"needle": "bench.tasks.needle",
"loop-battery": "bench.tasks.loop_battery",
- "no-think": "bench.tasks.no_think",
+ "reasoning": "bench.tasks.reasoning", # computing knowledge: MMLU-Pro computer science
+ "sleuth": "bench.tasks.sleuth", # troubleshoot broken hosts in containers
+ "conformance": "bench.tasks.conformance", # per-lane preflight (run before any bench)
+ "report": "bench.tasks.report", # capability profile across lanes
+ "oracle": "bench.tasks.oracle", # per-item oracle lane labels + policy sims
}
def main():
_load_dotenv()
- if len(sys.argv) < 2:
+ if len(sys.argv) < 2 or sys.argv[1] in ("-h", "--help"):
print(__doc__)
print("\nAvailable instruments:")
for name in sorted(INSTRUMENTS):
print(f" {name}")
- sys.exit(1)
+ sys.exit(0 if len(sys.argv) > 1 else 1)
instrument = sys.argv[1]
if instrument not in INSTRUMENTS:
@@ -99,16 +71,14 @@ def main():
if here not in sys.path:
sys.path.insert(0, here)
- mod = __import__(INSTRUMENTS[instrument], fromlist=["__main__"])
+ from bench.core.lane import LaneError
+ mod = importlib.import_module(INSTRUMENTS[instrument])
# Strip the instrument name from argv so the module sees its own args.
sys.argv = [INSTRUMENTS[instrument]] + sys.argv[2:]
- # Each instrument module has a main() that parses sys.argv for its
- # subcommand (validate / run / report / etc).
- if hasattr(mod, "main"):
+ try:
mod.main()
- else:
- print(f"ERROR: instrument {instrument} has no main()")
- sys.exit(1)
+ except LaneError as e:
+ sys.exit(f"ERROR: {e}")
if __name__ == "__main__":
diff --git a/bench/core/__init__.py b/bench/core/__init__.py
index cf553d6..e69de29 100644
--- a/bench/core/__init__.py
+++ b/bench/core/__init__.py
@@ -1,7 +0,0 @@
-"""Package init — exposes the core modules."""
-from . import client
-from . import runners
-from . import tools
-from . import reporting
-
-__all__ = ["client", "runners", "tools", "reporting"]
\ No newline at end of file
diff --git a/bench/core/claude_cli.py b/bench/core/claude_cli.py
new file mode 100644
index 0000000..4a900ab
--- /dev/null
+++ b/bench/core/claude_cli.py
@@ -0,0 +1,308 @@
+"""Claude reference runner: one agentic attempt driven by headless `claude -p` (the subscription,
+not the API) instead of the HTTP tool loop. Same tools, same results: agent_loop() here takes and
+returns what tools.agent_loop does, so run_item, the gates and the rows are unchanged.
+
+The instrument's toolset is served to Claude over MCP (claude_mcp.py relays each call back to a
+bridge in this process, which runs it on the attempt's Workspace through tools.run_tool, with the
+same truncation). Claude gets no built-in tools (--tools ""), no MCP server but ours
+(--strict-mcp-config), no settings, skills or slash commands, and runs from an empty temp dir
+outside any repo, so no CLAUDE.md or project memory. What it still sees beyond a local lane's
+prompt: Claude Code's one-line SDK preamble, its environment block (temp cwd, darwin, date) and
+the account e-mail reminder (captured 2026-10-12, CLI 2.1.296). Claude Code sets the sampler; the
+lane records model and effort.
+
+The system prompt (the task plan, ports and paths included) goes in through --system-prompt-file,
+never argv: a model's `pkill -f cmd/server` matched claude's own command line and SIGTERMed the
+session (Opus low, go_htmx, 2026-10-12).
+
+One process per attempt, stream-json in and out: a query that ends without the stop tool is a
+no-tool turn (done word / nudge / give up, as in tools.agent_loop). Per-turn tokens come from
+the message_delta events (exact output + thinking tokens). The process is killed right after the
+stop tool's result or when turn max_turns + 1 starts, so turn counts match the HTTP loop.
+
+Lane keys (runner "claude-cli"): model (--model), effort (--effort, optional), http_timeout
+(seconds per attempt), max_concurrency.
+"""
+import json
+import os
+import secrets
+import shutil
+import signal
+import subprocess
+import tempfile
+import threading
+import time
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+
+from bench.core import client, tools
+
+RUNNER = "claude-cli"
+CLAUDE = os.environ.get("CLAUDE_BIN", "claude")
+MCP_SERVER = os.path.join(os.path.dirname(os.path.abspath(__file__)), "claude_mcp.py")
+SERVER = "bench" # MCP server name: Claude sees mcp__bench__<tool>
+ENDED = "ERROR: the session has ended; do not call more tools."
+
+
+def is_claude(lane):
+ return (lane.raw.get("runner") if lane is not None else None) == RUNNER
+
+
+class Bridge:
+ """The tools endpoint claude_mcp.py relays to. Calls run one at a time, in arrival order."""
+
+ def __init__(self, ws, toolset, trunc_fmt, result_cap):
+ self.ws, self.toolset = ws, toolset
+ self.trunc_fmt, self.result_cap = trunc_fmt, result_cap
+ self.calls, self.stopped, self.infra = [], False, None
+ self.token = secrets.token_hex(16)
+ self._lock = threading.Lock()
+ bridge = self
+
+ class Handler(BaseHTTPRequestHandler):
+ def log_message(self, *a):
+ pass
+
+ def _send(self, code, obj):
+ body = json.dumps(obj).encode()
+ self.send_response(code)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def do_GET(self):
+ if self.headers.get("X-Bench-Token") != bridge.token:
+ return self._send(403, {"error": "bad token"})
+ self._send(200, bridge.tool_list())
+
+ def do_POST(self):
+ if self.headers.get("X-Bench-Token") != bridge.token:
+ return self._send(403, {"error": "bad token"})
+ req = json.loads(self.rfile.read(int(self.headers.get("Content-Length") or 0)))
+ self._send(200, {"text": bridge.call(req.get("name") or "", req.get("arguments") or {})})
+
+ self.srv = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
+ self.url = "http://127.0.0.1:%d" % self.srv.server_port
+ threading.Thread(target=self.srv.serve_forever, daemon=True).start()
+
+ def tool_list(self):
+ return [{"name": f["function"]["name"], "description": f["function"].get("description", ""),
+ "inputSchema": f["function"].get("parameters") or {"type": "object", "properties": {}}}
+ for f in self.toolset.schema]
+
+ def call(self, name, args):
+ with self._lock:
+ rec = {"name": name, "args_head": json.dumps(args)[:200], "executed": False}
+ if self.stopped or self.infra is not None:
+ result = ENDED
+ else:
+ try:
+ result, stop = tools.run_tool(self.ws, self.toolset, name, args)
+ rec["executed"] = True
+ self.stopped = stop
+ except tools.InfraError as e:
+ self.infra = e
+ result = "ERROR: the machine is unavailable"
+ if self.trunc_fmt is not None and len(result) > self.result_cap:
+ result = result[:self.result_cap] + self.trunc_fmt.format(n=len(result))
+ rec.update(result_len=len(result), result_head=result[:200])
+ self.calls.append(rec)
+ return result
+
+ def close(self):
+ self.srv.shutdown()
+ self.srv.server_close()
+
+
+def command(lane, system_file, cfg, toolset):
+ allowed = ["mcp__%s__%s" % (SERVER, f["function"]["name"]) for f in toolset.schema]
+ cmd = [CLAUDE, "-p", "--output-format", "stream-json", "--input-format", "stream-json",
+ "--verbose", "--include-partial-messages", "--model", lane.model,
+ "--setting-sources", "", "--disable-slash-commands", "--no-session-persistence",
+ "--tools", "", "--mcp-config", cfg, "--strict-mcp-config", "--permission-mode", "dontAsk",
+ "--allowedTools", *allowed, "--system-prompt-file", system_file]
+ if lane.raw.get("effort"):
+ cmd += ["--effort", lane.raw["effort"]]
+ return cmd
+
+
+def _user(text):
+ return json.dumps({"type": "user", "message": {"role": "user", "content": text}}) + "\n"
+
+
+def agent_loop(ws, messages, toolset, *, max_turns, item_id=None, run_id=None, lane=None,
+ done_word=True, give_up_after=None, nudge="", trunc_fmt="\n...[truncated, {n} total]",
+ result_cap=tools.RESULT_CAP, log=print, tag="", **_http_only):
+ """tools.agent_loop's contract on claude -p. messages = [system, user]; max_tokens and
+ temperature are the HTTP loop's and do not apply."""
+ turns = []
+ out = {"stop_reason": "max_turns", "turns_used": 0, "turns": turns, "error": None,
+ "error_dt": None, "harness_error": None, "last_resp": None, "row_extra": {}}
+ system = "\n\n".join(m["content"] for m in messages if m["role"] == "system")
+ user = "\n\n".join(m["content"] for m in messages if m["role"] == "user")
+ bridge = Bridge(ws, toolset, trunc_fmt, result_cap)
+ tmp = tempfile.mkdtemp(prefix="llm-bench-claude-")
+ cfg = os.path.join(tmp, "mcp.json")
+ with open(cfg, "w") as f:
+ json.dump({"mcpServers": {SERVER: {"command": "/usr/bin/python3", "args": ["-I", MCP_SERVER],
+ "env": {"BENCH_BRIDGE_URL": bridge.url,
+ "BENCH_BRIDGE_TOKEN": bridge.token}}}}, f)
+ with open(os.path.join(tmp, "system.txt"), "w") as f:
+ f.write(system)
+ os.makedirs(os.path.join(tmp, "cwd"))
+ env = dict(os.environ, MCP_TOOL_TIMEOUT="1800000", MCP_TIMEOUT="60000", DISABLE_AUTOUPDATER="1")
+ t0 = time.time()
+ proc, watchdog, killed = None, None, {"why": None}
+
+ def kill(why):
+ if killed["why"] is None:
+ killed["why"] = why
+ try:
+ os.killpg(proc.pid, signal.SIGKILL)
+ except (ProcessLookupError, PermissionError):
+ pass
+
+ try:
+ with open(os.path.join(tmp, "stderr"), "w") as err:
+ proc = subprocess.Popen(command(lane, os.path.join(tmp, "system.txt"), cfg, toolset), cwd=os.path.join(tmp, "cwd"), env=env,
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=err,
+ text=True, start_new_session=True)
+ watchdog = threading.Timer(lane.http_timeout, kill, ("timeout",))
+ watchdog.daemon = True
+ watchdog.start()
+ proc.stdin.write(_user(user))
+ proc.stdin.flush()
+ cur, t_turn, streak, tools_since_user, n_results = None, time.time(), 0, False, 0
+ for line in proc.stdout:
+ try:
+ ev = json.loads(line)
+ except ValueError:
+ continue
+ typ = ev.get("type")
+ if typ == "system" and ev.get("subtype") == "init":
+ out["row_extra"] = {"claude_model": ev.get("model"),
+ "claude_version": ev.get("claude_code_version")}
+ if not any(s.get("name") == SERVER and s.get("status") == "connected"
+ for s in ev.get("mcp_servers") or ()):
+ raise client.CallError("conn", "MCP tool bridge not connected: %s"
+ % ev.get("mcp_servers"))
+ elif typ == "stream_event":
+ e = ev.get("event") or {}
+ if e.get("type") == "message_start":
+ if len(turns) == max_turns:
+ kill("max_turns")
+ break
+ cur = {"turn": len(turns) + 1, "id": e["message"].get("id"), "tools": [],
+ "tool_names": [], "text": "", "t_start": t_turn}
+ turns.append(cur)
+ out["turns_used"] = cur["turn"]
+ elif e.get("type") == "message_delta" and cur is not None:
+ u = e.get("usage") or {}
+ cur.update(prompt_tokens=sum(u.get(k) or 0 for k in (
+ "input_tokens", "cache_read_input_tokens", "cache_creation_input_tokens")),
+ completion_tokens=u.get("output_tokens") or 0,
+ reasoning_tokens=(u.get("output_tokens_details") or {}).get("thinking_tokens"),
+ finish=(e.get("delta") or {}).get("stop_reason"))
+ elif e.get("type") == "message_stop" and cur is not None:
+ cur["wall_s"] = round(time.time() - cur.pop("t_start"), 2)
+ cur["cut_off"] = cur.get("finish") == "max_tokens"
+ log(f" {tag}turn {cur['turn']:2d}: {cur['wall_s']:6.1f}s "
+ f"ptok={cur.get('prompt_tokens', 0):6d} ctok={cur.get('completion_tokens', 0):5d} "
+ f"rtok={cur.get('reasoning_tokens') or 0:5d} fr={str(cur.get('finish')):10s} "
+ f"tools=[{','.join(cur['tool_names']) or '(no tool call)'}]")
+ elif typ == "assistant" and cur is not None:
+ for b in (ev.get("message") or {}).get("content") or ():
+ if b.get("type") == "tool_use":
+ cur["tool_names"].append(str(b.get("name", "")).replace(f"mcp__{SERVER}__", ""))
+ tools_since_user = True
+ elif b.get("type") == "text":
+ cur["text"] += b.get("text") or ""
+ elif typ == "user" and any(isinstance(b, dict) and b.get("type") == "tool_result"
+ for b in (ev.get("message") or {}).get("content") or ()):
+ t_turn = time.time() # tool results are back: the next turn's clock starts
+ if bridge.stopped or bridge.infra is not None:
+ kill("stop")
+ break
+ elif typ == "result":
+ n_results += 1
+ if ev.get("is_error"):
+ raise client.CallError("http", str(ev.get("result") or ev.get("subtype"))[:500],
+ code=429 if "limit" in str(ev.get("result")).lower() else 502)
+ if bridge.stopped:
+ break
+ text = str(ev.get("result") or "")
+ if done_word and tools.said_done(text):
+ if turns:
+ turns[-1]["done"] = True
+ out["stop_reason"] = "done"
+ break
+ streak = 1 if tools_since_user else streak + 1
+ tools_since_user = False
+ if give_up_after and streak >= give_up_after:
+ log(f" {tag}-> giving up after {streak} no-tool turns")
+ out["stop_reason"] = "gave_up"
+ break
+ if turns:
+ turns[-1]["nudged"] = True
+ t_turn = time.time()
+ proc.stdin.write(_user(nudge))
+ proc.stdin.flush()
+ if bridge.infra is not None:
+ raise bridge.infra
+ if bridge.stopped:
+ out["stop_reason"] = "done"
+ if turns:
+ turns[-1]["done"] = True
+ elif killed["why"] == "timeout":
+ raise client.CallError("timeout", "claude -p passed http_timeout=%ss" % lane.http_timeout)
+ elif killed["why"] is None and out["stop_reason"] == "max_turns" and len(turns) < max_turns:
+ proc.wait(30)
+ with open(os.path.join(tmp, "stderr")) as f:
+ tail = f.read()[-400:]
+ raise client.CallError("conn", "claude -p ended early (rc=%s, %d results): %s"
+ % (proc.returncode, n_results, tail))
+ except client.CallError as e:
+ log(f" {tag}CLAUDE ERROR {e.label()}: {str(e)[:200]}")
+ out.update(stop_reason=e.label(), error=e, error_dt=time.time() - t0)
+ except Exception as e: # noqa: BLE001 — harness bug or InfraError: keep the turns logged so far
+ log(f" {tag}HARNESS ERROR in the claude loop: {e!r}")
+ out.update(stop_reason="harness_error", harness_error=e)
+ finally:
+ if watchdog is not None:
+ watchdog.cancel()
+ if proc is not None:
+ if proc.poll() is None:
+ kill(killed["why"] or "done")
+ proc.wait(30)
+ for f in (proc.stdin, proc.stdout):
+ try:
+ f.close()
+ except OSError:
+ pass
+ bridge.close()
+ shutil.rmtree(tmp, ignore_errors=True)
+
+ calls = iter(bridge.calls)
+ for t in turns:
+ t.pop("t_start", None)
+ t.pop("id", None)
+ t["tools"] = [next(calls, {"name": n, "executed": False}) for n in t.pop("tool_names")]
+ t["n_tool_calls"] = len(t["tools"])
+ t["content_head"] = t.pop("text")[:200]
+ real = [t for t in turns if "wall_s" in t]
+ rts = [t["reasoning_tokens"] for t in real if t.get("reasoning_tokens") is not None]
+ finish_counts = {}
+ for t in real:
+ finish_counts[str(t.get("finish"))] = finish_counts.get(str(t.get("finish")), 0) + 1
+ out.update({
+ "cut_off_turns": sum(1 for t in real if t.get("cut_off")),
+ "prompt_tokens": sum(t.get("prompt_tokens", 0) for t in real),
+ "completion_tokens": sum(t.get("completion_tokens", 0) for t in real),
+ "reasoning_tokens": sum(rts) if rts else None,
+ "peak_prompt_tokens": max((t.get("prompt_tokens", 0) for t in real), default=0),
+ "cost_usd": None, # subscription
+ "finish_counts": finish_counts,
+ "tool_calls": sum(len(t["tools"]) for t in real),
+ "model_s": round(sum(t["wall_s"] for t in real), 2),
+ })
+ return out
diff --git a/bench/core/claude_mcp.py b/bench/core/claude_mcp.py
new file mode 100644
index 0000000..3b82198
--- /dev/null
+++ b/bench/core/claude_mcp.py
@@ -0,0 +1,61 @@
+"""Stdio MCP server that relays an instrument's tools to the bench process (claude_cli.py).
+
+claude -p starts it from --mcp-config. It lists the tools the bridge serves and forwards every
+call to it, so the tools run in the bench process on the attempt's Workspace, exactly as they do
+for HTTP lanes. Stdlib only, newline-delimited JSON-RPC 2.0 on stdin/stdout.
+
+ env BENCH_BRIDGE_URL http://127.0.0.1:<port> of the attempt's bridge
+ BENCH_BRIDGE_TOKEN shared secret, sent as X-Bench-Token
+"""
+import json
+import os
+import sys
+import urllib.request
+
+URL = os.environ.get("BENCH_BRIDGE_URL", "")
+TOKEN = os.environ.get("BENCH_BRIDGE_TOKEN", "")
+
+
+def bridge(path, payload=None):
+ data = None if payload is None else json.dumps(payload).encode()
+ req = urllib.request.Request(URL + path, data=data, headers={
+ "X-Bench-Token": TOKEN, "Content-Type": "application/json"})
+ with urllib.request.urlopen(req, timeout=3600) as r:
+ return json.load(r)
+
+
+def handle(method, params):
+ if method == "initialize":
+ return {"protocolVersion": params.get("protocolVersion") or "2025-06-18",
+ "capabilities": {"tools": {"listChanged": False}},
+ "serverInfo": {"name": "llm-bench", "version": "1"}}
+ if method == "tools/list":
+ return {"tools": bridge("/tools")}
+ if method == "tools/call":
+ r = bridge("/call", {"name": params.get("name"), "arguments": params.get("arguments") or {}})
+ return {"content": [{"type": "text", "text": r["text"]}], "isError": False}
+ if method == "ping":
+ return {}
+ raise LookupError(method)
+
+
+def main():
+ for line in sys.stdin:
+ if not line.strip():
+ continue
+ msg = json.loads(line)
+ if "id" not in msg:
+ continue # a notification (notifications/initialized, cancelled ...)
+ out = {"jsonrpc": "2.0", "id": msg["id"]}
+ try:
+ out["result"] = handle(msg.get("method"), msg.get("params") or {})
+ except LookupError:
+ out["error"] = {"code": -32601, "message": "method not found: %s" % msg.get("method")}
+ except Exception as e: # noqa: BLE001 — report it to the client, keep serving
+ out["error"] = {"code": -32603, "message": repr(e)[:500]}
+ sys.stdout.write(json.dumps(out) + "\n")
+ sys.stdout.flush()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/bench/core/client.py b/bench/core/client.py
index b468dc3..b426ed8 100644
--- a/bench/core/client.py
+++ b/bench/core/client.py
@@ -1,81 +1,325 @@
-"""OpenAI-compatible chat-completions client used by every instrument.
-
-One thin wrapper around urllib + json. No deps. Every instrument imports
-`call_model` from here so endpoint/auth/model config lives in exactly one
-place (loaded from .env at import time, overridable via env vars).
-
-Env vars (all optional — sensible defaults):
- ENDPOINT chat-completions URL (default http://127.0.0.1:1234/v1/chat/completions)
- MODEL model id (default "local")
- API_KEY bearer token, sent if set (default none)
- MAX_TOKENS per-turn generation cap (default 8000)
- TEMPERATURE sampling temp (default 0.0)
- HTTP_TIMEOUT per-request wall timeout (default 900s)
- NOTHINK "1" = append empty <think/> (default off)
+"""OpenAI-compatible chat-completions client (urllib + json) used by every instrument.
+
+call_model builds each body from the active lane (bench.core.lane), later wins:
+ {model, messages[, tools]} <- instrument defaults (max_tokens=, temperature= kwargs)
+ <- lane.request <- override= kwarg <- lane.extra_body (deep merge) <- lane no-think mechanism
+
+History hygiene (so no lane gets a template 500 from our own echo): assistant tool_call
+`arguments` that are not a JSON object become "{}", dict arguments are serialized, and
+reasoning fields are dropped from prior turns unless the lane sets reasoning_echo=true.
+
+Failures raise CallError, labelled for result rows: http_<code> | oom | ctx_overflow | timeout
+| conn_error | budget_stop | guard_refused | bad_response. 429/502/503/504/529 and connection
+resets are retried with backoff (Retry-After honored); 500/4xx and timeouts are not.
"""
+import copy
+import hashlib
+import http.client
import json
import os
+import random
+import re
+import socket
import time
-import urllib.request
import urllib.error
+import urllib.request
-ENDPOINT = os.environ.get(
- "ENDPOINT", "http://127.0.0.1:1234/v1/chat/completions")
-MODEL = os.environ.get("MODEL", "local")
-API_KEY = os.environ.get("API_KEY", "")
-MAX_TOKENS = int(os.environ.get("MAX_TOKENS", "8000"))
-TEMPERATURE = float(os.environ.get("TEMPERATURE", "0"))
-HTTP_TIMEOUT = int(os.environ.get("HTTP_TIMEOUT", "900"))
-NOTHINK = os.environ.get("NOTHINK", "") == "1"
+from bench.core import lane as lane_mod
+from bench.core import ledger
+RETRY_STATUS = {429, 502, 503, 504, 529}
+OOM_MARKERS = ("out of memory", "failed to allocate", "cudamalloc", "insufficient memory")
+CTX_MARKERS = ("context size", "context length", "exceeds the available context", "maximum context",
+ "too many tokens", "context_length_exceeded")
+THINK_PREFILL = "<think>\n\n</think>\n\n"
+BACKOFF_SCALE = float(os.environ.get("BENCH_BACKOFF_SCALE", "1")) # tests set ~0
-def call_model(messages, tools=None, *, max_tokens=None, temperature=None,
- model=None, endpoint=None, api_key=None, http_timeout=None):
- """Send a chat-completions request. Returns (resp_dict, elapsed_seconds).
- All kwargs default to the module-level config (env-driven). Pass kwargs
- only when an instrument needs to override per-call (e.g. router_bench
- wants NOTHINK but coding-suite does not).
- """
- msgs = list(messages)
- if NOTHINK:
- msgs = msgs + [{"role": "assistant", "content": "<think></think>"}]
- body = {
- "model": model or MODEL,
- "messages": msgs,
- "max_tokens": max_tokens if max_tokens is not None else MAX_TOKENS,
- "temperature": temperature if temperature is not None else TEMPERATURE,
- }
+def _backoff(attempt):
+ return BACKOFF_SCALE * 3 * 2 ** (attempt - 1)
+
+
+class CallError(RuntimeError):
+ def __init__(self, kind, detail="", code=None, attempts=1):
+ super().__init__(f"{kind}{'' if code is None else ' ' + str(code)}: {detail[:300]}")
+ self.kind = kind
+ self.code = code
+ self.detail = detail[:500]
+ self.attempts = attempts
+
+ def label(self):
+ if self.kind == "http":
+ low = self.detail.lower()
+ if self.code == 507 or any(m in low for m in OOM_MARKERS):
+ return "oom"
+ if self.code == 400 and any(m in low for m in CTX_MARKERS):
+ return "ctx_overflow"
+ return f"http_{self.code}"
+ return {"timeout": "timeout", "conn": "conn_error", "budget": "budget_stop",
+ "guard": "guard_refused"}.get(self.kind, "bad_response")
+
+
+def _deep_merge(dst, src):
+ for k, v in src.items():
+ if isinstance(v, dict) and isinstance(dst.get(k), dict):
+ _deep_merge(dst[k], v)
+ else:
+ dst[k] = copy.deepcopy(v)
+ return dst
+
+
+def _sanitize_history(messages, keep_reasoning):
+ out = []
+ for m in messages:
+ m = dict(m)
+ if m.get("role") == "assistant":
+ if not keep_reasoning:
+ m.pop("reasoning_content", None)
+ m.pop("reasoning", None)
+ m.pop("reasoning_details", None)
+ if m.get("tool_calls"):
+ fixed = []
+ for tc in m["tool_calls"]:
+ tc = copy.deepcopy(tc)
+ fn = tc.setdefault("function", {})
+ args = fn.get("arguments")
+ if isinstance(args, dict):
+ fn["arguments"] = json.dumps(args)
+ else:
+ try:
+ ok = isinstance(json.loads(args or ""), dict)
+ except (TypeError, ValueError):
+ ok = False
+ if not ok:
+ fn["arguments"] = "{}"
+ fixed.append(tc)
+ m["tool_calls"] = fixed
+ out.append(m)
+ return out
+
+
+def _merge_system(messages):
+ sys_parts = [m.get("content") or "" for m in messages if m.get("role") == "system"]
+ if len(sys_parts) <= 1 and (not sys_parts or messages[0].get("role") == "system"):
+ return messages
+ rest = [m for m in messages if m.get("role") != "system"]
+ return [{"role": "system", "content": "\n\n".join(sys_parts)}] + rest
+
+
+def build_body(messages, tools=None, *, max_tokens=None, temperature=None, override=None,
+ lane=None):
+ """Return the exact request body for this lane (exposed for tests/mocks)."""
+ lane = lane or lane_mod.current()
+ msgs = _sanitize_history(list(messages), bool(lane.raw.get("reasoning_echo")))
+ if lane.raw.get("merge_system_messages"):
+ msgs = _merge_system(msgs)
+ body = {"model": lane.model, "messages": msgs}
+ if max_tokens is not None:
+ body["max_tokens"] = max_tokens
+ if temperature is not None:
+ body["temperature"] = temperature
+ body.update(copy.deepcopy(lane.request))
+ if override:
+ body.update(copy.deepcopy(override))
+ _deep_merge(body, lane.extra_body)
+ if lane.thinking == "off":
+ mech = lane.nothink["mechanism"]
+ if mech == "reasoning_effort_none":
+ body["reasoning_effort"] = "none"
+ elif mech == "openrouter_reasoning_off":
+ body.pop("reasoning_effort", None)
+ _deep_merge(body, {"reasoning": {"enabled": False, "exclude": False}})
+ elif mech == "template_kwargs":
+ _deep_merge(body, {"chat_template_kwargs": {"enable_thinking": False}})
+ elif mech == "think_prefill":
+ body["messages"] = body["messages"] + [{"role": "assistant", "content": THINK_PREFILL}]
if tools:
body["tools"] = tools
+ for field, bad in lane.forbid.items():
+ if body.get(field) in bad:
+ raise CallError("guard", f"lane {lane.lane_id} forbids {field}={body.get(field)!r}")
+ return body
+
+
+def request_profile(body):
+ """The settings part of a body (no messages/tools) + a short hash, for result rows."""
+ prof = {k: v for k, v in body.items() if k not in ("messages", "tools")}
+ h = hashlib.sha256(json.dumps(prof, sort_keys=True).encode()).hexdigest()[:12]
+ return prof, h
+
+
+def _post(url, data, headers, timeout):
+ req = urllib.request.Request(url, data=data, headers=headers)
+ with urllib.request.urlopen(req, timeout=timeout) as r:
+ return json.load(r)
+
+
+def call_model(messages, tools=None, *, max_tokens=None, temperature=None, override=None,
+ item_id=None, run_id=None, lane=None):
+ """Send one chat-completions request. Returns (resp_dict, elapsed_seconds).
+
+ resp["_bench"] carries per-call metadata (attempts, request profile + hash,
+ cost, provider, gen id) for result rows. Raises CallError on failure.
+ """
+ lane = lane or lane_mod.current()
+ if lane.raw.get("runner"):
+ raise CallError("guard", f"lane {lane.lane_id} runs through {lane.raw['runner']}, "
+ "which drives agentic instruments only")
+ body = build_body(messages, tools, max_tokens=max_tokens, temperature=temperature,
+ override=override, lane=lane)
data = json.dumps(body).encode()
+ if lane.cost:
+ try:
+ ledger.check(lane.cost, len(data), body.get("max_tokens"))
+ except ledger.BudgetExceeded as e:
+ raise CallError("budget", str(e))
headers = {"Content-Type": "application/json"}
- key = api_key if api_key is not None else API_KEY
+ key = lane.api_key()
if key:
headers["Authorization"] = "Bearer " + key
- req = urllib.request.Request(
- endpoint or ENDPOINT, data=data, headers=headers)
+ url = lane.endpoint
+ timeout = lane.http_timeout
+ retries = int(lane.raw.get("retries", 4))
+ attempt = 0
t0 = time.time()
- timeout = http_timeout or HTTP_TIMEOUT
- with urllib.request.urlopen(req, timeout=timeout) as r:
- resp = json.load(r)
- return resp, time.time() - t0
+ while True:
+ attempt += 1
+ wait = None
+ try:
+ resp = _post(url, data, headers, timeout)
+ err = resp.get("error") if isinstance(resp, dict) else None
+ if err and not resp.get("choices"):
+ # OpenRouter can return 200 with an error object from the provider.
+ code = err.get("code") if isinstance(err.get("code"), int) else 502
+ if code in RETRY_STATUS and attempt <= retries:
+ wait = _backoff(attempt)
+ else:
+ raise CallError("http", json.dumps(err)[:500], code=code, attempts=attempt)
+ elif not isinstance(resp, dict) or not resp.get("choices"):
+ raise CallError("bad_response", json.dumps(resp)[:500], attempts=attempt)
+ else:
+ break
+ except urllib.error.HTTPError as e:
+ detail = ""
+ try:
+ detail = e.read().decode("utf-8", "replace")
+ except Exception: # noqa: BLE001 — best effort body read
+ pass
+ if e.code in RETRY_STATUS and attempt <= retries:
+ ra = e.headers.get("Retry-After") if e.headers else None
+ wait = min(float(ra), 120.0) * BACKOFF_SCALE \
+ if ra and ra.replace(".", "", 1).isdigit() else _backoff(attempt)
+ else:
+ raise CallError("http", detail, code=e.code, attempts=attempt)
+ except (socket.timeout, TimeoutError) as e:
+ raise CallError("timeout", f"no response within {timeout}s ({e})", attempts=attempt)
+ except ValueError as e: # non-JSON body
+ raise CallError("bad_response", f"unparseable response: {e}", attempts=attempt)
+ except (urllib.error.URLError, ConnectionError, http.client.RemoteDisconnected) as e:
+ reason = getattr(e, "reason", e)
+ if isinstance(reason, (socket.timeout, TimeoutError)):
+ raise CallError("timeout", f"no response within {timeout}s", attempts=attempt)
+ if attempt <= retries:
+ wait = _backoff(attempt)
+ else:
+ raise CallError("conn", repr(reason), attempts=attempt)
+ time.sleep(wait + random.uniform(0, BACKOFF_SCALE))
+ dt = time.time() - t0
+ prof, h = request_profile(body)
+ u = usage(resp)
+ resp["_bench"] = {"attempts": attempt, "request": prof, "request_hash": h,
+ "provider": resp.get("provider"), "gen_id": resp.get("id"),
+ "cost_usd": u["cost_usd"]}
+ if lane.cost:
+ cost = u["cost_usd"]
+ if cost is None: # provider didn't report: charge the token-priced estimate
+ cost = (u["prompt_tokens"] * float(lane.cost.get("in_per_m", 0)) +
+ u["completion_tokens"] * float(lane.cost.get("out_per_m", 0))) / 1e6
+ resp["_bench"]["cost_usd"] = cost
+ resp["_bench"]["cost_estimated"] = True
+ ledger.record(lane.cost, lane_id=lane.lane_id, run_id=run_id, item_id=item_id,
+ cost_usd=cost, gen_id=resp.get("id"), provider=resp.get("provider"))
+ return resp, dt
+
+
+# ---- response extraction (one place for every runtime's quirks) ----------------------
+
+_THINK_RE = re.compile(r"^\s*<think>(.*?)</think>\s*", re.DOTALL)
+
+
+def _msg(resp):
+ return resp["choices"][0].get("message") or {}
+
+
+def _raw_content(resp):
+ c = _msg(resp).get("content")
+ if isinstance(c, list): # content-parts form
+ c = "".join(p.get("text", "") for p in c if isinstance(p, dict))
+ return c or ""
def content(resp):
- """Extract the assistant content string from a chat-completions response."""
- return resp["choices"][0]["message"].get("content") or ""
+ """Answer text with any inline <think>…</think> removed ("" if thinking never closed)."""
+ c = _raw_content(resp)
+ m = _THINK_RE.match(c)
+ if m:
+ return c[m.end():]
+ if c.lstrip().startswith("<think>"):
+ return ""
+ return c
+
+
+def reasoning(resp):
+ """Thinking text from reasoning_content (llama-server), reasoning (MLX/OpenRouter),
+ reasoning_details (OpenRouter) or an inline <think> block."""
+ msg = _msg(resp)
+ r = msg.get("reasoning_content") or msg.get("reasoning")
+ if not r and isinstance(msg.get("reasoning_details"), list):
+ r = "".join(d.get("text", "") or d.get("summary", "") for d in msg["reasoning_details"]
+ if isinstance(d, dict))
+ if r:
+ return r
+ c = _raw_content(resp)
+ m = _THINK_RE.match(c)
+ if m:
+ return m.group(1)
+ if c.lstrip().startswith("<think>"):
+ return c.lstrip()[len("<think>"):]
+ return ""
def tool_calls(resp):
"""Extract the tool_calls list (empty if none)."""
- return resp["choices"][0]["message"].get("tool_calls") or []
+ return _msg(resp).get("tool_calls") or []
-def reasoning(resp):
- """Extract reasoning_content (thinking) if the backend exposes it."""
- msg = resp["choices"][0]["message"]
- return msg.get("reasoning_content") or ""
+def json_spans(text, opener="{", closer="}"):
+ """(start, span) for every balanced opener...closer span of text, left to right, outermost
+ only, skipping brackets inside JSON strings. An opener that never closes is skipped."""
+ i = 0
+ while i < len(text):
+ if text[i] == opener:
+ depth, in_str, esc = 0, False, False
+ for j in range(i, len(text)):
+ ch = text[j]
+ if in_str:
+ if esc:
+ esc = False
+ elif ch == "\\":
+ esc = True
+ elif ch == '"':
+ in_str = False
+ elif ch == '"':
+ in_str = True
+ elif ch == opener:
+ depth += 1
+ elif ch == closer:
+ depth -= 1
+ if depth == 0:
+ yield i, text[i:j + 1]
+ i = j
+ break
+ i += 1
def finish_reason(resp):
@@ -83,23 +327,77 @@ def finish_reason(resp):
def usage(resp):
- """Return a normalized usage dict: prompt/completion/reasoning tokens."""
+ """Normalized usage. reasoning_tokens / cached_tokens / cost_usd are None when the
+ backend doesn't report them (None is not 0)."""
u = resp.get("usage") or {}
+ ctd = u.get("completion_tokens_details") or {}
+ ptd = u.get("prompt_tokens_details") or {}
+ t = resp.get("timings") or {}
+ cached = ptd.get("cached_tokens")
+ if cached is None:
+ cached = t.get("cache_n")
return {
"prompt_tokens": u.get("prompt_tokens") or 0,
"completion_tokens": u.get("completion_tokens") or 0,
- "reasoning_tokens":
- (u.get("completion_tokens_details") or {}).get("reasoning_tokens") or 0,
+ "reasoning_tokens": ctd.get("reasoning_tokens"),
+ "cached_tokens": cached,
+ "cost_usd": u.get("cost"),
}
def timings(resp):
- """Return prefill/decode tok/s if the backend reports them (llama-server).
-
- OpenAI-style responses don't have these; they'll be None.
- """
+ """llama-server timings (None elsewhere). prefill_ps excludes cached tokens."""
t = resp.get("timings") or {}
return {
"prefill_ps": t.get("prompt_per_second"),
"decode_ps": t.get("predicted_per_second"),
- }
\ No newline at end of file
+ "prompt_n": t.get("prompt_n"),
+ "prompt_ms": t.get("prompt_ms"),
+ "predicted_n": t.get("predicted_n"),
+ "predicted_ms": t.get("predicted_ms"),
+ "cache_n": t.get("cache_n"),
+ "draft_n": t.get("draft_n"),
+ "draft_n_accepted": t.get("draft_n_accepted"),
+ }
+
+
+def status(resp):
+ """ok | truncated (finish=length) | empty (no answer and no tool call)."""
+ if finish_reason(resp) == "length":
+ return "truncated"
+ if not content(resp).strip() and not tool_calls(resp):
+ return "empty"
+ return "ok"
+
+
+def meta(resp, wall_s=None):
+ """Standard per-call fields for a result row."""
+ u = usage(resp)
+ b = resp.get("_bench") or {}
+ row = {
+ "status": status(resp),
+ "finish": finish_reason(resp),
+ "prompt_tokens": u["prompt_tokens"],
+ "completion_tokens": u["completion_tokens"],
+ "reasoning_tokens": u["reasoning_tokens"],
+ "cached_tokens": u["cached_tokens"],
+ "reasoning_chars": len(reasoning(resp)),
+ "content_chars": len(content(resp)),
+ "wall_s": None if wall_s is None else round(wall_s, 2),
+ "attempts": b.get("attempts"),
+ "request_hash": b.get("request_hash"),
+ "cost_usd": b.get("cost_usd"),
+ "provider": b.get("provider"),
+ "gen_id": b.get("gen_id"),
+ }
+ row.update({k: v for k, v in timings(resp).items() if v is not None})
+ return row
+
+
+def error_meta(err, wall_s=None):
+ """Result-row fields for a failed call (CallError or anything else)."""
+ if isinstance(err, CallError):
+ return {"status": err.label(), "error": str(err)[:300], "attempts": err.attempts,
+ "wall_s": None if wall_s is None else round(wall_s, 2)}
+ return {"status": "harness_error", "error": repr(err)[:300],
+ "wall_s": None if wall_s is None else round(wall_s, 2)}
diff --git a/bench/core/lane.py b/bench/core/lane.py
new file mode 100644
index 0000000..125ff49
--- /dev/null
+++ b/bench/core/lane.py
@@ -0,0 +1,150 @@
+"""Lane profiles: one JSON file per (server, model, request settings) under test.
+
+A lane is everything that decides what a model is asked and how: endpoint, model id, full
+sampler, max_tokens, thinking on/off and how it is turned off, provider pinning, timeouts and
+provenance. Instruments read it through `current()` and the client merges it into every
+request, so two lanes are always compared under recorded settings, never server defaults.
+LANE=<id> loads lanes/<id>.json, LANE=<path> loads that file; LANE is required.
+
+Lane file keys (all optional except lane_id, endpoint, model):
+ lane_id, description, base_model
+ card HF repo id of the model card whose sampler applies (a key of lanes/cards.json;
+ the base model's card for a straight quant). Conformance checks the sampler.
+ sampler_overrides {"<field>": {"value": <sent value>, "reason": "..."}} accepted card deviations
+ runner "claude-cli": agentic attempts run on headless `claude -p` (bench/core/claude_cli.py;
+ model = --model, effort = --effort); no HTTP endpoint, no card, no sampler
+ endpoint chat-completions URL
+ model value of the request "model" field
+ auth {"keychain_service": "<svc>"} | {"env": "<VAR>"[, "required": true]} | null
+ thinking "on" | "off"
+ nothink {"mechanism": "reasoning_effort_none" | "openrouter_reasoning_off"
+ | "template_kwargs" | "think_prefill"} (thinking "off" only)
+ request merged into every body; wins over instrument defaults
+ (temperature, top_p, top_k, min_p, presence_penalty,
+ repetition_penalty, max_tokens, seed, reasoning_effort ...)
+ extra_body deep-merged last (provider pinning, usage accounting ...)
+ forbid {"<field>": [bad values]} -> refused client-side
+ merge_system_messages, reasoning_echo, retries client behaviour (see client.py)
+ http_timeout seconds per request (default 1800)
+ max_concurrency upper bound for instruments that run items in parallel
+ cost {"ledger": "<name>", "cap_usd": 5.0, "in_per_m": .., "out_per_m": ..}
+ snapshot "llama-server" | "mtplx" | "openrouter" | "none"
+ weights, runtime, context free-form provenance, copied into every run record
+"""
+import json
+import os
+import subprocess
+import threading
+
+HERE = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+LANES_DIR = os.path.join(HERE, "lanes")
+
+NOTHINK_MECHANISMS = ("reasoning_effort_none", "openrouter_reasoning_off",
+ "template_kwargs", "think_prefill")
+
+_current = None
+_lock = threading.Lock()
+
+
+class LaneError(ValueError):
+ pass
+
+
+class Lane:
+ def __init__(self, raw, source):
+ self.raw = raw
+ self.source = source
+ for key in ("lane_id", "endpoint", "model"):
+ if not raw.get(key):
+ raise LaneError(f"lane {source}: missing {key!r}")
+ self.lane_id = raw["lane_id"]
+ self.endpoint = raw["endpoint"]
+ self.model = raw["model"]
+ self.thinking = raw.get("thinking", "on")
+ if self.thinking not in ("on", "off"):
+ raise LaneError(f"lane {self.lane_id}: thinking must be 'on' or 'off'")
+ self.nothink = raw.get("nothink")
+ if self.thinking == "off":
+ mech = (self.nothink or {}).get("mechanism")
+ if mech not in NOTHINK_MECHANISMS:
+ raise LaneError(f"lane {self.lane_id}: thinking 'off' needs nothink.mechanism "
+ f"in {NOTHINK_MECHANISMS}")
+ self.request = dict(raw.get("request") or {})
+ self.extra_body = dict(raw.get("extra_body") or {})
+ self.forbid = dict(raw.get("forbid") or {})
+ self.http_timeout = int(raw.get("http_timeout", 1800))
+ self.max_concurrency = int(raw.get("max_concurrency", 1))
+ self.cost = raw.get("cost")
+ self.snapshot_kind = raw.get("snapshot", "none")
+ self._key = None
+
+ # ---- auth -------------------------------------------------------------
+ def api_key(self):
+ """Resolve the bearer token at call time. Never logged or returned in records."""
+ if self._key is not None:
+ return self._key
+ auth = self.raw.get("auth") or {}
+ key = ""
+ if auth.get("env"):
+ key = os.environ.get(auth["env"], "")
+ if not key and auth.get("required"):
+ raise LaneError(f"lane {self.lane_id}: env {auth['env']} is empty (auth.required)")
+ elif auth.get("keychain_service"):
+ try:
+ p = subprocess.run(["security", "find-generic-password", "-s",
+ auth["keychain_service"], "-w"],
+ capture_output=True, text=True, timeout=30)
+ key = p.stdout.strip() if p.returncode == 0 else ""
+ except (FileNotFoundError, subprocess.TimeoutExpired):
+ key = ""
+ if not key:
+ raise LaneError(f"lane {self.lane_id}: keychain item "
+ f"{auth['keychain_service']!r} not readable")
+ self._key = key
+ return key
+
+ # ---- provenance ---------------------------------------------------------
+ def record(self):
+ """The lane block written into every run record (no secrets)."""
+ r = {k: v for k, v in self.raw.items() if k != "auth"}
+ auth = self.raw.get("auth") or {}
+ r["auth_kind"] = next(iter(auth), None)
+ r["source"] = self.source
+ return r
+
+ def base_url(self):
+ """Server root, e.g. http://host:8000 for .../v1/chat/completions."""
+ ep = self.endpoint
+ for suffix in ("/v1/chat/completions", "/chat/completions"):
+ if ep.endswith(suffix):
+ return ep[: -len(suffix)]
+ return ep.rsplit("/", 1)[0]
+
+
+def load(spec):
+ """Load a lane from an id (lanes/<id>.json) or a path."""
+ path = spec if (os.sep in spec or spec.endswith(".json")) else os.path.join(LANES_DIR, spec + ".json")
+ if not os.path.isfile(path):
+ raise LaneError(f"lane file not found: {path}")
+ with open(path) as f:
+ raw = json.load(f)
+ return Lane(raw, os.path.relpath(path, HERE) if path.startswith(HERE) else path)
+
+
+def current():
+ """The active lane for this process (LANE env)."""
+ global _current
+ with _lock:
+ if _current is None:
+ spec = os.environ.get("LANE", "").strip()
+ if not spec:
+ raise LaneError("LANE is not set; set LANE=<id> to one of the lanes/*.json files.")
+ _current = load(spec)
+ return _current
+
+
+def set_current(lane):
+ """Tests / multi-lane drivers: replace the active lane."""
+ global _current
+ with _lock:
+ _current = lane
diff --git a/bench/core/ledger.py b/bench/core/ledger.py
new file mode 100644
index 0000000..4c96561
--- /dev/null
+++ b/bench/core/ledger.py
@@ -0,0 +1,81 @@
+"""Spend ledger + cap for paid lanes (OpenRouter).
+
+Every paid call appends {ts, lane_id, run_id, item_id, cost_usd, gen_id,
+provider} to bench/results/_ledger/<ledger>.jsonl. Before each call the client asks
+`check()` whether spent-so-far + a worst-case estimate for this call would
+cross the cap; if so it raises BudgetExceeded and the instrument records the
+item as status "budget_stop" (not as a model failure).
+
+The ledger is a plain append-only file guarded by an flock, so several bench
+processes (one per lane) share one budget. The cap comes from the lane's
+`cost.cap_usd`, overridable with LEDGER_CAP_USD. It is a soft cap: concurrent calls can each
+pass check() before any of them is recorded, and overshoot it.
+"""
+import fcntl
+import json
+import os
+import time
+
+from bench.core.reporting import RESULTS_DIR
+
+LEDGER_DIR = os.path.join(RESULTS_DIR, "_ledger")
+
+
+class BudgetExceeded(RuntimeError):
+ pass
+
+
+def _path(name):
+ os.makedirs(LEDGER_DIR, exist_ok=True)
+ return os.path.join(LEDGER_DIR, f"{name}.jsonl")
+
+
+def spent(name):
+ p = _path(name)
+ if not os.path.exists(p):
+ return 0.0
+ total = 0.0
+ with open(p) as f:
+ fcntl.flock(f, fcntl.LOCK_SH)
+ for line in f:
+ if line.strip():
+ total += float(json.loads(line).get("cost_usd") or 0.0)
+ fcntl.flock(f, fcntl.LOCK_UN)
+ return total
+
+
+def cap_for(cost_cfg):
+ env = os.environ.get("LEDGER_CAP_USD")
+ if env:
+ return float(env)
+ return float(cost_cfg.get("cap_usd", 0.0))
+
+
+def estimate(cost_cfg, prompt_chars, max_tokens):
+ """Worst-case $ for one call: ~3.5 chars/token in, full max_tokens out."""
+ in_m = float(cost_cfg.get("in_per_m", 0.0))
+ out_m = float(cost_cfg.get("out_per_m", 0.0))
+ return (prompt_chars / 3.5) * in_m / 1e6 + (max_tokens or 0) * out_m / 1e6
+
+
+def check(cost_cfg, prompt_chars, max_tokens):
+ """Raise BudgetExceeded if this call could push the ledger past the cap."""
+ name = cost_cfg.get("ledger", "default")
+ cap = cap_for(cost_cfg)
+ if cap <= 0:
+ return
+ now = spent(name)
+ est = estimate(cost_cfg, prompt_chars, max_tokens)
+ if now + est > cap:
+ raise BudgetExceeded(
+ f"ledger {name!r}: spent ${now:.4f} + worst-case ${est:.4f} > cap ${cap:.2f}")
+
+
+def record(cost_cfg, *, lane_id, run_id, item_id, cost_usd, gen_id, provider):
+ name = cost_cfg.get("ledger", "default")
+ row = {"ts": time.strftime("%Y-%m-%dT%H:%M:%S"), "lane_id": lane_id, "run_id": run_id,
+ "item_id": item_id, "cost_usd": cost_usd, "gen_id": gen_id, "provider": provider}
+ with open(_path(name), "a") as f:
+ fcntl.flock(f, fcntl.LOCK_EX)
+ f.write(json.dumps(row) + "\n")
+ fcntl.flock(f, fcntl.LOCK_UN)
diff --git a/bench/core/mockserver.py b/bench/core/mockserver.py
new file mode 100644
index 0000000..7175a5a
--- /dev/null
+++ b/bench/core/mockserver.py
@@ -0,0 +1,120 @@
+"""Scriptable mock OpenAI-compatible server for offline harness tests.
+
+Never point a harness change at a live endpoint first: start a MockServer,
+point a lane at it, and assert on what the harness sent and how it scored.
+
+ with MockServer() as srv:
+ srv.script = [chat("hi"), (429, {"error": "slow down"}), chat("ok")]
+ lane = srv.lane(request={"temperature": 1.0})
+ ...
+ srv.requests # list of received JSON bodies, in order
+
+`script` items are consumed in order; each is a response dict (HTTP 200),
+a (status, body) tuple, or a callable(body) -> either. When the script runs
+out, `default` (a callable or response) answers. GET /props, /v1/models and
+/slots return canned llama-server-ish JSON.
+"""
+import json
+import threading
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+
+from bench.core.lane import Lane
+
+
+def chat(content="", *, reasoning=None, reasoning_field="reasoning_content", tool_calls=None,
+ finish="stop", prompt_tokens=10, completion_tokens=5, reasoning_tokens=None,
+ cost=None, provider=None, timings=None):
+ msg = {"role": "assistant", "content": content}
+ if reasoning is not None:
+ msg[reasoning_field] = reasoning
+ if tool_calls:
+ msg["tool_calls"] = tool_calls
+ if finish == "stop":
+ finish = "tool_calls"
+ usage = {"prompt_tokens": prompt_tokens, "completion_tokens": completion_tokens,
+ "total_tokens": prompt_tokens + completion_tokens}
+ if reasoning_tokens is not None:
+ usage["completion_tokens_details"] = {"reasoning_tokens": reasoning_tokens}
+ if cost is not None:
+ usage["cost"] = cost
+ resp = {"id": "gen-mock", "object": "chat.completion", "model": "mock",
+ "choices": [{"index": 0, "message": msg, "finish_reason": finish}], "usage": usage}
+ if provider:
+ resp["provider"] = provider
+ if timings:
+ resp["timings"] = timings
+ return resp
+
+
+def tool_call(name, arguments, call_id="call_0"):
+ args = arguments if isinstance(arguments, str) else json.dumps(arguments)
+ return {"id": call_id, "type": "function", "function": {"name": name, "arguments": args}}
+
+
+class MockServer:
+ def __init__(self):
+ self.script = []
+ self.default = chat("mock default")
+ self.requests = []
+ self.gets = []
+ self._lock = threading.Lock()
+ outer = self
+
+ class H(BaseHTTPRequestHandler):
+ def log_message(self, *a): # quiet
+ pass
+
+ def _send(self, status, body):
+ data = json.dumps(body).encode()
+ self.send_response(status)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(data)))
+ self.end_headers()
+ self.wfile.write(data)
+
+ def do_GET(self):
+ outer.gets.append(self.path)
+ if self.path.startswith("/props"):
+ self._send(200, {"default_generation_settings": {"n_ctx": 65536},
+ "total_slots": 2, "chat_template": "{{ messages }}",
+ "build_info": "mock"})
+ elif self.path.startswith("/v1/models"):
+ self._send(200, {"object": "list", "data": [{"id": "mock"}]})
+ elif self.path.startswith("/slots"):
+ self._send(200, [{"id": 0, "is_processing": False}])
+ else:
+ self._send(404, {"error": "not found"})
+
+ def do_POST(self):
+ n = int(self.headers.get("Content-Length") or 0)
+ body = json.loads(self.rfile.read(n) or b"{}")
+ with outer._lock:
+ outer.requests.append({"path": self.path, "body": body,
+ "auth": self.headers.get("Authorization")})
+ item = outer.script.pop(0) if outer.script else outer.default
+ if callable(item):
+ item = item(body)
+ status, payload = item if isinstance(item, tuple) else (200, item)
+ self._send(status, payload)
+
+ self.httpd = ThreadingHTTPServer(("127.0.0.1", 0), H)
+ self.port = self.httpd.server_address[1]
+ self._t = threading.Thread(target=self.httpd.serve_forever, daemon=True)
+
+ @property
+ def url(self):
+ return f"http://127.0.0.1:{self.port}/v1/chat/completions"
+
+ def lane(self, lane_id="mock", **overrides):
+ raw = {"lane_id": lane_id, "endpoint": self.url, "model": "mock",
+ "snapshot": "llama-server", "http_timeout": 10, "retries": 2}
+ raw.update(overrides)
+ return Lane(raw, "mock")
+
+ def __enter__(self):
+ self._t.start()
+ return self
+
+ def __exit__(self, *exc):
+ self.httpd.shutdown()
+ self.httpd.server_close()
diff --git a/bench/core/reporting.py b/bench/core/reporting.py
index 88786b9..59aaa12 100644
--- a/bench/core/reporting.py
+++ b/bench/core/reporting.py
@@ -1,62 +1,12 @@
-"""Shared reporting helpers — JSONL append, summary tables, result loading."""
-import json
+"""Where results live (BENCH_RESULTS_DIR, default bench/results) and filesystem-safe labels."""
import os
import re
HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
-RESULTS_DIR = os.path.join(HERE, "results")
+RESULTS_DIR = os.environ.get("BENCH_RESULTS_DIR") or os.path.join(HERE, "results")
os.makedirs(RESULTS_DIR, exist_ok=True)
def safe_label(s):
"""Sanitize a model name into a filesystem-safe label."""
return re.sub(r"[^A-Za-z0-9._-]", "_", s)
-
-
-def jsonl_path(label, prefix=""):
- """Return the JSONL output path for a given label/prefix."""
- name = f"{prefix}_{safe_label(label)}.jsonl" if prefix else f"{safe_label(label)}.jsonl"
- return os.path.join(RESULTS_DIR, name)
-
-
-def append_jsonl(path, record):
- with open(path, "a") as f:
- f.write(json.dumps(record) + "\n")
-
-
-def load_jsonl(path):
- if not os.path.exists(path):
- return []
- return [json.loads(l) for l in open(path) if l.strip()]
-
-
-def write_json(record, label, prefix=""):
- path = os.path.join(RESULTS_DIR, f"{prefix}_{safe_label(label)}.json"
- if prefix else f"{safe_label(label)}.json")
- with open(path, "w") as f:
- json.dump(record, f, indent=2)
- return path
-
-
-def coding_suite_summary(results):
- """Print + return the coding-suite scoreboard."""
- npass = sum(1 for r in results if r.get("passed"))
- print("\n========================= SUMMARY =========================")
- print("Overall: %d/%d passed (%.0f%%)\n" %
- (npass, len(results), 100 * npass / max(len(results), 1)))
- cats = {}
- for r in results:
- cats.setdefault(r["cat"], []).append(r)
- for cat, rs in cats.items():
- p = sum(1 for r in rs if r.get("passed"))
- print(" %-9s %d/%d" % (cat, p, len(rs)))
- print("\n %-16s %-5s %-6s %-7s %-9s %s" %
- ("task", "pass", "lat_s", "tot_tok", "reason_tok", "note"))
- for r in results:
- print(" %-16s %-5s %-6s %-7s %-9s %s" % (
- r["id"], "Y" if r.get("passed") else "n",
- r.get("latency_s", "-"), r.get("total_tokens", "-"),
- r.get("reasoning_tokens", "-"),
- ("" if r.get("passed") else (r.get("detail", "") or "")[:80])))
- print()
- return npass == len(results)
\ No newline at end of file
diff --git a/bench/core/results.py b/bench/core/results.py
new file mode 100644
index 0000000..a83c15b
--- /dev/null
+++ b/bench/core/results.py
@@ -0,0 +1,387 @@
+"""Append-only, provenance-carrying result store and the run driver every instrument shares.
+
+ bench/results/<instrument>/<lane_id>/<run_id>/ (never overwritten: a fresh run_id per run)
+ run.json lane record (no secrets) + server snapshot + harness git sha/dirty + host
+ + args + item_set + started/ended + complete flag
+ items.jsonl one row per attempt (row contract: CONTRACT.md)
+ summary.json written by finish()
+
+Rows are read back deduped (see dedupe) and with read-time status rules (effective_status).
+"""
+import json
+import os
+import platform
+import socket
+import subprocess
+import threading
+import time
+import uuid
+import urllib.parse
+import urllib.request
+from concurrent.futures import ThreadPoolExecutor
+
+from bench.core import client, stats
+from bench.core import lane as lane_mod
+from bench.core.reporting import RESULTS_DIR, safe_label
+
+# Not a grade of the model's answer. ctx_overflow is listed here for quality comparisons,
+# but oracle-label derivation treats it as "this lane cannot take this job".
+INFRA_STATUSES = {"timeout", "oom", "ctx_overflow", "conn_error", "budget_stop",
+ "guard_refused", "bad_response", "harness_error", "skipped", "stripped"}
+
+# "stripped": the server generated answer tokens but returned none of them (no content, no
+# tool call) -- a provider-side parser ate the output: DeepInfra's Qwen tool
+# parser swallows a plain-text <tool_call>...</tool_call> even with no tools declared (3/3
+# probes on the tc-xml probe, now in conformance's preflight). Needs reported reasoning_tokens to tell answer tokens from
+# thinking, so llama-server lanes (which don't report them) stay "empty". One tool call is
+# ~27 tokens; a genuinely empty answer is a few end-of-turn tokens.
+STRIPPED_MIN_ANSWER_TOKENS = 16
+
+
+def is_infra(status):
+ return status in INFRA_STATUSES or str(status).startswith("http_")
+
+
+def effective_status(row):
+ """The row's status, with "empty" upgraded to "stripped" when answer tokens went missing.
+ Applied when rows are written and again when they are read, so stored rows reclassify."""
+ st = row.get("status")
+ ct, rt = row.get("completion_tokens"), row.get("reasoning_tokens")
+ if st == "empty" and rt is not None and ct and ct - rt >= STRIPPED_MIN_ANSWER_TOKENS:
+ return "stripped"
+ return st
+
+
+def _git_info():
+ here = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+ try:
+ sha = subprocess.run(["git", "rev-parse", "HEAD"], cwd=here, capture_output=True,
+ text=True, timeout=10).stdout.strip()
+ dirty = subprocess.run(["git", "status", "--porcelain", "--", "."], cwd=here,
+ capture_output=True, text=True, timeout=10).stdout.strip()
+ return {"git_sha": sha or None, "dirty": bool(dirty)}
+ except Exception: # noqa: BLE001 — provenance is best effort
+ return {"git_sha": None, "dirty": None}
+
+
+def _get_json(url, timeout=10):
+ try:
+ with urllib.request.urlopen(url, timeout=timeout) as r:
+ return json.load(r)
+ except Exception as e: # noqa: BLE001
+ return {"_error": repr(e)[:200]}
+
+
+def server_snapshot(lane):
+ """What the server says about itself, at run start. Large blobs are hashed."""
+ kind = lane.snapshot_kind
+ base = lane.base_url()
+ snap = {"kind": kind, "taken_at": time.strftime("%Y-%m-%dT%H:%M:%S")}
+ if kind == "llama-server":
+ # ?model= lets a multi-backend gateway (one port, several models) answer for the right
+ # backend; a bare llama-server ignores the query string.
+ props = _get_json(base + "/props?model=" + urllib.parse.quote(lane.model))
+ tmpl = props.pop("chat_template", None) if isinstance(props, dict) else None
+ if tmpl:
+ import hashlib
+ props["chat_template_sha256"] = hashlib.sha256(tmpl.encode()).hexdigest()
+ snap["props"] = props
+ snap["models"] = _get_json(base + "/v1/models")
+ elif kind == "mtplx":
+ snap["models"] = _get_json(base + "/v1/models")
+ elif kind == "openrouter":
+ snap["endpoints"] = _get_json(f"https://openrouter.ai/api/v1/models/{lane.model}/endpoints")
+ return snap
+
+
+class RunStore:
+ def __init__(self, instrument, *, item_set=None, args=None, lane=None):
+ self.lane = lane or lane_mod.current()
+ self.instrument = instrument
+ stamp = time.strftime("%Y%m%d-%H%M%S")
+ self.run_id = f"{stamp}-{uuid.uuid4().hex[:6]}"
+ self.dir = os.path.join(RESULTS_DIR, safe_label(instrument),
+ safe_label(self.lane.lane_id), self.run_id)
+ os.makedirs(self.dir, exist_ok=False)
+ self.items_path = os.path.join(self.dir, "items.jsonl")
+ self._lock = threading.Lock()
+ self.n_rows = 0
+ self.run = {
+ "run_id": self.run_id, "instrument": instrument, "item_set": item_set,
+ "lane": self.lane.record(),
+ "server": server_snapshot(self.lane),
+ "harness": dict(_git_info(), host=socket.gethostname(),
+ python=platform.python_version()),
+ "args": args or {}, "started_at": time.strftime("%Y-%m-%dT%H:%M:%S"),
+ "ended_at": None, "complete": False,
+ }
+ self._write_run()
+
+ def _write_run(self):
+ tmp = os.path.join(self.dir, "run.json.tmp")
+ with open(tmp, "w") as f:
+ json.dump(self.run, f, indent=2)
+ os.replace(tmp, os.path.join(self.dir, "run.json"))
+
+ def add(self, *, item_id, sample_idx=0, category=None, correct=None, score=None, **fields):
+ row = {"run_id": self.run_id, "lane_id": self.lane.lane_id,
+ "instrument": self.instrument, "item_id": item_id, "sample_idx": sample_idx,
+ "category": category, "correct": correct, "score": score,
+ "ts": time.strftime("%Y-%m-%dT%H:%M:%S")}
+ row.update(fields)
+ row.setdefault("status", "ok")
+ row["status"] = effective_status(row)
+ if is_infra(row["status"]) and correct is not None:
+ # An infra failure is never a grade.
+ row["correct"] = None
+ with self._lock:
+ with open(self.items_path, "a") as f:
+ f.write(json.dumps(row, default=str) + "\n")
+ self.n_rows += 1
+ return row
+
+ @classmethod
+ def resume(cls, run_dir, *, lane=None):
+ """Reopen an interrupted run to append the attempts it is missing.
+ The lane must match the one the run started with."""
+ self = cls.__new__(cls)
+ with open(os.path.join(run_dir, "run.json")) as f:
+ self.run = json.load(f)
+ self.lane = lane or lane_mod.current()
+ if self.lane.lane_id != self.run["lane"]["lane_id"]:
+ raise ValueError(f"resume: run is lane {self.run['lane']['lane_id']!r}, "
+ f"active lane is {self.lane.lane_id!r}")
+ self.instrument = self.run["instrument"]
+ self.run_id = self.run["run_id"]
+ self.dir = run_dir
+ self.items_path = os.path.join(run_dir, "items.jsonl")
+ self._lock = threading.Lock()
+ self.n_rows = sum(1 for _ in open(self.items_path)) if os.path.exists(self.items_path) else 0
+ self.run.setdefault("resumed_at", []).append(time.strftime("%Y-%m-%dT%H:%M:%S"))
+ self._write_run()
+ return self
+
+ def rows(self):
+ return dedupe(_read(self.items_path))
+
+ def done_keys(self):
+ """(item_id, sample_idx) pairs already recorded with a non-infra status —
+ a resumed run skips these and retries everything else."""
+ return {(r["item_id"], r.get("sample_idx", 0)) for r in self.rows()
+ if not is_infra(r.get("status"))}
+
+ def sidecar(self, name, obj):
+ """Write a per-item artifact (e.g. an agentic turn log) next to items.jsonl."""
+ path = os.path.join(self.dir, safe_label(name) + ".json")
+ with open(path, "w") as f:
+ json.dump(obj, f, indent=2, default=str)
+ return os.path.basename(path)
+
+ def finish(self, summary=None, *, complete=True):
+ if summary is not None:
+ with open(os.path.join(self.dir, "summary.json"), "w") as f:
+ json.dump(summary, f, indent=2, default=str)
+ self.run["ended_at"] = time.strftime("%Y-%m-%dT%H:%M:%S")
+ self.run["complete"] = complete
+ self.run["n_rows"] = self.n_rows
+ self._write_run()
+ return self.dir
+
+
+def _read(items_path):
+ rows = []
+ if os.path.exists(items_path):
+ with open(items_path) as f:
+ rows = [json.loads(line) for line in f if line.strip()]
+ for r in rows: # rows stored before a status rule existed get it on read
+ r["status"] = effective_status(r)
+ return rows
+
+
+def dedupe(rows):
+ """Keep, per (run_id, item_id, sample_idx), the last non-infra row else the last row."""
+ best = {}
+ order = []
+ for r in rows:
+ k = (r.get("run_id"), r.get("item_id"), r.get("sample_idx", 0))
+ cur = best.get(k)
+ if cur is None:
+ order.append(k)
+ best[k] = r
+ elif not is_infra(r.get("status")) or is_infra(cur.get("status")):
+ best[k] = r
+ return [best[k] for k in order]
+
+
+def load_runs(instruments=None, lanes=None, include_incomplete=False):
+ """[(run_json, rows)] for every run dir under the results root (rows not deduped)."""
+ out = []
+ for dirpath, _dirs, files in sorted(os.walk(RESULTS_DIR)):
+ if "run.json" not in files or "items.jsonl" not in files:
+ continue
+ with open(os.path.join(dirpath, "run.json")) as f:
+ run = json.load(f)
+ if not include_incomplete and not run.get("complete"):
+ continue
+ if instruments and run.get("instrument") not in instruments:
+ continue
+ if lanes and run["lane"]["lane_id"] not in lanes:
+ continue
+ out.append((dict(run, _dir=dirpath), _read(os.path.join(dirpath, "items.jsonl"))))
+ return out
+
+
+def load_rows(instrument, lane_id):
+ """Deduped rows of every complete run of `instrument` on `lane_id`."""
+ return [r for _run, rows in load_runs({instrument}, {lane_id}) for r in dedupe(rows)]
+
+
+# ---------------------------------------------------------------- summaries
+
+def summarize(rows, extra=None):
+ """Totals + per-category counts over deduped rows. extra = {field: fn(rows of a category)}
+ adds instrument-specific per-category values."""
+ def counts(rs):
+ graded = [bool(r["correct"]) for r in rs if r.get("correct") is not None]
+ return {"n": len(rs), "graded": len(graded), "correct": sum(graded),
+ "mean_correct": stats.mean(graded),
+ "mean_score": stats.mean(r["score"] for r in rs if r.get("score") is not None),
+ "truncated": sum(r.get("status") == "truncated" for r in rs),
+ "infra": sum(is_infra(r.get("status")) for r in rs)}
+ by = {}
+ for r in rows:
+ by.setdefault(r.get("category"), []).append(r)
+ cats = {c: dict(counts(by[c]), **{k: fn(by[c]) for k, fn in (extra or {}).items()})
+ for c in sorted(by, key=str)}
+ return dict(counts(rows), by_category=cats)
+
+
+def print_summary(summary, extra=(), log=print):
+ """The per-category table every instrument prints; `extra` names more per-category fields."""
+ def fmt(v):
+ return "-" if v is None else "%.1f" % v if isinstance(v, float) else str(v)
+ log("\n%-30s %5s %9s %6s %5s %5s" % ("category", "n", "correct", "score", "trunc", "infra")
+ + "".join(" %*s" % (max(8, len(k)), k) for k in extra))
+ for cat, c in list(summary["by_category"].items()) + [("TOTAL", summary)]:
+ score = "-" if c["mean_score"] is None else "%.3f" % c["mean_score"]
+ log("%-30s %5d %4d/%-4d %6s %5d %5d" % (cat, c["n"], c["correct"], c["graded"], score,
+ c["truncated"], c["infra"])
+ + "".join(" %*s" % (max(8, len(k)), fmt(c.get(k))) for k in extra))
+
+
+def print_report(instrument, extra=None):
+ """`<instrument> report`: the summary over every complete run of the active lane."""
+ print_summary(summarize(load_rows(instrument, lane_mod.current().lane_id), extra), extra or ())
+
+
+# ---------------------------------------------------------------- the run driver
+
+def add_run_args(p, samples=1, concurrency=1):
+ """The CONTRACT.md `run` flags."""
+ p.add_argument("--samples", type=int, default=samples)
+ p.add_argument("--concurrency", type=int, default=concurrency)
+ p.add_argument("--items", default="", help="comma-separated item ids")
+ p.add_argument("--resume", default=None, metavar="RUN_DIR")
+
+
+def run_args(ns, **more):
+ """The args a `run` records in run.json (see add_run_args)."""
+ return dict(samples=ns.samples, concurrency=ns.concurrency, items=ns.items, **more)
+
+
+_print_lock = threading.Lock()
+
+
+def call_attempt(store, lane, item_id, sample_idx, category, messages, grade, fields=None,
+ **call_kw):
+ """One model call -> one row. grade(resp) -> row fields (correct, score, ...). A failed call
+ is recorded under its CallError label (any other exception: harness_error, as is a grade()
+ that raises); budget_stop is recorded and re-raised so the run stops."""
+ row = dict(fields or {}, item_id=item_id, sample_idx=sample_idx, category=category)
+ t0, err = time.time(), None
+ try:
+ resp, dt = client.call_model(messages, item_id=item_id, run_id=store.run_id, lane=lane,
+ **call_kw)
+ row.update(client.meta(resp, dt))
+ try:
+ row.update(grade(resp))
+ except Exception as e: # noqa: BLE001 — a grader bug is not a model failure
+ row.update(client.error_meta(e, dt), correct=None)
+ except Exception as e: # noqa: BLE001 — one bad item must not kill the run
+ err = e
+ row.update(client.error_meta(e, time.time() - t0))
+ row = store.add(**row)
+ with _print_lock:
+ print(" %-24s #%d %-4s %-12s %ss ctok=%s" % (
+ item_id, sample_idx, {True: "PASS", False: "FAIL"}.get(row["correct"], "-"),
+ row["status"], row.get("wall_s"), row.get("completion_tokens")), flush=True)
+ if isinstance(err, client.CallError) and err.label() == "budget_stop":
+ raise err
+ return row
+
+
+def run_attempts(instrument, args, plan, attempt, *, resume=None, lane=None, extra=None,
+ log=print):
+ """Run every (item, sample) not yet done -> (store, summary).
+
+ args what the run records in run.json: samples, concurrency, items (ids, list or comma
+ string; None = all) + instrument settings. --resume restores them from run.json
+ (only concurrency follows the command line) and refuses a changed item_set.
+ plan plan(args) -> (item_set, [(item_id, payload), ...]) for the whole set
+ attempt attempt(store, lane, payload, sample_idx) records one row; a client.CallError
+ escaping it (budget_stop) stops the run after the attempts in flight
+ extra per-category summary fields (see summarize)
+ """
+ lane = lane or lane_mod.current()
+ if not resume and instrument != "conformance":
+ from bench.tasks import conformance # preflight: rule out non-model problems first
+ conformance.require(lane, log)
+ store = RunStore.resume(resume, lane=lane) if resume else None
+ if store and store.instrument != instrument:
+ raise SystemExit(f"resume: {resume} is a {store.instrument!r} run, not {instrument!r}; "
+ "pass a run dir of this instrument.")
+ if store:
+ args = dict(store.run.get("args") or {}, concurrency=args.get("concurrency"))
+ iset, items = plan(args)
+ want = args.get("items")
+ want = set(want.split(",") if isinstance(want, str) else want or ()) - {""}
+ unknown = sorted(want - {iid for iid, _ in items})
+ if unknown:
+ raise SystemExit(f"unknown item ids {unknown}; pass ids of this instrument's item set.")
+ if store is None:
+ store = RunStore(instrument, item_set=iset, args=args, lane=lane)
+ elif store.run.get("item_set") != iset:
+ raise SystemExit(f"resume: run item_set {store.run.get('item_set')} != current {iset}; "
+ "start a new run instead of mixing definitions.")
+ done = store.done_keys()
+ jobs = [(p, k) for iid, p in items if not want or iid in want
+ for k in range(args.get("samples") or 1) if (iid, k) not in done]
+ conc = max(1, min(args.get("concurrency") or lane.max_concurrency, lane.max_concurrency))
+ log(f"{instrument}: run {store.run_id} lane={lane.lane_id} item_set={iset} "
+ f"attempts={len(jobs)} (skipping {len(done)} done) concurrency={conc}\n dir: {store.dir}")
+ stop = threading.Event()
+
+ def work(job):
+ if not stop.is_set():
+ try:
+ attempt(store, lane, *job)
+ except client.CallError:
+ stop.set()
+
+ complete = False
+ try:
+ if conc == 1: # in the main thread, so Ctrl-C stops the attempt in flight
+ for job in jobs:
+ work(job)
+ else:
+ with ThreadPoolExecutor(max_workers=conc) as ex:
+ list(ex.map(work, jobs))
+ complete = not stop.is_set()
+ finally:
+ summary = summarize(store.rows(), extra)
+ summary["stopped"] = "budget_stop" if stop.is_set() else None if complete else "interrupted"
+ store.finish(summary, complete=complete)
+ print_summary(summary, tuple(extra or ()), log)
+ log(f"results: {store.dir}" if complete else
+ f"BUDGET STOP: run incomplete; resume with --resume {store.dir}")
+ return store, summary
diff --git a/bench/core/runners.py b/bench/core/runners.py
index 2521c3c..401bb4a 100644
--- a/bench/core/runners.py
+++ b/bench/core/runners.py
@@ -1,44 +1,87 @@
-"""Language runners — compile + execute model output against hidden tests.
-
-Each runner takes a task dict (id, lang, symptom, buggy, fix, test) and
-model-generated code, writes it to a fresh temp dir, runs the real toolchain,
-and returns (passed: bool, detail: str).
-
-Supported languages: Go, Rust, TypeScript (via bun), Python, Swift (if xcrun
-available). The coding-suite tasks reference these by their runner key.
-
-Adding a new language: add a `run_<lang>(task, code)` function here and
-register it in RUNNERS.
+"""Language runners: compile + run model code against a task's hidden test.
+
+run_<lang>(task, code, workdir) -> (passed, detail): passed is True / False, or None when the
+check could not run for infra reasons (toolchain missing; callers record status "skipped");
+detail is the tail of the toolchain output. Work dirs are work/<run_id>/<item>-<sample>/
+(BENCH_WORK_DIR overrides work/); every subprocess runs in its own session and the whole
+process group is killed on timeout, so a runaway test binary cannot outlive the run.
+Supported: Go, Rust, TypeScript (bun), Swift (macOS with xcrun), Python (python3), shell (bash;
+items stay bash-3.2-safe for macOS), SQL (sqlite3: the task's fixture, then the model's query; CSV
+output compared to task["expect"], as sorted lines unless task["ordered"]); register new ones in
+RUNNERS.
"""
import os
import re
+import shutil
+import signal
import subprocess
-WORK = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "work")
-RUN_TIMEOUT = 120 # seconds per compile+run
+WORK = os.environ.get("BENCH_WORK_DIR") or os.path.join(
+ os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "work")
+RUN_TIMEOUT = 120 # seconds per compile / run step
+AGENT_ENV = ("CLAUDECODE", "AGENT", "REPL_ID") # stripped from every run, see tools.AGENT_ENV
+
+_TOOLS = {"go": "go", "rust": "rustc", "ts": "bun", "python": "python3", "sh": "bash", "sql": "sqlite3"}
+
+
+def work_dir(run_id, item_id, sample_idx=0):
+ """work/<run_id>/<item_id>-<sample_idx>/ (not created)."""
+ safe = re.sub(r"[^A-Za-z0-9._-]", "_", str(item_id))
+ return os.path.join(WORK, str(run_id), "%s-%s" % (safe, sample_idx))
-def _freshdir(task_id, work=WORK):
- d = os.path.join(work, task_id)
- subprocess.run(["rm", "-rf", d])
+def _freshdir(task_id, workdir=None):
+ d = workdir or os.path.join(WORK, task_id)
+ shutil.rmtree(d, ignore_errors=True)
os.makedirs(d, exist_ok=True)
return d
-def _sh(cmd, cwd, env=None):
- p = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True,
- timeout=RUN_TIMEOUT, env=env)
- return p.returncode, (p.stdout + "\n" + p.stderr).strip()
+def _write(path, text):
+ with open(path, "w") as f:
+ f.write(text)
-def run_go(task, code):
- d = _freshdir(task["id"])
+def _sh(cmd, cwd, env=None, timeout=None):
+ """Run in a new session; on timeout kill the whole process group, then raise
+ subprocess.TimeoutExpired."""
+ timeout = RUN_TIMEOUT if timeout is None else timeout
+ env = {k: v for k, v in (os.environ if env is None else env).items() if k not in AGENT_ENV}
+ p = subprocess.Popen(cmd, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
+ text=True, start_new_session=True)
+ try:
+ out, err = p.communicate(timeout=timeout)
+ except subprocess.TimeoutExpired:
+ try:
+ os.killpg(p.pid, signal.SIGKILL)
+ except (ProcessLookupError, PermissionError):
+ pass
+ try:
+ p.communicate(timeout=10)
+ except Exception: # noqa: BLE001 — pipes may be held by orphans; we already killed the group
+ pass
+ raise
+ return p.returncode, (out + "\n" + err).strip()
+
+
+def _missing(lang):
+ tool = _TOOLS.get(lang)
+ if tool and shutil.which(tool) is None:
+ return "SKIP: %s not found on PATH" % tool
+ return None
+
+
+def run_go(task, code, workdir=None):
+ miss = _missing("go")
+ if miss:
+ return None, miss
+ d = _freshdir(task["id"], workdir)
code = re.sub(r'^\s*package\s+\w+', 'package solution', code, count=1, flags=re.M)
if not re.search(r'^\s*package\s+', code, flags=re.M):
code = "package solution\n\n" + code
- open(os.path.join(d, "solution.go"), "w").write(code)
- open(os.path.join(d, "solution_test.go"), "w").write(task["test"])
- open(os.path.join(d, "go.mod"), "w").write("module bench\n\ngo 1.26\n")
+ _write(os.path.join(d, "solution.go"), code)
+ _write(os.path.join(d, "solution_test.go"), task["test"])
+ _write(os.path.join(d, "go.mod"), "module bench\n\ngo 1.26\n")
try:
rc, out = _sh(["go", "test", "./..."], d)
except subprocess.TimeoutExpired:
@@ -46,13 +89,15 @@ def run_go(task, code):
return rc == 0, out[-1500:]
-def run_rust(task, code):
- d = _freshdir(task["id"])
+def run_rust(task, code, workdir=None):
+ miss = _missing("rust")
+ if miss:
+ return None, miss
+ d = _freshdir(task["id"], workdir)
src = code + "\n\n" + task["test"]
- open(os.path.join(d, "solution.rs"), "w").write(src)
+ _write(os.path.join(d, "solution.rs"), src)
try:
- rc, out = _sh(["rustc", "--edition", "2021", "--test",
- "solution.rs", "-o", "tb"], d)
+ rc, out = _sh(["rustc", "--edition", "2021", "--test", "solution.rs", "-o", "tb"], d)
if rc != 0:
return False, "COMPILE:\n" + out[-1500:]
rc, out = _sh([os.path.join(d, "tb")], d)
@@ -61,10 +106,13 @@ def run_rust(task, code):
return rc == 0, out[-1500:]
-def run_ts(task, code):
- d = _freshdir(task["id"])
- open(os.path.join(d, "solution.ts"), "w").write(code)
- open(os.path.join(d, "runtests.ts"), "w").write(task["test"])
+def run_ts(task, code, workdir=None):
+ miss = _missing("ts")
+ if miss:
+ return None, miss
+ d = _freshdir(task["id"], workdir)
+ _write(os.path.join(d, "solution.ts"), code)
+ _write(os.path.join(d, "runtests.ts"), task["test"])
try:
rc, out = _sh(["bun", "run", "runtests.ts"], d)
except subprocess.TimeoutExpired:
@@ -72,42 +120,33 @@ def run_ts(task, code):
return rc == 0, out[-1500:]
-def run_python(task, code):
- d = _freshdir(task["id"])
- open(os.path.join(d, "solution.py"), "w").write(code)
- open(os.path.join(d, "test_solution.py"), "w").write(task["test"])
- try:
- rc, out = _sh([os.sys.executable, "test_solution.py"], d)
- except subprocess.TimeoutExpired:
- return False, "TIMEOUT"
- return rc == 0, out[-1500:]
-
-
_SWIFT_SDK = None
+
def _swift_env():
+ """(env, sdk_path); sdk is "" when xcrun/Swift is unavailable."""
global _SWIFT_SDK
env = {k: v for k, v in os.environ.items() if k != "SDKROOT"}
if _SWIFT_SDK is None:
try:
p = subprocess.run(["xcrun", "--sdk", "macosx", "--show-sdk-path"],
- capture_output=True, text=True, env=env)
- _SWIFT_SDK = p.stdout.strip()
- except FileNotFoundError:
+ capture_output=True, text=True, env=env, timeout=60)
+ _SWIFT_SDK = p.stdout.strip() if p.returncode == 0 else ""
+ except (FileNotFoundError, subprocess.TimeoutExpired):
_SWIFT_SDK = ""
return env, _SWIFT_SDK
-def run_swift(task, code):
- d = _freshdir(task["id"])
- open(os.path.join(d, "solution.swift"), "w").write(code)
- open(os.path.join(d, "main.swift"), "w").write(task["test"])
+def run_swift(task, code, workdir=None):
env, sdk = _swift_env()
if not sdk:
- return False, "SKIP: xcrun/Swift not available on this platform"
+ return None, "SKIP: xcrun/Swift not available on this platform"
+ d = _freshdir(task["id"], workdir)
+ _write(os.path.join(d, "solution.swift"), code)
+ _write(os.path.join(d, "main.swift"), task["test"])
try:
- rc, out = _sh(["xcrun", "swiftc", "solution.swift", "main.swift",
- "-sdk", sdk, "-o", "bin"], d, env=env)
+ rc, out = _sh(["xcrun", "swiftc", "solution.swift", "main.swift", "-sdk", sdk,
+ "-o", "bin"], d, env=env)
if rc != 0:
return False, "COMPILE:\n" + out[-1500:]
rc, out = _sh([os.path.join(d, "bin")], d, env=env)
@@ -116,20 +155,76 @@ def run_swift(task, code):
return rc == 0, out[-1500:]
+def run_python(task, code, workdir=None):
+ miss = _missing("python")
+ if miss:
+ return None, miss
+ d = _freshdir(task["id"], workdir)
+ _write(os.path.join(d, "solution.py"), code)
+ _write(os.path.join(d, "test_solution.py"), task["test"])
+ try:
+ rc, out = _sh(["python3", "-B", "test_solution.py"], d)
+ except subprocess.TimeoutExpired:
+ return False, "TIMEOUT"
+ return rc == 0, out[-1500:]
+
+
+def run_sh(task, code, workdir=None):
+ miss = _missing("sh")
+ if miss:
+ return None, miss
+ d = _freshdir(task["id"], workdir)
+ _write(os.path.join(d, "solution.sh"), code)
+ _write(os.path.join(d, "test.sh"), task["test"])
+ try:
+ rc, out = _sh(["bash", "test.sh"], d)
+ except subprocess.TimeoutExpired:
+ return False, "TIMEOUT"
+ return rc == 0, out[-1500:]
+
+
+def run_sql(task, code, workdir=None):
+ miss = _missing("sql")
+ if miss:
+ return None, miss
+ d = _freshdir(task["id"], workdir)
+ _write(os.path.join(d, "fixture.sql"), task["fixture"])
+ try:
+ rc, out = _sh(["sqlite3", "-batch", "-bail", os.path.join(d, "db.sqlite"), ".read fixture.sql"], d)
+ if rc != 0:
+ return False, "FIXTURE:\n" + out[-1500:]
+ p = subprocess.run(["sqlite3", "-batch", "-bail", "-csv", os.path.join(d, "db.sqlite")],
+ input=code, capture_output=True, text=True, cwd=d, timeout=RUN_TIMEOUT)
+ except subprocess.TimeoutExpired:
+ return False, "TIMEOUT"
+ if p.returncode != 0:
+ return False, "SQL ERROR:\n" + (p.stdout + p.stderr)[-1500:]
+ got = [ln for ln in p.stdout.replace("\r", "").split("\n") if ln.strip()]
+ want = [ln for ln in task["expect"].strip().split("\n") if ln.strip()]
+ if not task.get("ordered"):
+ got, want = sorted(got), sorted(want)
+ if got == want:
+ return True, "OK"
+ return False, "got:\n%s\nwant:\n%s" % ("\n".join(got)[:700], "\n".join(want)[:700])
+
+
RUNNERS = {
"go": run_go,
"rust": run_rust,
"ts": run_ts,
- "python": run_python,
"swift": run_swift,
+ "python": run_python,
+ "sh": run_sh,
+ "sql": run_sql,
}
def extract_code(content):
- """Return the most plausible code block from a chat content string."""
+ """Return the most plausible code block from a chat content string (longest fenced
+ block, else the whole text)."""
if not content:
return ""
blocks = re.findall(r"```[a-zA-Z0-9_+#.-]*\n(.*?)```", content, re.DOTALL)
if blocks:
return max(blocks, key=len).strip()
- return content.strip()
\ No newline at end of file
+ return content.strip()
diff --git a/bench/core/stats.py b/bench/core/stats.py
new file mode 100644
index 0000000..a068e01
--- /dev/null
+++ b/bench/core/stats.py
@@ -0,0 +1,122 @@
+"""Small, dependency-free statistics for the reporting tools (Python 3.9 stdlib only).
+
+Unit of analysis is the ITEM: samples of one item are averaged first, then items are
+resampled / paired. Everything here is deterministic (explicit seeds).
+
+McNemar pairing (documented choice): each lane's per-item pass-rate is reduced to a binary
+"majority" outcome (rate > 0.5 pass, rate < 0.5 fail); items with an exact 0.5 tie in either
+lane are dropped from the McNemar table (they are neither clearly pass nor fail). With one
+sample per item this is the classic per-item McNemar.
+"""
+import math
+import random
+
+
+def mean(xs):
+ xs = list(xs)
+ return sum(xs) / len(xs) if xs else None
+
+
+def median(xs):
+ xs = sorted(xs)
+ n = len(xs)
+ if not n:
+ return None
+ return xs[n // 2] if n % 2 else (xs[n // 2 - 1] + xs[n // 2]) / 2
+
+
+def percentile(sorted_xs, q):
+ """Linear-interpolated percentile of an already sorted list, q in [0,1]."""
+ n = len(sorted_xs)
+ if n == 1:
+ return sorted_xs[0]
+ pos = q * (n - 1)
+ lo = int(math.floor(pos))
+ hi = min(lo + 1, n - 1)
+ return sorted_xs[lo] + (sorted_xs[hi] - sorted_xs[lo]) * (pos - lo)
+
+
+def bootstrap_ci(values, n_boot=2000, seed=0, alpha=0.05):
+ """Percentile bootstrap CI of the mean over items. Returns (lo, hi) or None if empty."""
+ values = list(values)
+ n = len(values)
+ if n == 0:
+ return None
+ if n == 1:
+ return (values[0], values[0])
+ rng = random.Random(seed)
+ means = []
+ for _ in range(n_boot):
+ s = 0.0
+ for _ in range(n):
+ s += values[rng.randrange(n)]
+ means.append(s / n)
+ means.sort()
+ return (percentile(means, alpha / 2), percentile(means, 1 - alpha / 2))
+
+
+def wilson(k, n, z=1.959964):
+ """Wilson score interval for k successes of n. Returns (lo, hi) or None if n == 0."""
+ if n <= 0:
+ return None
+ p = k / n
+ z2 = z * z
+ denom = 1 + z2 / n
+ centre = (p + z2 / (2 * n)) / denom
+ half = z * math.sqrt(p * (1 - p) / n + z2 / (4 * n * n)) / denom
+ return (max(0.0, centre - half), min(1.0, centre + half))
+
+
+def mcnemar_exact(b, c):
+ """Exact two-sided McNemar p-value from the discordant counts b (A pass/B fail) and
+ c (A fail/B pass): two-sided binomial test of min(b,c) ~ Bin(b+c, 0.5)."""
+ n = b + c
+ if n == 0:
+ return 1.0
+ k = min(b, c)
+ tail = sum(math.comb(n, i) for i in range(k + 1)) / (2 ** n)
+ return min(1.0, 2 * tail)
+
+
+def paired_items(a, b):
+ """Item ids present in both dicts (item_id -> value), sorted."""
+ return sorted(set(a) & set(b))
+
+
+def paired_delta(a, b, n_boot=2000, seed=0):
+ """Delta (a - b) on the intersection of item_ids graded in both lanes.
+ a, b: dict item_id -> per-item value (None values are ignored).
+ Returns dict(n, mean_delta, ci_lo, ci_hi, mean_a, mean_b); n == 0 -> deltas None."""
+ ids = [i for i in paired_items(a, b) if a[i] is not None and b[i] is not None]
+ if not ids:
+ return {"n": 0, "mean_delta": None, "ci_lo": None, "ci_hi": None,
+ "mean_a": None, "mean_b": None}
+ d = [a[i] - b[i] for i in ids]
+ ci = bootstrap_ci(d, n_boot=n_boot, seed=seed)
+ return {"n": len(ids), "mean_delta": mean(d), "ci_lo": ci[0], "ci_hi": ci[1],
+ "mean_a": mean(a[i] for i in ids), "mean_b": mean(b[i] for i in ids)}
+
+
+def mcnemar_items(a, b):
+ """McNemar over per-item pass-rates (see module docstring for pairing).
+ Returns dict(b, c, n_both_pass, n_both_fail, n_tied_dropped, n, p).
+ b = A pass & B fail, c = A fail & B pass."""
+ nb = nc = both = neither = tied = 0
+ for i in paired_items(a, b):
+ x, y = a[i], b[i]
+ if x is None or y is None:
+ continue
+ if x == 0.5 or y == 0.5:
+ tied += 1
+ continue
+ pa, pb = x > 0.5, y > 0.5
+ if pa and pb:
+ both += 1
+ elif pa:
+ nb += 1
+ elif pb:
+ nc += 1
+ else:
+ neither += 1
+ return {"b": nb, "c": nc, "n_both_pass": both, "n_both_fail": neither,
+ "n_tied_dropped": tied, "n": nb + nc + both + neither, "p": mcnemar_exact(nb, nc)}
diff --git a/bench/core/tools.py b/bench/core/tools.py
index 503a2a6..ab0af50 100644
--- a/bench/core/tools.py
+++ b/bench/core/tools.py
@@ -1,205 +1,1008 @@
-"""File/exec tool implementations for agentic build benches.
+"""Workspace, tool implementations, gate helpers and the tool loop shared by the agentic
+instruments (agentic-fix's hard tier, agentic-multitask, sleuth).
-These are the tools the agent can call during a multi-turn build loop:
-list_files, read_file, write_file, edit_file, search, run_build, run_test,
-run_shell. They operate on a work dir set via `set_work_dir()`.
+Workspace one per attempt: its own work dir (work/<run_id>/<item_id>-<sample_idx>/), its own
+ subprocess bookkeeping and environment, so attempts can run concurrently. Every
+ subprocess (tool AND gate) runs in a new session and is killed as a process group
+ on timeout and when the attempt ends (servers the model started in the background
+ included). Each also carries LLM_BENCH_WS=<per-workspace token>, so anything that
+ left its group (`setsid ./server &`) is found through /proc and killed too (Linux;
+ elsewhere only the groups).
+Toolset the OpenAI `tools` schema + implementations for one task. build_toolset() makes the
+ work-dir toolset with per-language run_build/run_test (GO_/RUST_/TS_TOOLSET).
+agent_loop() the multi-turn loop: call the model, execute tool calls, append results, until
+ DONE / give-up / turn cap / CallError.
-The tool SCHEMA (OpenAI function-calling format) is in TOOLS; the
-implementations are in TOOL_IMPLS. Instruments that want a different tool
-set (e.g. agentic_bench_v1 uses read-only exploration + submit_fix) define
-their own and don't import these.
+Hygiene rules
+- Tool arguments must parse to a JSON object (a dict passed by the server is accepted); anything
+ else gets an error result and is NOT executed. On a length-cut turn such a call gets
+ CUT_OFF_MSG instead (the client repairs its arguments to "{}" in the next request).
+- Every implementation runs inside try/except: a tool returns an error string, never kills the run.
+- Paths must be non-empty, relative, and resolve (symlinks included) inside the work dir.
+- Reads are binary-safe: a NUL byte in the first 8 KiB is reported, not dumped; search skips them.
+- Tool subprocesses get stdin=/dev/null and write to temp files, not pipes, so a background
+ child holding the stream open can't stall the call until timeout.
+
+DONE (said_done): a no-tool turn whose answer text (inline <think> removed) contains the whole
+word "done" in any case, not directly preceded by `not`, `never` or a word ending in `n't`
+(optionally with one of yet/quite/fully/really/completely/all in between). "DONE", "Done.",
+"`DONE`" count; "abandoned", "undone", "not done", "isn't done yet", "haven't done" don't.
"""
+import json
import os
import re
+import shlex
+import signal
+import socket
+import sqlite3
import subprocess
-import shutil
+import tempfile
+import threading
+import time
+import urllib.parse
+import urllib.request
+import uuid
+
+from bench.core import client
+
+LLM_BENCH = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+WORK_ROOT = os.environ.get("BENCH_WORK_DIR") or os.path.join(LLM_BENCH, "work")
+# Set when the bench is started from an AI agent (Claude Code: CLAUDECODE). Tools change their output
+# for agents (bun 1.3 drops its per-test "(pass)" lines), so graded subprocesses never see them.
+AGENT_ENV = ("CLAUDECODE", "AGENT", "REPL_ID")
+
+RESULT_CAP = 6000 # tool results longer than this are truncated before going to the model
+
+CUT_OFF_MSG = ("ERROR: your output hit the max_tokens limit and this call was cut off; it was "
+ "NOT executed. Re-issue it, splitting large files into several smaller "
+ "write_file calls.")
+
+BINARY_SNIFF = 8192
+
+
+class ToolError(Exception):
+ """A tool refused its input; the message goes back to the model as `ERROR: <msg>`."""
+
+
+class InfraError(Exception):
+ """The sandbox under a tool failed (not the model's command): the attempt is infra, ungraded."""
+
+
+class Symlink(str):
+ """A materialize() value: a symlink to this target instead of a file."""
+
+
+class ToolResult:
+ """A tool result that can also end the loop (agentic-fix's submit_fix)."""
+
+ def __init__(self, text, stop=False):
+ self.text = text
+ self.stop = stop
+
+
+# ============================================================ ports
+
+_reserved = set()
+_port_lock = threading.Lock()
+
+
+def _listening(port):
+ for host in ("127.0.0.1", "::1"):
+ fam = socket.AF_INET6 if ":" in host else socket.AF_INET
+ try:
+ s = socket.socket(fam, socket.SOCK_STREAM)
+ except OSError:
+ continue
+ s.settimeout(0.3)
+ try:
+ s.connect((host, port))
+ return True
+ except OSError:
+ pass
+ finally:
+ s.close()
+ return False
+
+
+def port_is_free(port):
+ """Nothing listens on loopback (v4 or v6) and the port can be bound on all interfaces.
+ SO_REUSEADDR is set for the bind probe so TIME_WAIT leftovers don't count as busy."""
+ if _listening(port):
+ return False
+ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ try:
+ s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ s.bind(("", port))
+ return True
+ except OSError:
+ return False
+ finally:
+ s.close()
+
+
+def free_port():
+ """An OS-assigned free port, never handed out twice in this process (concurrent items)."""
+ with _port_lock:
+ for _ in range(50):
+ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ s.bind(("", 0))
+ p = s.getsockname()[1]
+ s.close()
+ if p not in _reserved and port_is_free(p):
+ _reserved.add(p)
+ return p
+ raise RuntimeError("could not find a free port")
+
+
+def release_port(port):
+ with _port_lock:
+ _reserved.discard(port)
+
+
+def wait_port_free(port, timeout=5.0):
+ end = time.time() + timeout
+ while True:
+ if port_is_free(port):
+ return True
+ if time.time() >= end:
+ return False
+ time.sleep(0.1)
+
+
+# ============================================================ subprocesses
+
+class RunResult:
+ def __init__(self, rc, out, err, timed_out, timeout, dt):
+ self.rc = rc
+ self.out = out
+ self.err = err
+ self.timed_out = timed_out
+ self.timeout = timeout
+ self.dt = dt
+
+ @property
+ def ok(self):
+ return self.rc == 0 and not self.timed_out
+
+ def text(self):
+ """The format the model sees."""
+ if self.timed_out:
+ return f"TIMEOUT after {self.timeout}s"
+ return f"exit={self.rc}\n{(self.out + chr(10) + self.err).strip()}"
+
+ def combined(self):
+ return (self.out + self.err).strip()
+
+
+def _killpg(pgid, sig):
+ try:
+ os.killpg(pgid, sig)
+ return True
+ except (ProcessLookupError, PermissionError):
+ return False
+
+
+def group_alive(pgid):
+ try:
+ os.killpg(pgid, 0)
+ return True
+ except ProcessLookupError:
+ return False
+ except PermissionError:
+ return True
+
+
+MARKER_ENV = "LLM_BENCH_WS"
+
+
+def marked_pids(marker):
+ """PIDs (ours, not this process) whose environment carries LLM_BENCH_WS=<marker>. Linux /proc
+ only; [] elsewhere or for processes we can't read."""
+ needle = f"{MARKER_ENV}={marker}".encode()
+ out = []
+ try:
+ names = os.listdir("/proc")
+ except OSError:
+ return out
+ for name in names:
+ if not name.isdigit() or int(name) == os.getpid():
+ continue
+ try:
+ with open(f"/proc/{name}/environ", "rb") as f:
+ if needle in f.read().split(b"\0"):
+ out.append(int(name))
+ except OSError:
+ continue
+ return out
+
+
+def kill_marked(marker, grace=1.0):
+ """SIGTERM every process carrying the marker, SIGKILL what's left after `grace`. Returns the
+ PIDs still alive after that (should be empty)."""
+ pids = marked_pids(marker)
+ for sig in (signal.SIGTERM, signal.SIGKILL):
+ for pid in pids:
+ try:
+ os.kill(pid, sig)
+ except (ProcessLookupError, PermissionError):
+ pass
+ end = time.time() + (grace if sig == signal.SIGTERM else 2.0)
+ while pids and time.time() < end:
+ time.sleep(0.05)
+ pids = [p for p in pids if _pid_running(p)]
+ if not pids:
+ break
+ return pids
+
+
+def _pid_running(pid):
+ """Alive and not a zombie (a reparented child stays a zombie until init reaps it)."""
+ try:
+ with open(f"/proc/{pid}/stat", "rb") as f:
+ return f.read().rsplit(b")", 1)[1].split()[0] != b"Z"
+ except (OSError, IndexError):
+ return False
+
+
+def _read_tmp(f):
+ try:
+ f.flush()
+ f.seek(0)
+ return f.read().decode("utf-8", errors="replace")
+ finally:
+ f.close()
+
+
+class Workspace:
+ """Work dir + subprocess bookkeeping for one attempt. Use as a context manager or call
+ close(); close() kills every process group started through it."""
+
+ def __init__(self, path, env=None):
+ self.dir = os.path.abspath(path)
+ os.makedirs(self.dir, exist_ok=True)
+ self.env_extra = dict(env or {})
+ self.state = {} # per-attempt scratch for instruments (fix: submission, reads)
+ self.marker = uuid.uuid4().hex # LLM_BENCH_WS: finds descendants that left their group
+ self._groups = {} # pgid -> Popen (leaders we started)
+ self._lock = threading.Lock()
+ self.ports = []
+ self.cleanups = [] # callables run at close(), after the process groups die
+
+ # ---- env / files -----------------------------------------------------------
+ def env(self, extra=None):
+ e = {k: v for k, v in os.environ.items() if k not in AGENT_ENV}
+ for src in (self.env_extra, extra or {}):
+ for k, v in src.items():
+ if v is None:
+ e.pop(k, None)
+ else:
+ e[k] = str(v)
+ e[MARKER_ENV] = self.marker
+ return e
+
+ def materialize(self, files):
+ return materialize(files, self.dir)
+
+ def allocate_port(self):
+ p = free_port()
+ self.ports.append(p)
+ return p
+
+ # ---- processes ---------------------------------------------------------------
+ def _prune(self):
+ """Forget groups observed empty, so a recycled PGID is never signalled later.
+ (A PGID can't be reused while its group has members; it can be once it is empty.)"""
+ with self._lock:
+ for g, p in list(self._groups.items()):
+ if p.poll() is not None and not group_alive(g):
+ del self._groups[g]
+
+ def _track(self, proc):
+ self._prune()
+ with self._lock:
+ self._groups[proc.pid] = proc
+
+ def live_groups(self):
+ self._prune()
+ with self._lock:
+ return list(self._groups)
+
+ def run(self, cmd, timeout, env=None):
+ """Run `cmd` (str -> sh -c; list -> argv) in the work dir, in its own session.
+ On timeout the whole process group is SIGKILLed. Background children that outlive
+ the command stay tracked and die at close()."""
+ out_f = tempfile.TemporaryFile()
+ err_f = tempfile.TemporaryFile()
+ t0 = time.time()
+ try:
+ proc = subprocess.Popen(cmd, shell=isinstance(cmd, str), cwd=self.dir,
+ env=self.env(env), stdin=subprocess.DEVNULL,
+ stdout=out_f, stderr=err_f, start_new_session=True)
+ except Exception:
+ out_f.close()
+ err_f.close()
+ raise
+ self._track(proc)
+ timed_out = False
+ try:
+ rc = proc.wait(timeout=timeout)
+ except subprocess.TimeoutExpired:
+ timed_out = True
+ _killpg(proc.pid, signal.SIGKILL)
+ rc = proc.wait()
+ self._prune()
+ return RunResult(None if timed_out else rc, _read_tmp(out_f), _read_tmp(err_f),
+ timed_out, timeout, time.time() - t0)
+
+ def popen(self, argv, env=None):
+ """Start a long-running process (a server under test) in its own session.
+ Output goes to a temp file: read it with proc_output(proc)."""
+ log = tempfile.TemporaryFile()
+ proc = subprocess.Popen(argv, cwd=self.dir, env=self.env(env), stdin=subprocess.DEVNULL,
+ stdout=log, stderr=subprocess.STDOUT, start_new_session=True)
+ proc._bench_log = log
+ self._track(proc)
+ return proc
+
+ @staticmethod
+ def proc_output(proc, tail=2000):
+ log = getattr(proc, "_bench_log", None)
+ if log is None or log.closed:
+ return ""
+ try:
+ log.flush()
+ log.seek(0)
+ return log.read().decode("utf-8", errors="replace")[-tail:]
+ except (OSError, ValueError):
+ return ""
-BUILD_TIMEOUT = int(os.environ.get("BUILD_TIMEOUT", "180"))
-TEST_TIMEOUT = int(os.environ.get("TEST_TIMEOUT", "180"))
-SHELL_TIMEOUT = int(os.environ.get("SHELL_TIMEOUT", "60"))
+ def stop(self, proc, grace=5.0):
+ """SIGTERM the group, wait `grace`, then SIGKILL whatever is left of it."""
+ _killpg(proc.pid, signal.SIGTERM)
+ try:
+ proc.wait(timeout=grace)
+ except subprocess.TimeoutExpired:
+ pass
+ _killpg(proc.pid, signal.SIGKILL)
+ try:
+ proc.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ pass
+ log = getattr(proc, "_bench_log", None)
+ if log is not None and not log.closed:
+ log.close()
-_WORK = None
+ def kill_all(self, grace=1.0):
+ """Kill every process group started through this workspace. Returns the pgids that
+ still had live members afterwards (should be empty)."""
+ self._prune()
+ with self._lock:
+ groups = dict(self._groups)
+ live = [g for g in groups if group_alive(g)]
+ for g in live:
+ _killpg(g, signal.SIGTERM)
+ end = time.time() + grace
+ while live and time.time() < end:
+ for g in live:
+ p = groups[g]
+ if p.poll() is None:
+ try:
+ p.wait(timeout=0.05)
+ except subprocess.TimeoutExpired:
+ pass
+ live = [g for g in live if group_alive(g)]
+ if live:
+ time.sleep(0.05)
+ for g in live:
+ _killpg(g, signal.SIGKILL)
+ for p in groups.values():
+ if p.poll() is None:
+ try:
+ p.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ pass
+ log = getattr(p, "_bench_log", None)
+ if log is not None and not log.closed:
+ log.close()
+ end = time.time() + 2.0
+ survivors = [g for g in groups if group_alive(g)]
+ while survivors and time.time() < end: # reparented zombies take a moment to reap
+ time.sleep(0.05)
+ survivors = [g for g in survivors if group_alive(g)]
+ return survivors + kill_marked(self.marker, grace)
-def set_work_dir(d):
- global _WORK
- _WORK = d
+ def close(self):
+ survivors = self.kill_all()
+ for p in self.ports:
+ release_port(p)
+ for fn in self.cleanups:
+ try:
+ fn()
+ except Exception: # noqa: BLE001 — one failed cleanup must not skip the rest
+ pass
+ return survivors
-def get_work_dir():
- return _WORK
+ def __enter__(self):
+ return self
+ def __exit__(self, *exc):
+ self.close()
-def materialize(files, dest=None):
- """Write a dict of {relative_path: content} into a work dir (cleared first)."""
- d = dest or _WORK
- shutil.rmtree(d, ignore_errors=True)
- os.makedirs(d, exist_ok=True)
+
+def materialize(files, dest):
+ """Write {relative_path: str | bytes | Symlink} into dest (cleared first)."""
+ import shutil
+ shutil.rmtree(dest, ignore_errors=True)
+ os.makedirs(dest, exist_ok=True)
for path, content in files.items():
- fp = os.path.join(d, path)
+ fp = os.path.join(dest, path)
os.makedirs(os.path.dirname(fp), exist_ok=True)
- with open(fp, "w") as f:
- f.write(content)
- return d
+ if isinstance(content, Symlink):
+ os.symlink(content, fp)
+ elif isinstance(content, bytes):
+ with open(fp, "wb") as f:
+ f.write(content)
+ else:
+ with open(fp, "w", encoding="utf-8") as f:
+ f.write(content)
+ return dest
+
+
+def prune(work_dir, names=("node_modules", "target", ".next")):
+ """Delete heavy build dirs at the top of a finished work dir (keeps the source)."""
+ import shutil
+ for n in names:
+ p = os.path.join(work_dir, n)
+ if os.path.isdir(p) and not os.path.islink(p):
+ shutil.rmtree(p, ignore_errors=True)
+
+
+# ============================================================ test-count parsing (gates)
+
+_GO_PASS = re.compile(r"^\s*--- PASS: ", re.M)
+_CARGO_RESULT = re.compile(r"test result: \w+\. (\d+) passed")
+
+
+def go_tests_passed(output):
+ """Number of passing tests in `go test -v` output (subtests included)."""
+ return len(_GO_PASS.findall(output or ""))
+
+def cargo_tests_passed(output):
+ """Sum of `N passed` over every `test result:` line of `cargo test` output."""
+ return sum(int(n) for n in _CARGO_RESULT.findall(output or ""))
-def _run(cmd, timeout):
+
+def build_test_gates(ws, toolset, test_cmd, count):
+ """build: the toolset's build command exits 0; test: `test_cmd` exits 0 AND count(output)
+ >= 1 (a suite with zero tests passes vacuously otherwise). -> ({build, test}, detail)"""
+ t = toolset.commands["timeouts"]
+ b = ws.run(toolset.commands["run_build"], t["build"])
+ r = ws.run(test_cmd, t["test"])
+ n = count(r.combined())
+ g, d = {"build": b.ok, "test": r.ok and n >= 1}, {"tests_passed": n}
+ if not b.ok:
+ d["build_tail"] = b.text()[-400:]
+ if not g["test"]:
+ d["test_tail"] = r.text()[-400:]
+ return g, d
+
+
+def go_has_real_app(work_dir):
+ """Not the starter stub: cmd/server/main.go serves HTTP and internal/ has >= 3 packages
+ (build and test pass vacuously on `func main(){}`)."""
+ main_go = os.path.join(work_dir, "cmd", "server", "main.go")
+ internal = os.path.join(work_dir, "internal")
+ if not os.path.isfile(main_go) or not os.path.isdir(internal):
+ return False
+ with open(main_go) as f:
+ src = f.read()
+ return (("ListenAndServe" in src or "http.Server" in src)
+ and sum(os.path.isdir(os.path.join(internal, x)) for x in os.listdir(internal)) >= 3)
+
+
+def _rm_db(path):
+ for p in (path, path + "-wal", path + "-shm"):
+ try:
+ os.remove(p)
+ except OSError:
+ pass
+
+
+def go_web_probe(ws, port, page_ok, form, table, column):
+ """Build ./cmd/server and run it with NOTES_PORT/NOTES_DB; serves = GET / answers 200 with
+ page_ok(html). Then POST `form` to /, GET / again and count the rows of `table` whose
+ `column` = form[column] in the SQLite file.
+ -> (serves, {post_fragment, later_get, db_row} or {} if the POST failed, detail)"""
+ binpath, mark = os.path.join(ws.dir, "server"), form[column]
+ r = ws.run(f"go build -o {shlex.quote(binpath)} ./cmd/server",
+ GO_TOOLSET.commands["timeouts"]["build"])
+ if not r.ok or not os.path.isfile(binpath):
+ return False, {}, {"serves": "go build -o server failed: " + r.text()[-300:]}
+ if port is None or not port_is_free(port):
+ port = ws.allocate_port()
+ d = {"port": port}
+ dbpath = os.path.join(ws.dir, f"bench_{port}.db")
+ _rm_db(dbpath)
+ try:
+ proc = ws.popen([binpath], env={"NOTES_PORT": str(port), "NOTES_DB": dbpath})
+ except Exception as e: # noqa: BLE001
+ return False, {}, dict(d, serves=f"failed to start binary: {e!r}")
try:
- p = subprocess.run(cmd, cwd=_WORK, shell=True, capture_output=True,
- text=True, timeout=timeout)
- except subprocess.TimeoutExpired:
- return f"TIMEOUT after {timeout}s"
- out = (p.stdout + "\n" + p.stderr).strip()
- return f"exit={p.returncode}\n{out}"
+ for _ in range(40):
+ try:
+ with socket.create_connection(("127.0.0.1", port), 0.25):
+ break
+ except OSError:
+ time.sleep(0.25)
+ else:
+ return False, {}, dict(d, serves="binary did not start listening within 10s: "
+ + ws.proc_output(proc, 300))
+ url = f"http://127.0.0.1:{port}/"
+ try:
+ with urllib.request.urlopen(url, timeout=20) as resp:
+ status, html = resp.status, resp.read().decode(errors="replace")
+ except Exception as e: # noqa: BLE001
+ return False, {}, dict(d, serves=f"GET / failed: {e!r}")
+ if status != 200 or not page_ok(html):
+ return False, {}, dict(d, serves=f"GET / -> {status}, page check failed")
+ try:
+ data = urllib.parse.urlencode(form).encode()
+ with urllib.request.urlopen(urllib.request.Request(url, data=data), timeout=20) as resp:
+ post_body = resp.read().decode(errors="replace")
+ except Exception as e: # noqa: BLE001
+ return True, {}, dict(d, persists=f"POST / failed: {e!r}")
+ try:
+ with urllib.request.urlopen(url, timeout=20) as resp:
+ later = mark in resp.read().decode(errors="replace")
+ except Exception as e: # noqa: BLE001
+ later, d["later_get_error"] = False, repr(e)[:200]
+ db_row = False
+ if not os.path.exists(dbpath):
+ d["db_error"] = "no SQLite file at NOTES_DB"
+ else:
+ try:
+ conn = sqlite3.connect(dbpath)
+ try:
+ q = f"SELECT count(*) FROM {table} WHERE {column} = ?"
+ db_row = conn.execute(q, (mark,)).fetchone()[0] > 0
+ finally:
+ conn.close()
+ except Exception as e: # noqa: BLE001
+ d["db_error"] = repr(e)[:200]
+ checks = {"post_fragment": mark in post_body, "later_get": later, "db_row": db_row}
+ d["persists"] = " ".join(f"{k}={v}" for k, v in checks.items())
+ return True, checks, d
+ finally:
+ ws.stop(proc)
+ _rm_db(dbpath)
-def _list_files(args):
- out = []
- for root, dirs, files in os.walk(_WORK):
- dirs[:] = sorted(d for d in dirs if d not in {".git", "node_modules",
- ".next", "target", "dist"})
+# ============================================================ path + file helpers
+
+def resolve_path(ws, p):
+ if not isinstance(p, str) or not p.strip():
+ raise ToolError("path must be a non-empty, work-dir-relative string")
+ if os.path.isabs(p) or p.startswith("~"):
+ raise ToolError(f"path {p!r} is absolute; use a path relative to the work dir")
+ full = os.path.normpath(os.path.join(ws.dir, p))
+ root = os.path.realpath(ws.dir)
+ real = os.path.realpath(full)
+ if real != root and not real.startswith(root + os.sep):
+ raise ToolError(f"path {p!r} is outside the work dir")
+ return full
+
+
+def _is_binary(data):
+ return b"\x00" in data[:BINARY_SNIFF]
+
+
+def _str_arg(args, key, default=None):
+ v = args.get(key, default)
+ if v is None:
+ v = default
+ if not isinstance(v, str):
+ raise ToolError(f"`{key}` must be a string, got {type(v).__name__}")
+ return v
+
+
+def _walk(ws):
+ for root, dirs, files in os.walk(ws.dir):
+ dirs[:] = sorted(d for d in dirs if d not in {".git"})
for f in sorted(files):
full = os.path.join(root, f)
- rel = os.path.relpath(full, _WORK)
- out.append(rel)
- return "\n".join(out)
+ yield full, os.path.relpath(full, ws.dir)
+
+# ============================================================ work-dir tool impls
-def _read_file(args):
+def _list_files(ws, args):
+ return "\n".join(rel for _full, rel in _walk(ws))
+
+
+def _read_file(ws, args):
p = args.get("path", "")
- fp = os.path.join(_WORK, p)
+ if isinstance(p, str) and not p.strip():
+ return f"ERROR: no such file {p!r}. Use list_files."
+ fp = resolve_path(ws, p)
if not os.path.isfile(fp):
return f"ERROR: no such file {p!r}. Use list_files."
- with open(fp) as f:
- return f.read()
+ with open(fp, "rb") as f:
+ data = f.read()
+ if _is_binary(data):
+ return f"ERROR: {p!r} is a binary file ({len(data)} bytes); not shown."
+ return data.decode("utf-8", errors="replace")
-def _write_file(args):
+def _write_file(ws, args):
p = args.get("path", "")
- content = args.get("content", "")
- fp = os.path.join(_WORK, p)
+ content = _str_arg(args, "content", "")
+ fp = resolve_path(ws, p)
+ if os.path.isdir(fp):
+ raise ToolError(f"{p!r} is a directory")
os.makedirs(os.path.dirname(fp), exist_ok=True)
- with open(fp, "w") as f:
+ with open(fp, "w", encoding="utf-8") as f:
f.write(content)
return f"wrote {p} ({len(content)} bytes)"
-def _edit_file(args):
+def _edit_file(ws, args):
p = args.get("path", "")
- old = args.get("old_str", "")
- new = args.get("new_str", "")
- fp = os.path.join(_WORK, p)
+ old = _str_arg(args, "old_str", "")
+ new = _str_arg(args, "new_str", "")
+ fp = resolve_path(ws, p)
if not os.path.isfile(fp):
return f"ERROR: no such file {p!r}."
- with open(fp) as f:
- content = f.read()
+ with open(fp, "rb") as f:
+ data = f.read()
+ try:
+ content = data.decode("utf-8")
+ except UnicodeDecodeError:
+ return f"ERROR: {p!r} is not a UTF-8 text file; use write_file to replace it."
count = content.count(old)
if count == 0:
return f"ERROR: old_str not found in {p}."
if count > 1:
return f"ERROR: old_str appears {count} times in {p}; make it unique."
new_content = content.replace(old, new, 1)
- with open(fp, "w") as f:
+ with open(fp, "w", encoding="utf-8") as f:
f.write(new_content)
return f"edited {p} ({len(old)} -> {len(new)} chars)"
-def _search(args):
- pat = args.get("pattern", "")
+def _search(ws, args):
+ pat = _str_arg(args, "pattern", "")
try:
rx = re.compile(pat)
except re.error as e:
return f"ERROR: bad regex: {e}"
hits = []
- for root, dirs, files in os.walk(_WORK):
- dirs[:] = sorted(d for d in dirs if d not in {".git", "node_modules",
- ".next", "target", "dist"})
- for f in sorted(files):
- full = os.path.join(root, f)
- rel = os.path.relpath(full, _WORK)
- with open(full, errors="replace") as fh:
- for i, line in enumerate(fh, 1):
- if rx.search(line):
- hits.append(f"{rel}:{i}: {line.strip()}")
+ for full, rel in _walk(ws):
+ try:
+ with open(full, "rb") as fh:
+ data = fh.read()
+ except OSError:
+ continue
+ if _is_binary(data):
+ continue
+ for i, line in enumerate(data.decode("utf-8", errors="replace").splitlines(), 1):
+ if rx.search(line):
+ hits.append(f"{rel}:{i}: {line.strip()}")
return "\n".join(hits) if hits else "(no matches)"
-def _run_build(args):
- return _run("go build ./...", BUILD_TIMEOUT)
-
-
-def _run_test(args):
- return _run("go test ./...", TEST_TIMEOUT)
-
-
-def _run_shell(args):
- cmd = args.get("cmd", "")
- if not cmd:
- return "ERROR: empty cmd"
- return _run(cmd, SHELL_TIMEOUT)
-
-
-TOOL_IMPLS = {
- "list_files": _list_files,
- "read_file": _read_file,
- "write_file": _write_file,
- "edit_file": _edit_file,
- "search": _search,
- "run_build": _run_build,
- "run_test": _run_test,
- "run_shell": _run_shell,
-}
-
-TOOLS = [
- {"type": "function", "function": {
- "name": "list_files",
- "description": "List all file paths in the work dir. Returns one path per line.",
- "parameters": {"type": "object", "properties": {}},
- }},
- {"type": "function", "function": {
- "name": "read_file",
- "description": "Return the full contents of one file in the work dir.",
- "parameters": {"type": "object", "properties": {
- "path": {"type": "string", "description": "Project-relative file path"},
- }, "required": ["path"]},
- }},
- {"type": "function", "function": {
- "name": "write_file",
- "description": "Create or overwrite a file in the work dir with the given contents.",
- "parameters": {"type": "object", "properties": {
- "path": {"type": "string"},
- "content": {"type": "string", "description": "Full file contents to write"},
- }, "required": ["path", "content"]},
- }},
- {"type": "function", "function": {
- "name": "edit_file",
- "description": "Apply a patch-style edit: replace the first occurrence of old_str with new_str. Fails if old_str is not found or appears more than once.",
- "parameters": {"type": "object", "properties": {
- "path": {"type": "string"},
- "old_str": {"type": "string", "description": "The exact text to find (must be unique)"},
- "new_str": {"type": "string", "description": "The replacement text"},
- }, "required": ["path", "old_str", "new_str"]},
- }},
- {"type": "function", "function": {
- "name": "search",
- "description": "Regex-search the whole work dir; returns matching path:line: text.",
- "parameters": {"type": "object", "properties": {
- "pattern": {"type": "string"},
- }, "required": ["pattern"]},
- }},
- {"type": "function", "function": {
- "name": "run_build",
- "description": f"Run `go build ./...` in the work dir. Returns exit code + output. Timeout {BUILD_TIMEOUT}s.",
- "parameters": {"type": "object", "properties": {}},
- }},
- {"type": "function", "function": {
- "name": "run_test",
- "description": f"Run `go test ./...` in the work dir. Returns exit code + output. Timeout {TEST_TIMEOUT}s.",
- "parameters": {"type": "object", "properties": {}},
- }},
- {"type": "function", "function": {
- "name": "run_shell",
- "description": f"Run an arbitrary shell command in the work dir (cwd = work dir). Use for `go get`, `go mod tidy`, npm, cargo, etc. Returns exit code + output. Timeout {SHELL_TIMEOUT}s.",
- "parameters": {"type": "object", "properties": {
- "cmd": {"type": "string", "description": "The shell command to run (sh -c)"},
- }, "required": ["cmd"]},
- }},
-]
\ No newline at end of file
+def _cmd_tool(cmd, timeout):
+ def impl(ws, args):
+ return ws.run(cmd, timeout).text()
+ return impl
+
+
+def _shell_tool(timeout):
+ def impl(ws, args):
+ cmd = _str_arg(args, "cmd", "")
+ if not cmd:
+ return "ERROR: empty cmd"
+ return ws.run(cmd, timeout).text()
+ return impl
+
+
+# ============================================================ toolsets
+
+class Toolset:
+ def __init__(self, name, schema, impls, cut_off_msg=CUT_OFF_MSG, commands=None,
+ unknown_fmt="ERROR: unknown tool {name!r}"):
+ self.name = name
+ self.schema = schema
+ self.impls = impls
+ self.cut_off_msg = cut_off_msg
+ self.unknown_fmt = unknown_fmt
+ self.commands = dict(commands or {})
+
+ def describe(self):
+ return {"name": self.name, "commands": self.commands,
+ "tools": [t["function"]["name"] for t in self.schema]}
+
+
+def _env_int(name, default):
+ v = os.environ.get(name)
+ return int(v) if v else default
+
+
+def build_toolset(name, *, build_cmd, test_cmd, build_desc, test_desc, shell_uses,
+ build_timeout, test_timeout, shell_timeout):
+ """The work-dir toolset; languages differ only in run_build/run_test/run_shell."""
+ build_timeout = _env_int("BUILD_TIMEOUT", build_timeout)
+ test_timeout = _env_int("TEST_TIMEOUT", test_timeout)
+ shell_timeout = _env_int("SHELL_TIMEOUT", shell_timeout)
+ schema = [
+ {"type": "function", "function": {
+ "name": "list_files",
+ "description": "List all file paths in the work dir (the project you are building). Returns one path per line.",
+ "parameters": {"type": "object", "properties": {}},
+ }},
+ {"type": "function", "function": {
+ "name": "read_file",
+ "description": "Return the full contents of one file in the work dir.",
+ "parameters": {"type": "object", "properties": {
+ "path": {"type": "string", "description": "Project-relative file path"},
+ }, "required": ["path"]},
+ }},
+ {"type": "function", "function": {
+ "name": "write_file",
+ "description": "Create or overwrite a file in the work dir with the given contents. Use for new files or full rewrites.",
+ "parameters": {"type": "object", "properties": {
+ "path": {"type": "string"},
+ "content": {"type": "string", "description": "Full file contents to write"},
+ }, "required": ["path", "content"]},
+ }},
+ {"type": "function", "function": {
+ "name": "edit_file",
+ "description": "Apply a patch-style edit to an existing file: replace the first occurrence of old_str with new_str. Fails if old_str is not found or appears more than once. Use this for surgical edits instead of rewriting the whole file.",
+ "parameters": {"type": "object", "properties": {
+ "path": {"type": "string"},
+ "old_str": {"type": "string", "description": "The exact text to find (must be unique in the file)"},
+ "new_str": {"type": "string", "description": "The replacement text"},
+ }, "required": ["path", "old_str", "new_str"]},
+ }},
+ {"type": "function", "function": {
+ "name": "search",
+ "description": "Regex-search the whole work dir; returns matching path:line: text, one per line.",
+ "parameters": {"type": "object", "properties": {
+ "pattern": {"type": "string"},
+ }, "required": ["pattern"]},
+ }},
+ {"type": "function", "function": {
+ "name": "run_build",
+ "description": build_desc,
+ "parameters": {"type": "object", "properties": {}},
+ }},
+ {"type": "function", "function": {
+ "name": "run_test",
+ "description": test_desc,
+ "parameters": {"type": "object", "properties": {}},
+ }},
+ {"type": "function", "function": {
+ "name": "run_shell",
+ "description": "Run an arbitrary shell command in the work dir (cwd = work dir). Use for " + shell_uses + ". Returns exit code + combined stdout/stderr. Timeout " + str(shell_timeout) + "s.",
+ "parameters": {"type": "object", "properties": {
+ "cmd": {"type": "string", "description": "The shell command to run (sh -c)"},
+ }, "required": ["cmd"]},
+ }},
+ ]
+ impls = {
+ "list_files": _list_files,
+ "read_file": _read_file,
+ "write_file": _write_file,
+ "edit_file": _edit_file,
+ "search": _search,
+ "run_build": _cmd_tool(build_cmd, build_timeout),
+ "run_test": _cmd_tool(test_cmd, test_timeout),
+ "run_shell": _shell_tool(shell_timeout),
+ }
+ return Toolset(name, schema, impls, commands={
+ "run_build": build_cmd, "run_test": test_cmd,
+ "timeouts": {"build": build_timeout, "test": test_timeout, "shell": shell_timeout}})
+
+
+GO_TOOLSET = build_toolset(
+ "go", build_cmd="go build ./...", test_cmd="go test ./...",
+ build_desc="Run `go build ./...` in the work dir. Returns exit code + combined stdout/stderr.",
+ test_desc="Run `go test ./...` in the work dir. Returns exit code + combined stdout/stderr.",
+ shell_uses="`go get`, `go mod tidy`, starting the server in the background, curl, etc",
+ build_timeout=180, test_timeout=180, shell_timeout=60)
+RUST_TOOLSET = build_toolset(
+ "rust", build_cmd="cargo build", test_cmd="cargo test",
+ build_desc="Run `cargo build` in the work dir. Returns exit code + combined stdout/stderr.",
+ test_desc="Run `cargo test` in the work dir. Returns exit code + combined stdout/stderr.",
+ shell_uses="`cargo add`, `cargo run`, running the built binary, curl, etc",
+ build_timeout=600, test_timeout=600, shell_timeout=60)
+TS_TOOLSET = build_toolset(
+ "ts", build_cmd="npx tsc --noEmit", test_cmd="npm test",
+ build_desc="Run `npx tsc --noEmit` (the TypeScript typecheck) in the work dir. Returns exit code + combined stdout/stderr.",
+ test_desc="Run `npm test` in the work dir. Returns exit code + combined stdout/stderr.",
+ shell_uses="`npm install`, `npx prisma generate`, `npx prisma db push`, starting the dev server in the background, curl, etc",
+ build_timeout=120, test_timeout=120, shell_timeout=300)
+
+
+# ============================================================ tool-call execution
+
+def parse_args(raw):
+ """(args_dict, None) or (None, error_text). Empty/None arguments mean {}."""
+ if isinstance(raw, dict):
+ return raw, None
+ if raw is None or (isinstance(raw, str) and not raw.strip()):
+ return {}, None
+ if not isinstance(raw, str):
+ return None, f"arguments must be a JSON object, got {type(raw).__name__}"
+ try:
+ v = json.loads(raw)
+ except ValueError as e:
+ return None, str(e)
+ if not isinstance(v, dict):
+ return None, f"arguments must be a JSON object, got {type(v).__name__}"
+ return v, None
+
+
+def run_tool(ws, toolset, name, args):
+ """Execute one call. Returns (text, stop). Never raises."""
+ impl = toolset.impls.get(name)
+ if impl is None:
+ return toolset.unknown_fmt.format(name=name), False
+ try:
+ r = impl(ws, args)
+ except ToolError as e:
+ return f"ERROR: {e}", False
+ except InfraError:
+ raise # agent_loop records it as harness_error: infra, never a grade
+ except Exception as e: # noqa: BLE001 — a tool may fail, the run may not
+ return f"ERROR: {name} raised {e!r}", False
+ if isinstance(r, ToolResult):
+ return str(r.text), r.stop
+ return str(r), False
+
+
+_DONE_RE = re.compile(r"\bdone\b", re.I)
+_NEG_RE = re.compile(r"(?:\bnot|\bnever|n't)\s+(?:(?:yet|quite|fully|really|completely|all)\s+)?$",
+ re.I)
+
+
+def said_done(text):
+ """Whole-word, un-negated "done" (see module docstring)."""
+ if not text:
+ return False
+ for m in _DONE_RE.finditer(text):
+ if not _NEG_RE.search(text[max(0, m.start() - 40):m.start()]):
+ return True
+ return False
+
+
+def _fmt(v, width, spec="d"):
+ if v is None:
+ return "-".rjust(width)
+ return format(v, f"{width}{spec}")
+
+
+def agent_loop(ws, messages, toolset, *, max_turns, max_tokens, temperature, item_id=None,
+ run_id=None, lane=None, done_word=True, give_up_after=None, nudge="",
+ bad_json_fmt="ERROR: invalid JSON args ({e}); re-emit the {name} call.",
+ trunc_fmt="\n...[truncated, {n} total]", result_cap=RESULT_CAP,
+ log=print, tag=""):
+ """Run the tool loop on `messages` (mutated in place).
+
+ done_word a no-tool turn whose answer says DONE ends the loop (stop_reason "done")
+ give_up_after stop after this many consecutive no-tool turns (None = never; nudge each)
+ nudge user message appended after a no-tool turn that didn't end the loop
+ bad_json_fmt tool result for a non-cut call whose arguments aren't a JSON object
+ trunc_fmt suffix for results over result_cap ({n} = full length); None = no cap
+
+ Returns {stop_reason, turns_used, turns, error, error_dt, harness_error, cut_off_turns,
+ totals...}. stop_reason: done | max_turns | gave_up | <CallError label> | harness_error.
+ Nothing escapes: a CallError lands in `error`, any other exception (a harness bug) in
+ `harness_error`, with the turns logged up to that point."""
+ turns = []
+ out = {"stop_reason": "max_turns", "turns_used": 0, "turns": turns, "error": None,
+ "error_dt": None, "harness_error": None, "last_resp": None}
+ no_tool_streak = 0
+ try:
+ for turn in range(1, max_turns + 1):
+ out["turns_used"] = turn
+ t_call = time.time()
+ try:
+ resp, dt = client.call_model(messages, tools=toolset.schema, max_tokens=max_tokens,
+ temperature=temperature, item_id=item_id,
+ run_id=run_id, lane=lane)
+ except client.CallError as e:
+ dt = time.time() - t_call
+ log(f" {tag}turn {turn:2d}: REQUEST ERROR {e.label()}: {str(e)[:200]}")
+ turns.append({"turn": turn, **client.error_meta(e, dt)})
+ out.update(stop_reason=e.label(), error=e, error_dt=dt)
+ break
+ out["last_resp"] = resp
+ msg = resp["choices"][0].get("message") or {}
+ fr = client.finish_reason(resp)
+ tcs = [tc for tc in client.tool_calls(resp) if isinstance(tc, dict)]
+ text = client.content(resp)
+ cut_off = fr == "length"
+ tlog = {"turn": turn, **client.meta(resp, dt), "cut_off": cut_off,
+ "content_head": text[:200], "n_tool_calls": len(tcs), "tools": []}
+ turns.append(tlog)
+ names = ",".join(((tc.get("function") or {}).get("name") or "?") for tc in tcs)
+ log(f" {tag}turn {turn:2d}: {dt:6.1f}s ptok={_fmt(tlog['prompt_tokens'], 6)} "
+ f"ctok={_fmt(tlog['completion_tokens'], 5)} rtok={_fmt(tlog['reasoning_tokens'], 5)} "
+ f"fr={str(fr):10s} tools=[{names or '(no tool call)'}]{' CUT-OFF' if cut_off else ''}")
+
+ a_msg = dict(msg)
+ a_msg["role"] = "assistant"
+ a_msg["content"] = msg.get("content") or ""
+ if tcs:
+ a_msg["tool_calls"] = tcs
+ else:
+ a_msg.pop("tool_calls", None)
+
+ if not tcs:
+ if done_word and said_done(text):
+ tlog["done"] = True
+ out["stop_reason"] = "done"
+ break
+ no_tool_streak += 1
+ if give_up_after and no_tool_streak >= give_up_after:
+ log(f" {tag}-> giving up after {no_tool_streak} no-tool turns")
+ tlog["gave_up"] = True
+ out["stop_reason"] = "gave_up"
+ break
+ tlog["nudged"] = True
+ messages.append(a_msg)
+ messages.append({"role": "user", "content": nudge})
+ continue
+
+ no_tool_streak = 0
+ messages.append(a_msg)
+ stop = False
+ for tc in tcs:
+ fn = tc.get("function") or {}
+ name = fn.get("name") or ""
+ raw = fn.get("arguments")
+ args, perr = parse_args(raw)
+ executed = False
+ if args is None:
+ result = toolset.cut_off_msg if cut_off else bad_json_fmt.format(e=perr, name=name)
+ else:
+ result, stop = run_tool(ws, toolset, name, args)
+ executed = True
+ if trunc_fmt is not None and len(result) > result_cap:
+ result = result[:result_cap] + trunc_fmt.format(n=len(result))
+ messages.append({"role": "tool", "tool_call_id": tc.get("id", ""), "content": result})
+ raw_s = raw if isinstance(raw, str) else json.dumps(raw)
+ tlog["tools"].append({"name": name, "executed": executed,
+ "args_head": (raw_s or "")[:200], "result_len": len(result),
+ "result_head": result[:200]})
+ if stop:
+ break
+ if stop:
+ tlog["done"] = True
+ out["stop_reason"] = "done"
+ break
+
+ except Exception as e: # noqa: BLE001 — harness bug: keep the turns logged so far
+ log(f" {tag}HARNESS ERROR in the loop: {e!r}")
+ turns.append({"turn": out["turns_used"], **client.error_meta(e)})
+ out.update(stop_reason="harness_error", harness_error=e)
+
+ real = [t for t in turns if "error" not in t]
+ rts = [t["reasoning_tokens"] for t in real if t.get("reasoning_tokens") is not None]
+ costs = [t["cost_usd"] for t in real if t.get("cost_usd") is not None]
+ finish_counts = {}
+ for t in real:
+ finish_counts[str(t.get("finish"))] = finish_counts.get(str(t.get("finish")), 0) + 1
+ out.update({
+ "cut_off_turns": sum(1 for t in real if t.get("cut_off")),
+ "prompt_tokens": sum(t["prompt_tokens"] for t in real),
+ "completion_tokens": sum(t["completion_tokens"] for t in real),
+ "reasoning_tokens": sum(rts) if rts else None,
+ "peak_prompt_tokens": max((t["prompt_tokens"] for t in real), default=0),
+ "cost_usd": round(sum(costs), 6) if costs else None,
+ "finish_counts": finish_counts,
+ "tool_calls": sum(len(t["tools"]) for t in real),
+ "model_s": round(sum(t.get("wall_s") or 0 for t in turns), 2),
+ })
+ return out
diff --git a/bench/data/reasoning/README.md b/bench/data/reasoning/README.md
new file mode 100644
index 0000000..082cc8a
--- /dev/null
+++ b/bench/data/reasoning/README.md
@@ -0,0 +1,24 @@
+# reasoning instrument data
+
+`python3 bench.py reasoning fetch` downloads the public dataset via the Hugging Face
+datasets-server JSON API, selects items deterministically, writes them to `cache/<set>.jsonl`
+(gitignored, re-creatable) and pins them in the committed `<set>.manifest.json`
+(per-item sha256 of the canonical item JSON + a `manifest_hash` that goes into the run's
+`item_set` as `<set>@<manifest_hash>`). `validate` re-hashes the cache against the manifest
+offline; `run` refuses to start on any drift.
+
+Selection rule: sort by `sha256(f"{set}:{native_id}")`, take the first N. No RNG state.
+
+| set | source (config / split) | selection | n | license |
+|---|---|---|---|---|
+| `mmlu-pro-cs` | `TIGER-Lab/MMLU-Pro` (default / test), category "computer science" | first 60 by hash; native_id = `question_id` | 60 | MIT |
+
+License as listed on the dataset card on 2026-10-12. The cache is not redistributed in this repo;
+only hashes and ids are committed.
+
+item_id = `mmlu-pro-cs/<question_id>`; category = `cs`. Grading is on the final content only (never
+the reasoning text): the last `ANSWER: <letter>` (A-J).
+
+Suite v3 (2026-10-12): only computing-relevant sets stay. `aime26` (MathArena/aime_2026, CC BY-NC-SA
+4.0), `musr` (TAUR-Lab/MuSR), `zebra` (WildEval/ZebraLogic) and the all-category `mmlu-pro` set were
+removed with their manifests (see git history); stored runs of them still read in reports.
diff --git a/bench/data/reasoning/mmlu-pro-cs.manifest.json b/bench/data/reasoning/mmlu-pro-cs.manifest.json
new file mode 100644
index 0000000..252be7e
--- /dev/null
+++ b/bench/data/reasoning/mmlu-pro-cs.manifest.json
@@ -0,0 +1,375 @@
+{
+ "set": "mmlu-pro-cs",
+ "source": {
+ "dataset": "TIGER-Lab/MMLU-Pro",
+ "config": "default",
+ "splits": [
+ "test"
+ ]
+ },
+ "selection_rule": "sort by sha256(f'<set>:<native_id>'), take first N per stratum. first 60 of category 'computer science' by sha256('mmlu-pro-cs:<question_id>')",
+ "n": 60,
+ "items": [
+ {
+ "item_id": "mmlu-pro-cs/10423",
+ "native_id": "10423",
+ "category": "cs",
+ "sha256": "bc65b4100349de6a6e609c01543984dbaaa13214dd4736f151aea5a979251eb9"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10444",
+ "native_id": "10444",
+ "category": "cs",
+ "sha256": "3795384e33286df4dfe20ed3d7ce2775bb3096357a615a7e4b6a53b0fde51ba7"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10760",
+ "native_id": "10760",
+ "category": "cs",
+ "sha256": "6d3314990b969a8480f084683c3a610e7e11cd7b8a8bf760a37b8948aab94ac5"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10487",
+ "native_id": "10487",
+ "category": "cs",
+ "sha256": "d0938c0d4ab3e33783adc1582fc1b66aef9a82f5459910b8b91de58ff68a6605"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10462",
+ "native_id": "10462",
+ "category": "cs",
+ "sha256": "915be82c1f16ad9be486fa5dca711da6d84822c2dd5b234d65fb68415aab17a0"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10717",
+ "native_id": "10717",
+ "category": "cs",
+ "sha256": "ac7c91af003dfbb85a1bcda200dec59e0e056f98e87a079cd25274e23c3c1f03"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10438",
+ "native_id": "10438",
+ "category": "cs",
+ "sha256": "e08b5f0b5a062ad14847c86801dec01e50f60f10be4caeba08a29a310815fd11"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10737",
+ "native_id": "10737",
+ "category": "cs",
+ "sha256": "4ec3713b8bac131b9542181aa33dd5b336d20de2bb1ef14a60e8ed17d94b02fa"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10758",
+ "native_id": "10758",
+ "category": "cs",
+ "sha256": "94dd06bfb1d5d6c40ddf19158e5adaba2ccc7689951aa6c1af4f71578326af3e"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10414",
+ "native_id": "10414",
+ "category": "cs",
+ "sha256": "2dec4579943cd616516f61f371dd3b630d9db750b6364022f7921fa37e274431"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10553",
+ "native_id": "10553",
+ "category": "cs",
+ "sha256": "0ff772ca695049602ed7c5cdc9f8e8cc5a5e6b53dc368c5c8519793f967cdf0e"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10490",
+ "native_id": "10490",
+ "category": "cs",
+ "sha256": "2bc3afb530a03fdb0892030019265ec20eecf1462a4a51b34605067ac0c221b1"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10705",
+ "native_id": "10705",
+ "category": "cs",
+ "sha256": "0113fce4a2c238603d7be07142edab5633278165b8ed3741b6f83c4817109ebd"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10485",
+ "native_id": "10485",
+ "category": "cs",
+ "sha256": "537332cad06e9abcdc5d3d6f92231f3a337de21b7728eccbc81da2089e4349ea"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10460",
+ "native_id": "10460",
+ "category": "cs",
+ "sha256": "8f530409ccb664d0d6d98dae112adba33bb852a10c5581b905e3f74bcf81d277"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10407",
+ "native_id": "10407",
+ "category": "cs",
+ "sha256": "60ce3c9e1d6ce335467f4e3d22e32a34cbcace821d3707f7d7eafe9846a21ae1"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10357",
+ "native_id": "10357",
+ "category": "cs",
+ "sha256": "0e168675ae8e45f77e902f20d4f9a1d50381521bcea2686efb52c9b3fa6e394c"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10610",
+ "native_id": "10610",
+ "category": "cs",
+ "sha256": "60abfdece27b2fe3b35c8e3109e8050aa1a8cfaa48b36b2eaf76907f66d33d25"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10361",
+ "native_id": "10361",
+ "category": "cs",
+ "sha256": "ebbbb57d9879b2cbd1a2cf4362cd43e072b0550043a7d74865d5a750157f853e"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10458",
+ "native_id": "10458",
+ "category": "cs",
+ "sha256": "75b9d8a0f55f927fe906ce521a13cb59fb656deaf4aafd29256aeaf7ed5b8174"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10646",
+ "native_id": "10646",
+ "category": "cs",
+ "sha256": "44d7c806eb64e0f93848c2b3d660f37fad68a921547aee9e7e3134c2872db022"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10713",
+ "native_id": "10713",
+ "category": "cs",
+ "sha256": "723a6307d99ecff1d0cbcfed98036fc21df87b6804dffc36db8865248bf0fc92"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10719",
+ "native_id": "10719",
+ "category": "cs",
+ "sha256": "49f9bcda563acf55e3773632835d940d6c52ffbd09c43bafeb7f17a83b9c3eae"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10538",
+ "native_id": "10538",
+ "category": "cs",
+ "sha256": "584775889009474b861bdd11840da39cb5dfb8fff51e95dc6299c10899c6952a"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10499",
+ "native_id": "10499",
+ "category": "cs",
+ "sha256": "4af22bccbe6d4ed97d54c8260228ac14660e2a28c158907326e80fb908550233"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10677",
+ "native_id": "10677",
+ "category": "cs",
+ "sha256": "48896d8d732e5abbb6bc864524d548ef54c59f74d2b203f35e6fcffd39e3915c"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10587",
+ "native_id": "10587",
+ "category": "cs",
+ "sha256": "aa62c5b33f1e9f6968ab0aeb788a275b402965d90e94d0f888b3b3cf3ebc0a3a"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10386",
+ "native_id": "10386",
+ "category": "cs",
+ "sha256": "5239db39a055b9f10e7fc075320bcae292c21d74b8f8e4a0b0dae2d2f2e77092"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10367",
+ "native_id": "10367",
+ "category": "cs",
+ "sha256": "4f95857cd54b6b0a0f33752a0398ad0a0e7e0b28a553d56da3957810f9544fbb"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10653",
+ "native_id": "10653",
+ "category": "cs",
+ "sha256": "46576dbb04b122ca28fd608c31e5c98bc9422263332fc0306f80995c1e95a3fd"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10659",
+ "native_id": "10659",
+ "category": "cs",
+ "sha256": "4df511c247ec1e0ba880af2efeb77d3e42ff5bdcd98258f69dabf1432d6961ef"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10385",
+ "native_id": "10385",
+ "category": "cs",
+ "sha256": "184ad7530c7a0f579d03c14fcc7195ad9a74775993af8f1dc1eec254b9466717"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10633",
+ "native_id": "10633",
+ "category": "cs",
+ "sha256": "64f451e0d4b5f55f0ef531567e238a40527e6eafff9b3b0d7b9cb16b2b0c82e4"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10607",
+ "native_id": "10607",
+ "category": "cs",
+ "sha256": "00c2d895bebf2656645d7d645bf812f64dfba94eb7c6f23db41a4098b6d32589"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10616",
+ "native_id": "10616",
+ "category": "cs",
+ "sha256": "2d9fc33fd170c5b5c30fb6815a28c89d8833c1d0e4555de783dc613a7ad5c39a"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10484",
+ "native_id": "10484",
+ "category": "cs",
+ "sha256": "a02731fa1161d24d85c51bdacc26a9ca957e276aeb0e9894b1120454b4937f8c"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10624",
+ "native_id": "10624",
+ "category": "cs",
+ "sha256": "73f1c822ceddff67b553f3e60d04d7daa8973327b7f458a7c50f935f67a6bd99"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10454",
+ "native_id": "10454",
+ "category": "cs",
+ "sha256": "a010f2ae54218fa308f9d6710fb2a4711ff9dbebe21b12cf1d8564dee11d24bb"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10710",
+ "native_id": "10710",
+ "category": "cs",
+ "sha256": "23fbbdc0fa89b854c6ca547f5b3e4d198f504a69d1a02e3338f1e0803cbf914a"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10585",
+ "native_id": "10585",
+ "category": "cs",
+ "sha256": "443359091599ea130b0378efe9d35b7f8af7f00a0840a0e22419e40259e46a6d"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10681",
+ "native_id": "10681",
+ "category": "cs",
+ "sha256": "8127197c54c9e6f526084f99a44c8bef39b2eb9a7cb543e69555f999b7a604db"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10464",
+ "native_id": "10464",
+ "category": "cs",
+ "sha256": "9641a586acdb105e08f8b96e510ff19b489530e1f7ea7e75d59d6385d9c55a0a"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10611",
+ "native_id": "10611",
+ "category": "cs",
+ "sha256": "3477029788b17f186bc085ccb9638690f8359b47e3348af5dcbf8fe42a6b1929"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10533",
+ "native_id": "10533",
+ "category": "cs",
+ "sha256": "cc96678fe23b901a07fc58925fc931113028bda9789df6fa1ecf5d8b1bdbd45e"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10416",
+ "native_id": "10416",
+ "category": "cs",
+ "sha256": "362dc94789062b270f21fddcf994332f9d46654b29b94611f393dd90d63cf9be"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10577",
+ "native_id": "10577",
+ "category": "cs",
+ "sha256": "ac5cbabea909ad773543d2f1f7f0125350d33723d60cec1ed1a20f9f27d49d2c"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10600",
+ "native_id": "10600",
+ "category": "cs",
+ "sha256": "7f426af8be84506574c5438879172774141022bb267f913c44951e9be31f624e"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10632",
+ "native_id": "10632",
+ "category": "cs",
+ "sha256": "33a621854a580e45f76914c7c07e54960dc270dc42e0543ba5edb95aad7188a7"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10711",
+ "native_id": "10711",
+ "category": "cs",
+ "sha256": "854b26d0d8f4ef3384abc2865745c8f308399c375ed4101f52a2b85115460980"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10476",
+ "native_id": "10476",
+ "category": "cs",
+ "sha256": "20d4f08766feaf20190c8812f43f3cc3aee8ea12e5c8f44b4c9c733eff859f67"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10427",
+ "native_id": "10427",
+ "category": "cs",
+ "sha256": "6496003e379a3b845054361034d706393efb2e0d35b755094165e7bd575636af"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10494",
+ "native_id": "10494",
+ "category": "cs",
+ "sha256": "6839cc5fe876f1e085c9b890b2f35e077219145d827604b7a5e6477d23c510b6"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10613",
+ "native_id": "10613",
+ "category": "cs",
+ "sha256": "f2bf7c9ac7e0f791ff0543ad1bb3b2b1dfdf558a759c8bb2768a1dd0bfc5dc1b"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10695",
+ "native_id": "10695",
+ "category": "cs",
+ "sha256": "bfbc48022cfd4af027bd957f34a0082769f0d0366eb1d715a628f25106a5db28"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10477",
+ "native_id": "10477",
+ "category": "cs",
+ "sha256": "f8e9a820832adb3c60064afee90fc40e76b43965bb3e4edf5e02dffbc8adfd22"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10588",
+ "native_id": "10588",
+ "category": "cs",
+ "sha256": "24846188f2254e33f48e06536544f2d93845264d09736887e8fd957b962523a6"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10535",
+ "native_id": "10535",
+ "category": "cs",
+ "sha256": "5d3fcff8b531aabb83d5fc76dfbc2f7ae7488068e65301beb2dd34e526d8e2e9"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10703",
+ "native_id": "10703",
+ "category": "cs",
+ "sha256": "58fa15fa1fe9f83dfb2c6739d25588f112f2edf76b666fcf035ffc665cd16157"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10733",
+ "native_id": "10733",
+ "category": "cs",
+ "sha256": "5a656baf781245066b20aaa59d8eadce7dd8861388ee988407f134c90fa82cd1"
+ },
+ {
+ "item_id": "mmlu-pro-cs/10645",
+ "native_id": "10645",
+ "category": "cs",
+ "sha256": "9279e7176e77995784d66d01b305d847c75f8278a7dc714af2befb0e1f9b9e70"
+ }
+ ],
+ "manifest_hash": "4e8c4ada52be"
+}
diff --git a/bench/tasks/__init__.py b/bench/tasks/__init__.py
index ba9dd56..e69de29 100644
--- a/bench/tasks/__init__.py
+++ b/bench/tasks/__init__.py
@@ -1,6 +0,0 @@
-"""Task instruments for the benchmark framework.
-
-Each module is an instrument (coding-suite, agentic-fix, agentic-build,
-agentic-multitask, router, needle, loop-battery, no-think) with a
-validate() and run() function, importable by the bench.py CLI.
-"""
\ No newline at end of file
diff --git a/bench/tasks/agentic_build.py b/bench/tasks/agentic_build.py
deleted file mode 100644
index c0f8405..0000000
--- a/bench/tasks/agentic_build.py
+++ /dev/null
@@ -1,572 +0,0 @@
-"""Agentic build instrument — "build a real small app" end-to-end.
-
-Given a plan and a thin starter scaffold, the agent uses tools to write ~8
-files, get `go build` green, get `go test` green, and produce a binary that
-starts, serves an HTML form, and persists a POSTed note to SQLite. The four
-"real product" gates are run by the harness, not the agent.
-
-This is a Go + SQLite + html/template app — a realistic small self-hosted
-web tool in miniature. It tests the actual workload: multi-turn tool-use,
-file creation, dependency management, iterative build/test cycles.
-
-Usage (via the bench.py CLI):
- python bench.py agentic-build validate
- python bench.py agentic-build run
-
-Env (via .env): ENDPOINT, MODEL, API_KEY, MAX_TOKENS, MAX_TURNS.
-"""
-import json
-import os
-import re
-import sys
-import time
-import shutil
-import subprocess
-import socket
-import signal
-import urllib.request
-import urllib.parse
-import urllib.error
-
-from bench.core import client
-from bench.core import tools
-from bench.core.reporting import write_json
-
-HERE = os.path.dirname(os.path.abspath(__file__))
-WORK = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "work", "agentic_build")
-MAX_TOKENS = int(os.environ.get("MAX_TOKENS", "16000"))
-MAX_TURNS = int(os.environ.get("MAX_TURNS", "40"))
-BUILD_TIMEOUT = int(os.environ.get("BUILD_TIMEOUT", "180"))
-TEST_TIMEOUT = int(os.environ.get("TEST_TIMEOUT", "180"))
-SERVER_TIMEOUT = int(os.environ.get("SERVER_TIMEOUT", "20"))
-
-PLAN = """\
-# Task — Build a Go web binary with a SQLite-backed notes CRUD
-
-## Goal
-`go build ./...` and `go test ./...` run green in the work dir, and the
-resulting binary starts on port 8080, serves an HTML form at `/` that lists
-existing notes and lets a visitor create a new one, and persists created
-notes to an embedded SQLite file `notes.db`.
-
-## Prerequisites
-A starter scaffold is already in the work dir:
- - `go.mod` (module `notes`, go 1.26, no deps yet)
- - `cmd/server/main.go` (empty stub: `package main; func main(){}`)
-You start from this scaffold. Do not delete existing files; build on them.
-
-## Spec — the app to build
-A single Go binary that serves a one-page HTML UI over HTTP. One `cmd/`,
-modular `internal/` packages, server-rendered `html/template`, embedded
-assets, embedded SQLite via the pure-Go driver `modernc.org/sqlite`.
-
-### Files to produce (layout)
- cmd/server/main.go boot: config -> db -> migrate -> handlers -> ListenAndServe + graceful shutdown
- internal/config/config.go Config{Port, DBPath}; LoadFromEnv() with sane defaults (port 8080, db "notes.db"). MUST read env vars NOTES_PORT (port) and NOTES_DB (db path) — the scoring harness sets these.
- internal/db/db.go Open(dsn): open modernc sqlite, PRAGMA WAL + busy_timeout + foreign_keys ON; Migrate() via embedded .sql
- internal/db/migrations/00001_init.sql CREATE TABLE notes (id INTEGER PRIMARY KEY, title TEXT NOT NULL, body TEXT NOT NULL, created_at DATETIME DEFAULT CURRENT_TIMESTAMP);
- internal/models/note.go Note struct + Create(db, title, body) + List(db) + Delete(db, id); plain database/sql, no ORM
- internal/handlers/handlers.go Handlers struct; routes via stdlib net/http ServeMux: GET / (list+form), POST / (create), POST /{id}/delete (delete)
- internal/handlers/handlers_test.go httptest: POST a note, GET /, assert the note title appears in the response body
- web/templates/index.html the one page: a form (title + body + submit) above a list of notes (each with a delete button); rendered server-side by html/template
-
-### Constraints
- - Use `modernc.org/sqlite` (pure-Go, CGO_ENABLED=0). Import path is `_ "modernc.org/sqlite"`.
- - Embed the migration SQL and the templates via `//go:embed`.
- - Stdlib `net/http` ServeMux only — no Gin, no chi.
- - No JS framework. Plain HTML form posts back to the server.
-
-## Steps
-1. Add the dependency: `go get modernc.org/sqlite`. Run `go mod tidy`.
-2. Write the files. Natural order: config -> db -> models -> handlers -> templates -> main.
-3. Build (`go build ./...`). Fix any compile errors.
-4. Test (`go test ./...`). The handlers_test.go must pass.
-5. Optionally run the binary briefly to confirm it serves.
-
-## Acceptance (harness-verified)
-1. `go build ./...` exits 0.
-2. `go test ./...` exits 0.
-3. The built binary starts on port 8080 and `GET /` returns HTTP 200 with a `<form` element.
-4. `POST /` with form fields title+body creates a row; a subsequent `GET /` shows that title; the SQLite file on disk contains the row.
-
-## Out of scope
-Auth, sessions, CSRF, styling beyond minimal readable HTML, HTMX, pagination, any JS.
-
-## Commit
-You do not commit; the harness owns the work dir.
-"""
-
-STARTER = {
- "go.mod": "module notes\n\ngo 1.26\n",
- "cmd/server/main.go": "package main\n\nfunc main() {}\n",
-}
-
-REFERENCE = {
- "go.mod": "module notes\n\ngo 1.26\n\nrequire modernc.org/sqlite v1.50.0\n",
- "cmd/server/main.go": '''package main
-
-import (
- "context"
- "fmt"
- "log"
- "net/http"
- "os"
- "os/signal"
- "syscall"
- "time"
-
- "notes/internal/config"
- "notes/internal/db"
- "notes/internal/handlers"
- "notes/internal/models"
-)
-
-func main() {
- cfg := config.LoadFromEnv()
- database, err := db.Open(cfg.DBPath)
- if err != nil { log.Fatalf("db open: %v", err) }
- defer database.Close()
- if err := database.Migrate(); err != nil { log.Fatalf("migrate: %v", err) }
- notes := &models.Store{DB: database.DB}
- h := handlers.New(notes)
- srv := &http.Server{Addr: fmt.Sprintf(":%d", cfg.Port), Handler: h.Routes()}
- go func() {
- log.Printf("listening on :%d", cfg.Port)
- if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
- log.Fatalf("serve: %v", err)
- }
- }()
- stop := make(chan os.Signal, 1)
- signal.Notify(stop, os.Interrupt, syscall.SIGTERM)
- <-stop
- log.Println("shutting down")
- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
- defer cancel()
- _ = srv.Shutdown(ctx)
-}
-''',
- "internal/config/config.go": '''package config
-
-import ("os"; "strconv")
-
-type Config struct { Port int; DBPath string }
-
-func LoadFromEnv() Config {
- cfg := Config{Port: 8080, DBPath: "notes.db"}
- if p := os.Getenv("NOTES_PORT"); p != "" {
- if v, err := strconv.Atoi(p); err == nil { cfg.Port = v }
- }
- if d := os.Getenv("NOTES_DB"); d != "" { cfg.DBPath = d }
- return cfg
-}
-''',
- "internal/db/db.go": '''package db
-
-import ("database/sql"; "embed"; "fmt"; _ "modernc.org/sqlite")
-
-//go:embed migrations/*.sql
-var migrationsFS embed.FS
-
-type Database struct { *sql.DB }
-
-func Open(dsn string) (*Database, error) {
- db, err := sql.Open("sqlite", dsn)
- if err != nil { return nil, fmt.Errorf("open sqlite: %w", err) }
- if _, err := db.Exec(`PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000; PRAGMA foreign_keys=ON;`); err != nil {
- db.Close(); return nil, fmt.Errorf("pragmas: %w", err)
- }
- return &Database{DB: db}, nil
-}
-
-func (d *Database) Migrate() error {
- if _, err := d.Exec(`CREATE TABLE IF NOT EXISTS schema_migrations (name TEXT PRIMARY KEY, applied_at DATETIME DEFAULT CURRENT_TIMESTAMP)`); err != nil {
- return fmt.Errorf("create schema_migrations: %w", err)
- }
- entries, err := migrationsFS.ReadDir("migrations")
- if err != nil { return fmt.Errorf("read migrations dir: %w", err) }
- for _, e := range entries {
- if e.IsDir() { continue }
- name := e.Name()
- var applied int
- if err := d.QueryRow(`SELECT count(*) FROM schema_migrations WHERE name = ?`, name).Scan(&applied); err != nil {
- return fmt.Errorf("check %s: %w", name, err)
- }
- if applied > 0 { continue }
- b, err := migrationsFS.ReadFile("migrations/" + name)
- if err != nil { return fmt.Errorf("read %s: %w", name, err) }
- if _, err := d.Exec(string(b)); err != nil { return fmt.Errorf("apply %s: %w", name, err) }
- if _, err := d.Exec(`INSERT INTO schema_migrations (name) VALUES (?)`, name); err != nil {
- return fmt.Errorf("record %s: %w", name, err)
- }
- }
- return nil
-}
-''',
- "internal/db/migrations/00001_init.sql": '''CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL, body TEXT NOT NULL, created_at DATETIME DEFAULT CURRENT_TIMESTAMP);''',
- "internal/models/note.go": '''package models
-
-import ("database/sql"; "time")
-
-type Note struct { ID int64; Title string; Body string; CreatedAt time.Time }
-type Store struct { DB *sql.DB }
-
-func (s *Store) Create(title, body string) (*Note, error) {
- res, err := s.DB.Exec(`INSERT INTO notes (title, body) VALUES (?, ?)`, title, body)
- if err != nil { return nil, err }
- id, err := res.LastInsertId()
- if err != nil { return nil, err }
- return &Note{ID: id, Title: title, Body: body, CreatedAt: time.Now()}, nil
-}
-
-func (s *Store) List() ([]Note, error) {
- rows, err := s.DB.Query(`SELECT id, title, body, created_at FROM notes ORDER BY id DESC`)
- if err != nil { return nil, err }
- defer rows.Close()
- var out []Note
- for rows.Next() {
- var n Note
- if err := rows.Scan(&n.ID, &n.Title, &n.Body, &n.CreatedAt); err != nil { return nil, err }
- out = append(out, n)
- }
- return out, rows.Err()
-}
-
-func (s *Store) Delete(id int64) (bool, error) {
- res, err := s.DB.Exec(`DELETE FROM notes WHERE id = ?`, id)
- if err != nil { return false, err }
- n, err := res.RowsAffected()
- if err != nil { return false, err }
- return n > 0, nil
-}
-''',
- "internal/handlers/handlers.go": '''package handlers
-
-import ("embed"; "html/template"; "log"; "net/http"; "strconv"; "notes/internal/models")
-
-//go:embed templates/*.html
-var templatesFS embed.FS
-
-type Handlers struct { notes *models.Store; tmpl *template.Template }
-
-func New(notes *models.Store) *Handlers {
- tmpl := template.Must(template.ParseFS(templatesFS, "templates/index.html"))
- return &Handlers{notes: notes, tmpl: tmpl}
-}
-
-func (h *Handlers) Routes() http.Handler {
- mux := http.NewServeMux()
- mux.HandleFunc("GET /", h.index)
- mux.HandleFunc("POST /", h.create)
- mux.HandleFunc("POST /{id}/delete", h.delete)
- return mux
-}
-
-func (h *Handlers) index(w http.ResponseWriter, r *http.Request) {
- notes, err := h.notes.List()
- if err != nil { log.Printf("list: %v", err); http.Error(w, "internal error", http.StatusInternalServerError); return }
- w.Header().Set("Content-Type", "text/html; charset=utf-8")
- if err := h.tmpl.Execute(w, notes); err != nil { log.Printf("render: %v", err) }
-}
-
-func (h *Handlers) create(w http.ResponseWriter, r *http.Request) {
- title := r.FormValue("title"); body := r.FormValue("body")
- if title == "" || body == "" { http.Error(w, "title and body are required", http.StatusBadRequest); return }
- if _, err := h.notes.Create(title, body); err != nil { log.Printf("create: %v", err); http.Error(w, "internal error", http.StatusInternalServerError); return }
- http.Redirect(w, r, "/", http.StatusSeeOther)
-}
-
-func (h *Handlers) delete(w http.ResponseWriter, r *http.Request) {
- idStr := r.PathValue("id"); id, err := strconv.ParseInt(idStr, 10, 64)
- if err != nil { http.Error(w, "bad id", http.StatusBadRequest); return }
- if _, err := h.notes.Delete(id); err != nil { log.Printf("delete: %v", err); http.Error(w, "internal error", http.StatusInternalServerError); return }
- http.Redirect(w, r, "/", http.StatusSeeOther)
-}
-''',
- "internal/handlers/templates/index.html": '''<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Notes</title><style>body{font-family:system-ui,sans-serif;max-width:40em;margin:2rem auto;padding:0 1rem}form{margin:1rem 0;padding:1rem;border:1px solid #ccc;border-radius:6px}label{display:block;margin:0.5rem 0}input[type=text],textarea{width:100%;box-sizing:border-box;padding:0.4rem}.note{margin:0.75rem 0;padding:0.75rem;border-bottom:1px solid #eee}form.delete{display:inline}form.delete button{background:none;border:none;color:#c00;cursor:pointer}</style></head><body><h1>Notes</h1><form method="POST" action="/"><label>Title <input type="text" name="title" required></label><label>Body <textarea name="body" rows="4" required></textarea></label><button type="submit">Add note</button></form>{{range .}}<div class="note"><h3>{{.Title}}</h3><p>{{.Body}}</p><form class="delete" method="POST" action="/{{.ID}}/delete"><button type="submit">delete</button></form></div>{{else}}<p>No notes yet.</p>{{end}}</body></html>''',
- "internal/handlers/handlers_test.go": '''package handlers
-
-import ("database/sql"; "io"; "net/http"; "net/http/httptest"; "net/url"; "strings"; "testing"; "notes/internal/models"; _ "modernc.org/sqlite")
-
-func newTestStore(t *testing.T) (*models.Store, func()) {
- t.Helper()
- db, err := sql.Open("sqlite", ":memory:")
- if err != nil { t.Fatalf("open: %v", err) }
- _, err = db.Exec(`CREATE TABLE notes (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL, body TEXT NOT NULL, created_at DATETIME DEFAULT CURRENT_TIMESTAMP)`)
- if err != nil { db.Close(); t.Fatalf("create table: %v", err) }
- return &models.Store{DB: db}, func() { db.Close() }
-}
-
-func TestCreateThenList(t *testing.T) {
- store, cleanup := newTestStore(t); defer cleanup()
- h := New(store)
- srv := httptest.NewServer(h.Routes()); defer srv.Close()
- form := url.Values{"title": {"My Note"}, "body": {"First body"}}
- resp, err := http.PostForm(srv.URL+"/", form)
- if err != nil { t.Fatalf("post: %v", err) }
- resp.Body.Close()
- if resp.StatusCode != http.StatusOK { t.Fatalf("post status = %d, want 200", resp.StatusCode) }
- resp2, err := http.Get(srv.URL + "/")
- if err != nil { t.Fatalf("get: %v", err) }
- defer resp2.Body.Close()
- body, _ := io.ReadAll(resp2.Body)
- if !strings.Contains(string(body), "My Note") { t.Fatalf("response does not contain the created note title; got:\\n%s", body) }
-}
-''',
- "internal/handlers/doc.go": "package handlers",
- "internal/models/doc.go": "package models",
- "internal/config/doc.go": "package config",
- "internal/db/doc.go": "package db",
-}
-
-# ----------------------------------------------------------------- scoring gates
-def _has_real_app(work_dir):
- main_go = os.path.join(work_dir, "cmd", "server", "main.go")
- if not os.path.isfile(main_go): return False
- with open(main_go) as f: src = f.read()
- if "ListenAndServe" not in src and "http.Server" not in src: return False
- internal = os.path.join(work_dir, "internal")
- if not os.path.isdir(internal): return False
- pkg_dirs = [d for d in os.listdir(internal) if os.path.isdir(os.path.join(internal, d))]
- return len(pkg_dirs) >= 3
-
-def _run(cmd, work_dir, timeout):
- try:
- p = subprocess.run(cmd, cwd=work_dir, shell=True, capture_output=True, text=True, timeout=timeout)
- except subprocess.TimeoutExpired:
- return f"TIMEOUT after {timeout}s"
- return f"exit={p.returncode}\n{(p.stdout + p.stderr).strip()}"
-
-def _free_port():
- s = socket.socket(socket.AF_INET, socket.SOCK_STREAM); s.bind(("", 0))
- p = s.getsockname()[1]; s.close(); return p
-
-def gates(work_dir):
- g = {}
- if not _has_real_app(work_dir):
- return {"build": False, "test": False, "serves": False, "persists": False}
- b = _run("go build ./...", work_dir, BUILD_TIMEOUT)
- g["build"] = b.startswith("exit=0")
- t = _run("go test ./...", work_dir, TEST_TIMEOUT)
- g["test"] = t.startswith("exit=0")
- binpath = os.path.abspath(os.path.join(work_dir, "server"))
- r = _run(f"go build -o {binpath} ./cmd/server", work_dir, BUILD_TIMEOUT)
- if not r.startswith("exit=0") or not os.path.isfile(binpath):
- g["serves"] = False; g["persists"] = False; return g
- port = _free_port()
- dbpath = os.path.abspath(os.path.join(work_dir, f"bench_{port}.db"))
- for ext in ("", "-wal", "-shm"):
- if os.path.exists(dbpath + ext): os.remove(dbpath + ext)
- env = dict(os.environ, NOTES_PORT=str(port), NOTES_DB=dbpath)
- try:
- proc = subprocess.Popen([binpath], cwd=work_dir, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
- except Exception:
- g["serves"] = False; g["persists"] = False; return g
- try:
- for _ in range(40):
- try:
- with socket.create_connection(("127.0.0.1", port), 0.25): break
- except OSError: time.sleep(0.25)
- else:
- g["serves"] = False; g["persists"] = False; return g
- base = f"http://127.0.0.1:{port}"
- try:
- with urllib.request.urlopen(base + "/", timeout=SERVER_TIMEOUT) as resp:
- if resp.status != 200:
- g["serves"] = False; g["persists"] = False; return g
- html = resp.read().decode(errors="replace")
- except Exception:
- g["serves"] = False; g["persists"] = False; return g
- g["serves"] = "<form" in html
- if not g["serves"]:
- g["persists"] = False; return g
- data = urllib.parse.urlencode({"title": "BenchNote", "body": "created by the gate"}).encode()
- try:
- req = urllib.request.Request(base + "/", data=data, method="POST")
- with urllib.request.urlopen(req, timeout=SERVER_TIMEOUT) as resp: _ = resp.read()
- except Exception:
- g["persists"] = False; return g
- try:
- with urllib.request.urlopen(base + "/", timeout=SERVER_TIMEOUT) as resp:
- after = resp.read().decode(errors="replace")
- except Exception:
- g["persists"] = False; return g
- g["persists"] = "BenchNote" in after
- if g["persists"] and os.path.exists(dbpath):
- try:
- import sqlite3
- conn = sqlite3.connect(dbpath)
- cur = conn.execute("SELECT count(*) FROM notes WHERE title = 'BenchNote'")
- g["persists"] = cur.fetchone()[0] > 0
- conn.close()
- except Exception: pass
- return g
- finally:
- proc.send_signal(signal.SIGTERM)
- try: proc.wait(timeout=5)
- except subprocess.TimeoutExpired: proc.kill()
- for ext in ("", "-wal", "-shm"):
- p = dbpath + ext
- if os.path.exists(p):
- try: os.remove(p)
- except: pass
-
-# ----------------------------------------------------------------- phases
-def validate():
- print("=== VALIDATION: reference app builds, tests, and serves ===\n")
- tools.set_work_dir(WORK)
- tools.materialize(REFERENCE, dest=WORK)
- r = _run("go mod tidy", WORK, BUILD_TIMEOUT)
- print("go mod tidy:", r[:200])
- g = gates(WORK)
- print(f"gates: {g}")
- ok = all(g.values())
- print(f"\n-> {'OK' if ok else 'BAD'}: reference app is {'buildable + working' if ok else 'BROKEN'}")
- return ok
-
-SYSTEM = (
- "You are a coding agent working in a Go project work dir. You are given "
- "a task plan below. Execute it step by step using the tools. You can "
- "write files, edit files, run builds and tests, and run shell commands "
- "(e.g. `go get`, `go mod tidy`) in the work dir. Keep going until the "
- "build is green, the tests pass, and the binary would work. Use the "
- "tools to verify your own progress — don't guess; compile and test.\n\n"
- "When you are confident the app is complete and the tests pass, say "
- "`DONE` in your final message (no tool call) and stop.\n\n"
- "TASK PLAN:\n" + PLAN
-)
-
-def run():
- tools.set_work_dir(WORK)
- tools.materialize(STARTER, dest=WORK)
- messages = [
- {"role": "system", "content": SYSTEM},
- {"role": "user", "content":
- "The work dir has the starter scaffold (go.mod + a stub main.go). "
- "Execute the task plan. Begin by adding the dependency and writing "
- "the files. Use the tools to build and test as you go."},
- ]
- turns_log = []
- peak_prompt = total_completion = total_reasoning = 0
- finish_reasons = []
- t0 = time.time()
- turns = 0
- done_said = False
- no_tool_streak = 0
- for turn in range(1, MAX_TURNS + 1):
- turns = turn
- try:
- resp, dt = client.call_model(messages, tools=tools.TOOLS, max_tokens=MAX_TOKENS)
- except Exception as e:
- print(f" turn {turn}: REQUEST ERROR {e!r}")
- turns_log.append({"turn": turn, "error": repr(e)})
- break
- u = client.usage(resp)
- peak_prompt = max(peak_prompt, u["prompt_tokens"])
- total_completion += u["completion_tokens"]
- total_reasoning += u["reasoning_tokens"]
- choice = resp["choices"][0]
- fr = choice.get("finish_reason")
- finish_reasons.append(fr)
- msg = choice["message"]
- tcs = msg.get("tool_calls") or []
- content = msg.get("content") or ""
- tlog = {"turn": turn, "dt": round(dt, 1), "prompt_tok": u["prompt_tokens"],
- "completion_tok": u["completion_tokens"], "reasoning_tok": u["reasoning_tokens"],
- "finish_reason": fr, "n_tool_calls": len(tcs)}
- turns_log.append(tlog)
- tc_summary = ",".join((tc["function"]["name"] for tc in tcs)) or "(no tool call)"
- print(f" turn {turn:2d}: {dt:5.1f}s ptok={u['prompt_tokens']:6d} "
- f"ctok={u['completion_tokens']:5d} rtok={u['reasoning_tokens']:5d} "
- f"fr={fr:8s} tools=[{tc_summary}]")
- if not tcs and "DONE" in content.upper():
- done_said = True
- turns_log[-1]["done"] = True
- break
- if not tcs:
- no_tool_streak += 1
- if no_tool_streak >= 2:
- print(" -> giving up after 2 no-tool turns")
- break
- turns_log[-1]["no_tool_streak"] = no_tool_streak
- messages.append({"role": "assistant", "content": content})
- messages.append({"role": "user", "content":
- "You must either call a tool to keep working, or say DONE if "
- "you believe the app is complete and tests pass."})
- continue
- no_tool_streak = 0
- a_msg = {"role": "assistant", "content": content}
- if tcs: a_msg["tool_calls"] = tcs
- messages.append(a_msg)
- for tc in tcs:
- fn = tc["function"]
- name = fn["name"]
- try:
- args = json.loads(fn["arguments"] or "{}")
- except json.JSONDecodeError as e:
- args = {}
- result = (f"ERROR: your tool_call arguments were not valid "
- f"JSON ({e}). Please re-emit the {name} tool call "
- f"with valid JSON arguments.")
- else:
- impl = tools.TOOL_IMPLS.get(name)
- if impl is None:
- result = f"ERROR: unknown tool {name!r}"
- else:
- try:
- result = impl(args)
- except Exception as e:
- result = f"ERROR: {name} raised {e!r}"
- if len(result) > 6000:
- result = result[:6000] + f"\n...[truncated, {len(result)} total chars]"
- messages.append({"role": "tool", "tool_call_id": tc.get("id", ""), "content": result})
- tlog.setdefault("tool_results", []).append({
- "tool": name, "result_len": len(result),
- "result_head": result[:120].replace("\n", " ")})
- wall = time.time() - t0
- g = gates(WORK)
- fr_counter = {}
- for f in finish_reasons:
- if f: fr_counter[f] = fr_counter.get(f, 0) + 1
- rec = {
- "model": client.MODEL, "max_tokens_per_turn": MAX_TOKENS,
- "max_turns": MAX_TURNS, "turns_used": turns, "done_said": done_said,
- "wall_s": round(wall, 1), "peak_prompt_tokens": peak_prompt,
- "total_completion_tokens": total_completion,
- "total_reasoning_tokens": total_reasoning,
- "finish_reasons": fr_counter, "checkpoints": g,
- "all_pass": all(g.values()), "turns_log": turns_log,
- }
- _report(rec)
-
-def _report(rec):
- print("\n===================== AGENTIC BUILD RESULT =====================")
- print(f"model : {rec['model']}")
- print(f"turns used : {rec['turns_used']}/{rec['max_turns']} (done_said={rec['done_said']})")
- print(f"wall clock : {rec['wall_s']}s ({rec['wall_s']/60:.1f} min)")
- print(f"peak prompt tok : {rec['peak_prompt_tokens']}")
- print(f"total completion : {rec['total_completion_tokens']}")
- print(f"total reasoning : {rec['total_reasoning_tokens']}")
- print(f"finish reasons : {rec['finish_reasons']}")
- print()
- print(f"--- checkpoints ---")
- for k, v in rec["checkpoints"].items():
- print(f" {k:10s}: {'PASS' if v else 'fail'}")
- print(f" => {'ALL PASS — real product works' if rec['all_pass'] else 'INCOMPLETE'}")
- write_json(rec, rec["model"], prefix="agentic-build")
- print()
-
-
-
-def main():
- mode = sys.argv[1] if len(sys.argv) > 1 else 'validate'
- if mode == 'validate':
- sys.exit(0 if validate() else 1)
- elif mode == 'run':
- run()
- else:
- print(f'usage: python bench.py agentic-build [validate|run]')
- sys.exit(1)
-
-
-if __name__ == "__main__":
- main()
diff --git a/bench/tasks/agentic_fix.py b/bench/tasks/agentic_fix.py
index 0583922..8e55d84 100644
--- a/bench/tasks/agentic_fix.py
+++ b/bench/tasks/agentic_fix.py
@@ -1,487 +1,295 @@
-"""Agentic fix instrument — multi-turn tool loop over a tiny in-memory codebase.
-
-The model gets a failing Go test and a read-only toolbox (list_files / read_file
-/ search / submit_fix), must explore the code, reason ACROSS files, and submit
-a fix. Scored by compile+run against the hidden test with the real Go toolchain.
-
-Why this shape:
- - Long context: the fix requires tracing Set() in store.go against isExpired()
- in ttl.go; a model that only reads one file cannot find it.
- - Agentic: real tool-call loop (assistant tool_calls -> tool results -> repeat),
- the exact pattern an agent panel drives — not a one-shot prompt.
- - Coherence-under-turns: MAX_TURNS caps runaway loops; we record turns used
- and whether the agent converged, which is where reasoning-loop behavior shows.
-
-Usage (via the bench.py CLI):
- python bench.py agentic-fix validate
- python bench.py agentic-fix run
-
-Env (via .env): ENDPOINT, MODEL, API_KEY, MAX_TOKENS, MAX_TURNS, HTTP_TIMEOUT.
+"""Agentic-fix instrument: bug fixes in two tiers (suite v3, 2026-10-12; absorbed coding-suite).
+
+easy single turn: the symptom and the buggy code in one message; the model answers with the
+ corrected code in a fenced block, which runs against a hidden test with the real toolchain
+ (bench/core/runners.py). Items: bench/tasks/fix_easy/<lang>.py. Swift runs on macOS only;
+ elsewhere its rows are "skipped" (infra), never a fail.
+hard multi-turn, cross-file: the failing test output, then read-only tools (list_files,
+ read_file, search) over a small project and one submit_fix with the complete new contents
+ of ONE file. Gate: the submission is merged, the hidden tests are restored as written, and
+ TEST_CMD must exit 0 with every named test passing. Items: bench/tasks/fix_hard/<item>.py.
+
+ bench.py agentic-fix validate [--tier easy|hard|all] [item ...]
+ bench.py agentic-fix run [--tier easy|hard|all] [item ...] [--samples K --concurrency N
+ --resume RUN_DIR --max-turns T]
+Item sets fix-easy@<hash> and fix-hard@<hash> (separate runs); categories easy/<lang>, hard/<lang>.
"""
+import argparse
+import hashlib
import json
import os
import re
-import sys
-import time
import shutil
-import subprocess
-
-from bench.core import client
-from bench.core.reporting import write_json
-
-HERE = os.path.dirname(os.path.abspath(__file__))
-WORK = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "work", "agentic_fix")
-MAX_TOKENS = int(os.environ.get("MAX_TOKENS", "4000"))
-MAX_TURNS = int(os.environ.get("MAX_TURNS", "24"))
-RUN_TIMEOUT = 120
-
-# ----------------------------------------------------------------- the codebase
-# A small in-memory TTL cache split across files. The bug is cross-file:
-# store.go Set() stores expireAt = now instead of now.Add(ttl), so every
-# entry is born expired. Finding it requires reading BOTH store.go (writes
-# expireAt) and ttl.go (isExpired compares expireAt to now).
-PROJECT = {
-"go.mod": "module kvstore\n\ngo 1.26\n",
-"doc.go": '''// Package kvstore is a small concurrency-safe in-memory key/value cache with
-// per-entry TTL expiry and a background sweeper that evicts expired entries.
-package kvstore
-''',
-"store.go": '''package kvstore
-
-import (
- "sync"
- "time"
-)
-
-type entry struct {
- value any
- expireAt time.Time
- created time.Time
-}
-
-type Store struct {
- mu sync.RWMutex
- items map[string]*entry
- stats *Stats
- opts options
- stopCh chan struct{}
- closed bool
-}
-
-func New(optFns ...Option) *Store {
- o := defaultOptions()
- for _, fn := range optFns {
- fn(&o)
- }
- s := &Store{
- items: make(map[string]*entry),
- stats: &Stats{},
- opts: o,
- stopCh: make(chan struct{}),
- }
- go s.sweepLoop()
- return s
-}
-
-func (s *Store) Set(key string, value any, ttl time.Duration) {
- s.mu.Lock()
- defer s.mu.Unlock()
- now := time.Now()
- e := &entry{value: value, created: now}
- if ttl > 0 {
- e.expireAt = now // BUG: forgets to add ttl -> entry is born expired.
- }
- s.items[key] = e
-}
-
-func (s *Store) Get(key string) (any, bool) {
- s.mu.Lock()
- defer s.mu.Unlock()
- e, ok := s.items[key]
- if !ok {
- s.stats.recordMiss()
- return nil, false
- }
- if isExpired(e, time.Now()) {
- delete(s.items, key)
- s.stats.recordMiss()
- return nil, false
- }
- s.stats.recordHit()
- return e.value, true
-}
-
-func (s *Store) Delete(key string) bool {
- s.mu.Lock()
- defer s.mu.Unlock()
- _, ok := s.items[key]
- delete(s.items, key)
- return ok
-}
-
-func (s *Store) Len() int {
- s.mu.RLock()
- defer s.mu.RUnlock()
- return len(s.items)
-}
-
-func (s *Store) Keys() []string {
- s.mu.RLock()
- defer s.mu.RUnlock()
- ks := make([]string, 0, len(s.items))
- for k := range s.items {
- ks = append(ks, k)
- }
- return ks
-}
-
-func (s *Store) Close() {
- s.mu.Lock()
- defer s.mu.Unlock()
- if !s.closed {
- close(s.stopCh)
- s.closed = true
- }
-}
-''',
-"ttl.go": '''package kvstore
-
-import "time"
-
-func isExpired(e *entry, now time.Time) bool {
- if e.expireAt.IsZero() {
- return false
- }
- return now.After(e.expireAt)
-}
-
-func remaining(e *entry, now time.Time) time.Duration {
- if e.expireAt.IsZero() {
- return 0
- }
- d := e.expireAt.Sub(now)
- if d < 0 {
- return 0
- }
- return d
-}
-''',
-"sweeper.go": '''package kvstore
-
-import "time"
-
-func (s *Store) sweepLoop() {
- t := time.NewTicker(s.opts.sweepInterval)
- defer t.Stop()
- for {
- select {
- case <-s.stopCh:
- return
- case <-t.C:
- s.sweepOnce()
- }
- }
-}
-
-func (s *Store) sweepOnce() {
- now := time.Now()
- s.mu.Lock()
- defer s.mu.Unlock()
- for k, e := range s.items {
- if isExpired(e, now) {
- delete(s.items, k)
- s.stats.recordEviction()
- }
- }
-}
-''',
-"stats.go": '''package kvstore
-
-import "sync/atomic"
-
-type Stats struct {
- hits atomic.Int64
- misses atomic.Int64
- evictions atomic.Int64
-}
-
-func (s *Stats) recordHit() { s.hits.Add(1) }
-func (s *Stats) recordMiss() { s.misses.Add(1) }
-func (s *Stats) recordEviction() { s.evictions.Add(1) }
-
-func (s *Stats) Snapshot() (hits, misses, evictions int64) {
- return s.hits.Load(), s.misses.Load(), s.evictions.Load()
-}
-
-func (s *Store) Stats() *Stats { return s.stats }
-''',
-"options.go": '''package kvstore
-
-import "time"
-
-type options struct {
- sweepInterval time.Duration
-}
-
-type Option func(*options)
-
-func defaultOptions() options {
- return options{sweepInterval: 30 * time.Second}
-}
-
-func WithSweepInterval(d time.Duration) Option {
- return func(o *options) {
- if d > 0 {
- o.sweepInterval = d
- }
- }
-}
-''',
-"store_test.go": '''package kvstore
-
-import (
- "testing"
- "time"
-)
-
-func TestSetThenGetWithinTTL(t *testing.T) {
- s := New(WithSweepInterval(time.Hour))
- defer s.Close()
- s.Set("k", "v", time.Hour)
- got, ok := s.Get("k")
- if !ok {
- t.Fatalf("Get right after Set: want hit, got miss")
- }
- if got != "v" {
- t.Fatalf("Get value = %v, want v", got)
- }
-}
-
-func TestExpiresAfterTTL(t *testing.T) {
- s := New(WithSweepInterval(time.Hour))
- defer s.Close()
- s.Set("k", "v", 10*time.Millisecond)
- time.Sleep(25 * time.Millisecond)
- if _, ok := s.Get("k"); ok {
- t.Fatalf("Get after TTL: want miss, got hit")
- }
-}
-
-func TestZeroTTLNeverExpires(t *testing.T) {
- s := New(WithSweepInterval(time.Hour))
- defer s.Close()
- s.Set("k", "v", 0)
- time.Sleep(15 * time.Millisecond)
- if _, ok := s.Get("k"); !ok {
- t.Fatalf("zero-ttl entry: want hit, got miss")
- }
-}
-''',
-}
-
-FIX = {
-"store.go": PROJECT["store.go"].replace(
- "\t\te.expireAt = now // BUG: forgets to add ttl -> entry is born expired.",
- "\t\te.expireAt = now.Add(ttl)",
-),
-}
-BUG_FILES = ["store.go"]
-
-# ----------------------------------------------------------------- go toolchain
-def _materialize(files):
- shutil.rmtree(WORK, ignore_errors=True)
- os.makedirs(WORK, exist_ok=True)
- for path, content in files.items():
- fp = os.path.join(WORK, path)
- os.makedirs(os.path.dirname(fp), exist_ok=True)
- with open(fp, "w") as f:
- f.write(content)
- return WORK
-
-def _go_test(d):
- try:
- p = subprocess.run(["go", "test", "./..."], cwd=d,
- capture_output=True, text=True, timeout=RUN_TIMEOUT)
- except subprocess.TimeoutExpired:
- return False, "TIMEOUT"
- return p.returncode == 0, (p.stdout + "\n" + p.stderr).strip()
-
-def _apply(base, patch):
- merged = dict(base)
- merged.update(patch)
- return merged
-
-# ----------------------------------------------------------------- tools
-TOOLS = [
+import sys
+
+from bench.core import client, results, tools
+from bench.core.runners import RUNNERS, extract_code, work_dir
+from bench.tasks import agentic_multitask as harness
+from bench.tasks import fix_easy, fix_hard
+
+INSTRUMENT = "agentic-fix"
+EASY_MAX_TOKENS, HARD_MAX_TOKENS = 8000, 4000 # instrument defaults; the lane overrides
+TEMPERATURE = 0.0
+MAX_TURNS = 24
+TEST_TIMEOUT = 300
+LANG_NAMES = {"go": "Go", "rust": "Rust", "ts": "TypeScript", "swift": "Swift", "python": "Python",
+ "sh": "Bash", "sql": "SQL (SQLite)"}
+
+
+# ============================================================ easy tier
+
+def easy_messages(t):
+ lang = LANG_NAMES[t["lang"]]
+ sysmsg = ("You are an expert %s developer. Fix the bug in the code. Respond with ONLY the corrected "
+ "code in a single fenced code block. Keep the same names and signatures. Do NOT add tests, "
+ "a main function, explanations, or extra declarations." % lang)
+ ctx = "%s\n\n" % t["context"] if t.get("context") else ""
+ user = ("%sThe following %s code has a bug. %s\n\n```%s\n%s```\n\nReturn the corrected code."
+ % (ctx, lang, t["symptom"], t["lang"], t["buggy"]))
+ return [{"role": "system", "content": sysmsg}, {"role": "user", "content": user}]
+
+
+def easy_item_set(items):
+ defs = [dict(t, messages=easy_messages(t)) for t in sorted(items, key=lambda t: t["id"])]
+ return "fix-easy@%s" % hashlib.sha256(json.dumps(defs, sort_keys=True).encode()).hexdigest()[:12]
+
+
+def _easy_attempt(store, lane, t, k):
+ def grade(resp):
+ code = extract_code(client.content(resp))
+ ok, detail = (False, "empty answer") if not code.strip() else \
+ RUNNERS[t["lang"]](t, code, work_dir(store.run_id, t["id"], k))
+ row = {"correct": None if ok is None else bool(ok), "code_head": code[:400],
+ "detail_head": (detail or "")[:400]}
+ if ok is None: # toolchain unavailable: not a model failure
+ row["status"] = "skipped"
+ return row
+ results.call_attempt(store, lane, t["id"], k, "easy/" + t["lang"], easy_messages(t), grade,
+ max_tokens=EASY_MAX_TOKENS, temperature=TEMPERATURE)
+
+
+def easy_validate(items, log=print):
+ ok_all = True
+ for t in items:
+ bug_pass, bug_out = RUNNERS[t["lang"]](t, t["buggy"])
+ fix_pass, fix_out = RUNNERS[t["lang"]](t, t["fix"])
+ if bug_pass is None or fix_pass is None:
+ log("[SKIP] %-22s %s" % (t["id"], (fix_out or bug_out).splitlines()[0]))
+ continue
+ ok = (not bug_pass) and fix_pass
+ ok_all = ok_all and ok
+ log("[%s] %-22s buggy_fails=%-5s fix_passes=%s" % ("OK " if ok else "BAD", t["id"], not bug_pass, fix_pass))
+ if bug_pass:
+ log(" !! buggy code PASSED the test")
+ if not fix_pass:
+ log(" !! reference fix FAILED:\n " + fix_out.replace("\n", "\n ")[:800])
+ return ok_all
+
+
+def easy_run(items, a):
+ """items: the whole tier (it defines the item set); a.items selects within it."""
+ plan = lambda _args: (easy_item_set(items), [(t["id"], t) for t in items]) # noqa: E731
+ _store, summary = results.run_attempts(INSTRUMENT, results.run_args(a, tier="easy"), plan,
+ _easy_attempt, resume=a.resume)
+ return 3 if summary["stopped"] else 0
+
+
+# ============================================================ hard tier
+
+HARD_SYSTEM = ("You are a coding agent working in a {lang} project. A test is failing. Use the tools to "
+ "explore the codebase, find the root cause (it may span multiple files), and fix it. When "
+ "you are confident, call submit_fix with the COMPLETE corrected contents of the single file "
+ "that needs changing. Keep every other file untouched and preserve all names and "
+ "signatures. Do not submit until you have read enough to be sure.")
+HARD_USER = "`{cmd}` fails in this project:\n\n```\n{out}\n```\n\nInvestigate with the tools and submit a fix."
+NUDGE = "You must either call a tool to keep investigating or call submit_fix. Do not answer in prose."
+BAD_JSON = "ERROR: invalid JSON args ({e}); re-emit the {name} call."
+CUT_OFF_MSG = ("ERROR: your output hit the max_tokens limit and this call was cut off; it was NOT "
+ "executed. Re-issue it.")
+HARD_TOOLS = [
{"type": "function", "function": {
"name": "list_files", "description": "List all file paths in the project.",
"parameters": {"type": "object", "properties": {}}}},
{"type": "function", "function": {
"name": "read_file", "description": "Return the full contents of one file.",
"parameters": {"type": "object", "properties": {
- "path": {"type": "string", "description": "Project-relative file path"}},
- "required": ["path"]}}},
+ "path": {"type": "string", "description": "Project-relative file path"}}, "required": ["path"]}}},
{"type": "function", "function": {
"name": "search", "description": "Regex-search the whole project; returns matching path:line: text.",
- "parameters": {"type": "object", "properties": {"pattern": {"type": "string"}},
- "required": ["pattern"]}},
- },
+ "parameters": {"type": "object", "properties": {"pattern": {"type": "string"}}, "required": ["pattern"]}}},
{"type": "function", "function": {
- "name": "submit_fix", "description": "Submit the complete corrected contents of ONE file to fix the failing test. Call this exactly once when you have the fix.",
+ "name": "submit_fix",
+ "description": "Submit the complete corrected contents of ONE file to fix the failing test. Call "
+ "this exactly once when you have the fix.",
"parameters": {"type": "object", "properties": {
"path": {"type": "string"},
"content": {"type": "string", "description": "Full new file contents"}},
- "required": ["path", "content"]}},
- },
+ "required": ["path", "content"]}}},
]
-def _tool_result(name, args):
- if name == "list_files":
- return "\n".join(sorted(PROJECT.keys()))
- if name == "read_file":
+
+def run_tests(ws, item, files):
+ """Materialize `files` into a clean work dir and run the item's TEST_CMD -> (rc_ok, output)."""
+ for name in os.listdir(ws.dir):
+ p = os.path.join(ws.dir, name)
+ shutil.rmtree(p) if os.path.isdir(p) and not os.path.islink(p) else os.remove(p)
+ ws.materialize(files)
+ r = ws.run(list(item.TEST_CMD), TEST_TIMEOUT)
+ out = (r.out + "\n" + r.err).strip()
+ return (not r.timed_out and r.rc == 0), ("TIMEOUT\n" + out if r.timed_out else out)
+
+
+def score(ws, item, path, content):
+ """Merge one submitted file, restore the hidden tests, run them -> (passed, detail)."""
+ files = dict(item.PROJECT, **{path: content})
+ files.update({h: item.PROJECT[h] for h in item.HIDDEN})
+ ok, out = run_tests(ws, item, files)
+ passed_names = set(re.findall(item.PASS_RE, out, re.M))
+ missing = [t for t in item.TESTS if t not in passed_names]
+ d = {"tests_passed": len(passed_names & set(item.TESTS)), "tests": len(item.TESTS)}
+ if missing:
+ d["tests_not_passed"] = missing
+ passed = ok and not missing
+ if not passed:
+ d["test_output"] = out[-800:]
+ return passed, d
+
+
+def _hard_toolset(item):
+ def st(ws):
+ ws.state.setdefault("reads", [])
+ ws.state.setdefault("searches", 0)
+ return ws.state
+
+ def list_files(ws, args):
+ return "\n".join(sorted(item.PROJECT))
+
+ def read_file(ws, args):
path = args.get("path", "")
- return PROJECT.get(path, f"ERROR: no such file {path!r}. Use list_files.")
- if name == "search":
+ if not isinstance(path, str):
+ raise tools.ToolError("`path` must be a string")
+ st(ws)["reads"].append(path)
+ return item.PROJECT.get(path, f"ERROR: no such file {path!r}. Use list_files.")
+
+ def search(ws, args):
+ st(ws)["searches"] += 1
pat = args.get("pattern", "")
+ if not isinstance(pat, str):
+ raise tools.ToolError("`pattern` must be a string")
try:
rx = re.compile(pat)
except re.error as e:
return f"ERROR: bad regex: {e}"
- hits = []
- for path, content in sorted(PROJECT.items()):
- for i, line in enumerate(content.splitlines(), 1):
- if rx.search(line):
- hits.append(f"{path}:{i}: {line.strip()}")
+ hits = [f"{p}:{i}: {line.strip()}" for p, c in sorted(item.PROJECT.items())
+ for i, line in enumerate(c.splitlines(), 1) if rx.search(line)]
return "\n".join(hits) if hits else "(no matches)"
- return f"ERROR: unknown tool {name}"
-
-SYSTEM = (
- "You are a coding agent working in a Go project. A test is failing. Use the "
- "tools to explore the codebase, find the root cause (it may span multiple "
- "files), and fix it. When you are confident, call submit_fix with the COMPLETE "
- "corrected contents of the single file that needs changing. Keep every other "
- "file untouched and preserve all names and signatures. Do not submit until you "
- "have read enough to be sure."
-)
-
-def validate():
- print("=== VALIDATION: buggy fails, reference fix passes ===\n")
- d = _materialize(PROJECT)
- bug_pass, bug_out = _go_test(d)
- d = _materialize(_apply(PROJECT, FIX))
- fix_pass, fix_out = _go_test(d)
- ok = (not bug_pass) and fix_pass
- print(f"buggy_fails={not bug_pass} fix_passes={fix_pass} -> {'OK' if ok else 'BAD'}")
- if bug_pass:
- print(" !! buggy project unexpectedly PASSED")
- if not fix_pass:
- print(" !! reference fix FAILED:\n" + fix_out[-1200:])
- return ok
-
-def run():
- d = _materialize(PROJECT)
- _, fail_out = _go_test(d)
- messages = [
- {"role": "system", "content": SYSTEM},
- {"role": "user", "content":
- "`go test ./...` fails in this project:\n\n```\n" + fail_out[-1500:] +
- "\n```\n\nInvestigate with the tools and submit a fix."},
- ]
- reads, searches, submitted = [], 0, None
- t0 = time.time()
- peak_prompt_tokens = 0
- turns = 0
- for turn in range(1, MAX_TURNS + 1):
- turns = turn
- try:
- resp, dt = client.call_model(messages, tools=TOOLS, max_tokens=MAX_TOKENS)
- except Exception as e:
- print(f" turn {turn}: REQUEST ERROR {e!r}")
- submitted = ("__error__", "")
- break
- u = client.usage(resp)
- peak_prompt_tokens = max(peak_prompt_tokens, u["prompt_tokens"])
- msg = resp["choices"][0]["message"]
- tcs = msg.get("tool_calls") or []
- if not tcs:
- content = (msg.get("content") or "")[:200]
- print(f" turn {turn}: no tool call (content={content!r})")
- messages.append({"role": "assistant", "content": msg.get("content") or ""})
- messages.append({"role": "user", "content":
- "You must either call a tool to keep investigating or call "
- "submit_fix. Do not answer in prose."})
- continue
- messages.append({"role": "assistant", "content": msg.get("content") or "",
- "tool_calls": tcs})
- done = False
- for tc in tcs:
- fn = tc["function"]
- name = fn["name"]
- try:
- args = json.loads(fn["arguments"] or "{}")
- except Exception:
- args = {}
- if name == "submit_fix":
- submitted = (args.get("path", ""), args.get("content", ""))
- messages.append({"role": "tool", "tool_call_id": tc.get("id", ""),
- "content": "fix received"})
- done = True
- print(f" turn {turn}: submit_fix({args.get('path','?')}) "
- f"[{len(reads)} reads, {searches} searches]")
- break
- if name == "read_file":
- reads.append(args.get("path", ""))
- elif name == "search":
- searches += 1
- result = _tool_result(name, args)
- messages.append({"role": "tool", "tool_call_id": tc.get("id", ""),
- "content": result})
- if done:
- break
- wall = time.time() - t0
- rec = {"model": client.MODEL, "turns": turns, "reads": reads, "searches": searches,
- "peak_prompt_tokens": peak_prompt_tokens, "wall_s": round(wall, 1)}
- if not submitted or submitted[0] == "__error__":
- rec.update({"passed": False, "reason": "no fix submitted (turn cap or error)"})
- else:
- path, content = submitted
- rec["submitted_path"] = path
- if path not in BUG_FILES:
- rec["note"] = f"submitted {path}, expected one of {BUG_FILES}"
- merged = _apply(PROJECT, {path: content})
- d = _materialize(merged)
- passed, out = _go_test(d)
- rec.update({"passed": bool(passed), "test_output": out[-800:]})
- _report(rec)
- return rec
-
-def _report(rec):
- print("\n===================== AGENTIC FIX RESULT =====================")
- print(f"model : {rec['model']}")
- print(f"passed : {'YES' if rec.get('passed') else 'no'}")
- print(f"turns used : {rec['turns']}/{MAX_TURNS}")
- print(f"files read : {len(rec['reads'])} {rec['reads']}")
- print(f"searches : {rec['searches']}")
- print(f"peak prompt tok : {rec['peak_prompt_tokens']}")
- print(f"wall clock : {rec['wall_s']}s")
- if rec.get("note"):
- print(f"note : {rec['note']}")
- if not rec.get("passed") and rec.get("test_output"):
- print("test output:\n" + rec["test_output"])
- write_json(rec, rec["model"], prefix="agentic-fix")
- print()
-
-
-
-def main():
- mode = sys.argv[1] if len(sys.argv) > 1 else 'validate'
- if mode == 'validate':
- sys.exit(0 if validate() else 1)
- elif mode == 'run':
- run()
- else:
- print(f'usage: python bench.py agentic-fix [validate|run]')
+
+ def submit_fix(ws, args):
+ path, content = args.get("path", ""), args.get("content", "")
+ if not isinstance(path, str) or not path.strip():
+ raise tools.ToolError("submit_fix needs `path`: the project-relative file to replace")
+ norm = os.path.normpath(path)
+ if os.path.isabs(path) or norm == "." or norm.startswith(".."):
+ raise tools.ToolError(f"path {path!r} is not a file inside the project; use list_files")
+ if not isinstance(content, str):
+ raise tools.ToolError("`content` must be the full file contents as a string")
+ st(ws)["submission"] = (norm, content)
+ return tools.ToolResult("fix received", stop=True)
+
+ return tools.Toolset(
+ "fix-hard-readonly", HARD_TOOLS,
+ {"list_files": list_files, "read_file": read_file, "search": search, "submit_fix": submit_fix},
+ cut_off_msg=CUT_OFF_MSG, unknown_fmt="ERROR: unknown tool {name}",
+ commands={"test_gate": " ".join(item.TEST_CMD) + " (hidden tests restored)"})
+
+
+def hard_task(item):
+ def user(ws):
+ if shutil.which(item.TOOL) is None:
+ raise tools.InfraError(f"{item.TOOL} not on PATH")
+ _, out = run_tests(ws, item, item.PROJECT)
+ return HARD_USER.format(cmd=" ".join(item.TEST_CMD), out=out[-1500:])
+
+ def gates(ws, port=None):
+ sub = ws.state.get("submission")
+ if not sub:
+ return {"test": False}, {"reason": "no fix submitted (turn cap or error)"}
+ passed, d = score(ws, item, *sub)
+ return {"test": passed}, d
+
+ def extra(ws):
+ sub = ws.state.get("submission")
+ return {"reads": ws.state.get("reads", []), "searches": ws.state.get("searches", 0),
+ "submitted_path": sub[0] if sub else None,
+ "fixed_file": sub[0] in item.FIX if sub else None}
+
+ def validate(ws, port=None):
+ if shutil.which(item.TOOL) is None:
+ print(f"{item.ITEM_ID}: SKIP, {item.TOOL} not on PATH")
+ return True, {"skipped_no_toolchain": True}, {}
+ (fpath, fcontent), = item.FIX.items()
+ bug_ok, bug_out = run_tests(ws, item, item.PROJECT)
+ g = {"buggy_fails": not bug_ok,
+ "fix_passes": score(ws, item, fpath, fcontent)[0],
+ "gate_rejects_buggy": not score(ws, item, fpath, item.PROJECT[fpath])[0],
+ "gate_rejects_test_rewrite": not score(ws, item, item.HIDDEN[0], "")[0],
+ "wrong_rejected": not any(score(ws, item, *next(iter(w.items())))[0]
+ for w in getattr(item, "WRONG", ()))}
+ return all(g.values()), g, {"buggy_output": bug_out[-300:]}
+
+ return harness.AgenticTask(
+ item_id=item.ITEM_ID, category="hard/" + item.LANG, plan="", starter={},
+ toolset=_hard_toolset(item), gates=gates, gate_names=("test",), validate=validate,
+ system_tmpl=HARD_SYSTEM.format(lang=LANG_NAMES[item.LANG]), user=user, nudge=NUDGE,
+ give_up_after=None, done_word=False, bad_json_fmt=BAD_JSON, trunc_fmt=None,
+ max_tokens=HARD_MAX_TOKENS, temperature=TEMPERATURE, extra=extra,
+ source_files=(os.path.abspath(item.__file__),), prune=("target", "node_modules", ".build"))
+
+
+def hard_tasks():
+ return [hard_task(m) for m in fix_hard.load()]
+
+
+# ============================================================ CLI
+
+def main(argv=None):
+ ap = argparse.ArgumentParser(prog="bench.py " + INSTRUMENT)
+ sub = ap.add_subparsers(dest="cmd")
+ for name in ("validate", "run"):
+ sp = sub.add_parser(name)
+ sp.add_argument("--tier", choices=("easy", "hard", "all"), default="all")
+ sp.add_argument("ids", nargs="*", help="item ids (default: all in the tier)")
+ if name == "run":
+ results.add_run_args(sp)
+ sp.add_argument("--max-turns", type=int, default=None)
+ a = ap.parse_args(sys.argv[1:] if argv is None else argv)
+ if a.cmd is None:
+ ap.print_help()
sys.exit(1)
+ ids = set(a.ids) | {i for i in (getattr(a, "items", "") or "").split(",") if i}
+ easy_all, hard_all = fix_easy.load(), hard_tasks()
+ known = {t["id"] for t in easy_all} | {t.item_id for t in hard_all}
+ if ids - known:
+ raise SystemExit("unknown items: %s" % ", ".join(sorted(ids - known)))
+ tiers = ("easy", "hard") if a.tier == "all" else (a.tier,)
+ easy = [t for t in easy_all if not ids or t["id"] in ids] if "easy" in tiers else []
+ hard = [t for t in hard_all if not ids or t.item_id in ids] if "hard" in tiers else []
+ if a.cmd == "validate":
+ ok = easy_validate(easy) if easy else True
+ ok = (harness.run_validate(hard) if hard else True) and ok
+ sys.exit(0 if ok else 1)
+ if a.resume and a.tier == "all":
+ raise SystemExit("--resume needs --tier easy or --tier hard")
+ rc = 0
+ if easy: # the item set is always the whole tier; ids select within it
+ a.items = ",".join(t["id"] for t in easy) if ids else ""
+ rc = easy_run(easy_all, a)
+ if hard and rc == 0:
+ max_turns = a.max_turns or int(os.environ.get("MAX_TURNS") or MAX_TURNS)
+ harness.run_instrument(INSTRUMENT, "fix-hard", hard_all, samples=a.samples,
+ concurrency=a.concurrency, resume=a.resume, max_turns=max_turns,
+ items=[t.item_id for t in hard] if ids else None)
+ sys.exit(rc)
if __name__ == "__main__":
diff --git a/bench/tasks/agentic_multitask.py b/bench/tasks/agentic_multitask.py
index 9f61b88..1e8bee2 100644
--- a/bench/tasks/agentic_multitask.py
+++ b/bench/tasks/agentic_multitask.py
@@ -1,68 +1,142 @@
-"""Agentic multi-task instrument — the v2-hard gauntlet.
-
-Runs multiple build-a-real-app tasks (each in a different language/framework)
-against one model, sequentially. Each task is a self-contained module under
-`bench/tasks/multitask/` exposing TASK_NAME, PLAN, STARTER, REFERENCE,
-validate(), gates(), TOOLS, TOOL_IMPLS. The harness materializes the
-starter, runs a multi-turn tool loop, then scores via the task's gates().
-
-Shipped tasks (the gauntlet):
- go_htmx — Go + HTMX partials + embedded SQLite + recursive CTE
- rust_cli — Rust + reqwest + quick-xml + async + Digest auth
- ts_next — Next.js + Prisma + Zod validation + API route
-
-These are realistic small-app shapes that test the real agent workload:
-multi-file creation, dependency management, iterative build/test cycles,
-and cross-file reasoning. Add your own by dropping a task module into
-`bench/tasks/multitask/` — it auto-discovers.
-
-Usage (via the bench.py CLI):
- python bench.py agentic-multitask validate go_htmx
- python bench.py agentic-multitask run go_htmx
- python bench.py agentic-multitask cohort go_htmx rust_cli ts_next
-
-Env (via .env): ENDPOINT, MODEL, API_KEY, MAX_TOKENS, MAX_TURNS, TEMPERATURE.
+"""Agentic multi-task instrument + the agentic harness shared with agentic-fix (hard tier) and sleuth.
+
+Each task is a module under bench/tasks/multitask/ (contract in its __init__.py) modelling a
+real small-app shape, so a model is measured on each language/pattern separately. Two tiers
+(suite v3, 2026-10-12), run separately (`run --tier easy|hard|all`, default all):
+ easy go_htmx Go + HTMX partials + embedded SQLite, multi-table schema with a recursive-CTE read
+ ts_next Next.js App Router + Prisma (SQLite) + a Zod-validated API route + server page
+ hard rust_cli Rust + reqwest + quick-xml + tokio CLI fetching XML behind Digest auth (where
+ local models fail most)
+Item sets multitask-easy@<hash> / multitask-hard@<hash>.
+
+One row per (task, sample): category <tier>/<go|rust|ts>, correct = every gate passed, score =
+fraction of gates passed, plus gates, gate_detail, stop_reason (done | max_turns | gave_up |
+<CallError label> | harness_error), turn totals and a per-turn sidecar (turn_log). A CallError
+stops the loop: the row gets its label (correct None) and the gates still run, as information.
+The model's leftover processes are killed BEFORE the gates run (a stale server can't answer a
+gate); heavy build dirs are pruned after them unless --keep-work. go_htmx's "8080" becomes the
+item's free port; ts_next's PLAN names no port, so two concurrent ts_next attempts that run
+`npm run dev` can reach each other's dev server (Next's default 3000).
+item_set covers the task text, tool schema and the task module's source; run.json records the
+harness git sha.
"""
-import importlib.util
+import argparse
+import hashlib
+import importlib
import json
import os
-import re
import sys
import time
+import traceback
+from bench.core import claude_cli
from bench.core import client
+from bench.core import lane as lane_mod
+from bench.core import results
from bench.core import tools
-from bench.core.reporting import write_json, safe_label
HERE = os.path.dirname(os.path.abspath(__file__))
MULTITASK_DIR = os.path.join(HERE, "multitask")
-WORK_BASE = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "work")
-MAX_TOKENS = int(os.environ.get("MAX_TOKENS", "16000"))
-MAX_TURNS = int(os.environ.get("MAX_TURNS", "40"))
-TEMPERATURE = float(os.environ.get("TEMPERATURE", "0"))
+MAX_TOKENS_DEFAULT = 16000
+TEMPERATURE_DEFAULT = 0.0
+MAX_TURNS_DEFAULT = 40
+SYSTEM_TMPL = (
+ "You are a coding agent working in a project work dir. You are given "
+ "a task plan below. Execute it step by step using the tools. You can "
+ "write files, edit files, run builds and tests, and run shell commands "
+ "in the work dir. Keep going until the build is green, the tests pass, "
+ "and the app/binary works. Use the tools to verify your own progress — "
+ "don't guess; compile and test.\n\n"
+ "When you are confident the task is complete and tests pass, say "
+ "`DONE` in your final message (no tool call) and stop.\n\n"
+ "TASK PLAN:\n")
+USER_MSG = ("The work dir has the starter scaffold. Execute the task plan. Begin "
+ "by adding any dependencies and writing the files. Use the tools to "
+ "build and test as you go.")
+NUDGE = ("You must either call a tool to keep working, or say DONE if "
+ "you believe the task is complete and tests pass.")
+BAD_JSON = "ERROR: invalid JSON args ({e}); re-emit the {name} call."
+TRUNC = "\n...[truncated, {n} total]"
+GIVE_UP_AFTER = 2
-def load_task(name):
- path = os.path.join(MULTITASK_DIR, f"{name}.py")
- if not os.path.isfile(path):
- print(f"ERROR: no such task module: {path}", file=sys.stderr)
- sys.exit(2)
- spec = importlib.util.spec_from_file_location(f"task_{name}", path)
- m = importlib.util.module_from_spec(spec)
- spec.loader.exec_module(m)
- return {
- "TASK_NAME": m.TASK_NAME,
- "PLAN": m.PLAN,
- "STARTER": m.STARTER,
- "REFERENCE": m.REFERENCE,
- "validate": m.validate,
- "gates": m.gates,
- "TOOLS": getattr(m, "TOOLS", tools.TOOLS),
- "TOOL_IMPLS": getattr(m, "TOOL_IMPLS", tools.TOOL_IMPLS),
- }
+
+def _sha_file(path):
+ with open(path, "rb") as f:
+ return hashlib.sha256(f.read()).hexdigest()
+
+
+class AgenticTask:
+ """One agentic item: what the model is told, which tools it gets, how it is graded.
+
+ gates(ws, port) -> (dict gate->bool, dict detail); validate(ws, port) -> (ok, g, d).
+ user: str, or callable(ws) -> str (agentic-fix computes the failing-test output).
+ extra(ws) -> dict of instrument-specific row fields (optional)."""
+
+ def __init__(self, *, item_id, category, plan, starter, toolset, gates, gate_names,
+ validate=None, system_tmpl=SYSTEM_TMPL, user=USER_MSG,
+ nudge=NUDGE, give_up_after=GIVE_UP_AFTER, done_word=True,
+ bad_json_fmt=BAD_JSON, trunc_fmt=TRUNC, max_tokens=MAX_TOKENS_DEFAULT,
+ temperature=TEMPERATURE_DEFAULT, port_token=None, env=None,
+ extra=None, source_files=(), prune=("node_modules", "target", ".next")):
+ self.item_id = item_id
+ self.category = category
+ self.plan = plan
+ self.starter = starter
+ self.toolset = toolset
+ self.gates = gates
+ self.gate_names = tuple(gate_names)
+ self.validate = validate
+ self.system_tmpl = system_tmpl
+ self.user = user
+ self.nudge = nudge
+ self.give_up_after = give_up_after
+ self.done_word = done_word
+ self.bad_json_fmt = bad_json_fmt
+ self.trunc_fmt = trunc_fmt
+ self.max_tokens = max_tokens
+ self.temperature = temperature
+ self.port_token = port_token
+ self.env = dict(env or {})
+ self.extra = extra
+ self.source_files = tuple(source_files)
+ self.prune = tuple(prune or ())
+
+ def plan_for(self, port):
+ if self.port_token and port is not None:
+ return self.plan.replace(self.port_token, str(port))
+ return self.plan
+
+ def system_for(self, port):
+ return self.system_tmpl + self.plan_for(port)
+
+ def definition_hash(self):
+ h = hashlib.sha256()
+ parts = [self.item_id, self.category, self.system_tmpl, self.plan,
+ self.user if isinstance(self.user, str) else "<callable>",
+ self.nudge, repr(self.give_up_after), repr(self.done_word), self.bad_json_fmt,
+ repr(self.trunc_fmt), repr(self.port_token), json.dumps(self.env, sort_keys=True),
+ json.dumps(self.starter, sort_keys=True),
+ json.dumps(self.toolset.schema, sort_keys=True),
+ json.dumps(self.toolset.commands, sort_keys=True), repr(self.gate_names)]
+ for p in parts:
+ h.update(p.encode())
+ h.update(b"\0")
+ for f in self.source_files:
+ h.update(_sha_file(f).encode())
+ return h.hexdigest()
+
+
+def item_set(name, tasks):
+ h = hashlib.sha256()
+ for t in sorted(tasks, key=lambda t: t.item_id):
+ h.update(f"{t.item_id}:{t.definition_hash()}\n".encode())
+ return f"{name}@{h.hexdigest()[:12]}"
+# ============================================================ multitask task modules
+
def available_tasks():
if not os.path.isdir(MULTITASK_DIR):
return []
@@ -70,199 +144,314 @@ def available_tasks():
if f.endswith(".py") and not f.startswith("_"))
-def _materialize(files, dest):
- import shutil
- shutil.rmtree(dest, ignore_errors=True)
- os.makedirs(dest, exist_ok=True)
- for path, content in files.items():
- fp = os.path.join(dest, path)
- os.makedirs(os.path.dirname(fp), exist_ok=True)
- with open(fp, "w") as f:
- f.write(content)
- return dest
-
-
-def run_solo(task, work_dir):
- tools.set_work_dir(work_dir)
- task_tools = task.get("TOOLS", tools.TOOLS)
- task_tool_impls = task.get("TOOL_IMPLS", tools.TOOL_IMPLS)
- _materialize(task["STARTER"], dest=work_dir)
- messages = [
- {"role": "system", "content":
- "You are a coding agent working in a project work dir. You are given "
- "a task plan below. Execute it step by step using the tools. You can "
- "write files, edit files, run builds and tests, and run shell commands "
- "in the work dir. Keep going until the build is green, the tests pass, "
- "and the app/binary works. Use the tools to verify your own progress — "
- "don't guess; compile and test.\n\n"
- "When you are confident the task is complete and tests pass, say "
- "`DONE` in your final message (no tool call) and stop.\n\n"
- "TASK PLAN:\n" + task["PLAN"]},
- {"role": "user", "content":
- "The work dir has the starter scaffold. Execute the task plan. Begin "
- "by adding any dependencies and writing the files. Use the tools to "
- "build and test as you go."},
- ]
- turns_log = []
- peak_prompt = total_completion = total_reasoning = 0
- finish_reasons = []
+def reference_validate(reference, gates, prep=()):
+ """validate(ws, port) that grades the reference solution after running the `prep` commands."""
+ def validate(ws, port):
+ ws.materialize(reference)
+ for cmd in prep:
+ print(f"{cmd}: {ws.run(cmd, 600).text()[-300:]}")
+ g, d = gates(ws, port)
+ return all(g.values()), g, d
+ return validate
+
+
+TIERS = {"easy": ("go_htmx", "ts_next"), "hard": ("rust_cli",)}
+
+
+def tier_of(name):
+ return next((t for t, names in TIERS.items() if name in names), "easy")
+
+
+def load_task(name):
+ if name not in available_tasks():
+ raise SystemExit(f"ERROR: no such task module: {name} (available: "
+ f"{', '.join(available_tasks())})")
+ m = importlib.import_module(f"bench.tasks.multitask.{name}")
+ return AgenticTask(
+ item_id=m.TASK_NAME, category=f"{tier_of(name)}/{m.CATEGORY}", plan=m.PLAN, starter=m.STARTER,
+ toolset=m.TOOLSET, gates=m.gates, gate_names=m.GATES,
+ validate=reference_validate(m.REFERENCE, m.gates, getattr(m, "VALIDATE_PREP", ())),
+ port_token=getattr(m, "PORT_TOKEN", None),
+ env=getattr(m, "ENV", None), source_files=(os.path.abspath(m.__file__),))
+
+
+# ============================================================ one attempt
+
+def _sidecar_name(store, base):
+ name, n = base, 1
+ while os.path.exists(os.path.join(store.dir, results.safe_label(name) + ".json")):
+ n += 1
+ name = f"{base}-retry{n}"
+ return name
+
+
+def _report(row, log=print):
+ g = row.get("gates") or {}
+ log(f"\n===================== {row['item_id']} #{row['sample_idx']} =====================")
+ log(f"status / stop : {row.get('status')} / {row.get('stop_reason')}")
+ log(f"turns used : {row.get('turns_used')}/{row.get('max_turns')} "
+ f"(cut-off turns: {row.get('cut_off_turns')})")
+ log(f"wall clock : {row.get('wall_s')}s (loop {row.get('loop_s')}s, "
+ f"gates {row.get('gates_s')}s)")
+ log(f"tokens : prompt {row.get('prompt_tokens')} (peak "
+ f"{row.get('peak_prompt_tokens')}), completion {row.get('completion_tokens')}, "
+ f"reasoning {row.get('reasoning_tokens')}")
+ log(f"finish reasons : {row.get('finish_counts')}")
+ log("--- gates ---")
+ for k, v in g.items():
+ log(f" {k:16s}: {'PASS' if v else 'fail'}")
+ verdict = "ALL PASS" if row.get("correct") else (
+ "NOT GRADED (" + str(row.get("status")) + ")" if row.get("correct") is None else "INCOMPLETE")
+ log(f" => {verdict}")
+ if row.get("gate_detail"):
+ log(f" detail: {json.dumps(row['gate_detail'])[:600]}")
+
+
+def run_item(task, store, sample_idx, *, max_turns, keep_work=False, lane=None, log=print):
+ """Run one (task, sample) attempt end to end and record it; re-raises budget_stop."""
+ lane = lane or lane_mod.current()
+ tag = f"[{task.item_id}#{sample_idx}] "
+ ws_dir = os.path.join(tools.WORK_ROOT, store.run_id, f"{task.item_id}-{sample_idx}")
t0 = time.time()
- turns = 0
- done_said = False
- no_tool_streak = 0
- for turn in range(1, MAX_TURNS + 1):
- turns = turn
- body = {"model": client.MODEL, "messages": messages, "max_tokens": MAX_TOKENS,
- "temperature": TEMPERATURE, "tools": task_tools}
+ loop, harness_err, port = None, None, None
+ with tools.Workspace(ws_dir, env=task.env) as ws:
try:
- resp, dt = client.call_model(messages, tools=task_tools, max_tokens=MAX_TOKENS,
- temperature=TEMPERATURE)
- except Exception as e:
- print(f" turn {turn}: REQUEST ERROR {e!r}")
- turns_log.append({"turn": turn, "error": repr(e)})
- break
- u = client.usage(resp)
- peak_prompt = max(peak_prompt, u["prompt_tokens"])
- total_completion += u["completion_tokens"]
- total_reasoning += u["reasoning_tokens"]
- choice = resp["choices"][0]
- fr = choice.get("finish_reason")
- finish_reasons.append(fr)
- msg = choice["message"]
- tcs = msg.get("tool_calls") or []
- content = msg.get("content") or ""
- tlog = {"turn": turn, "dt": round(dt, 1), "prompt_tok": u["prompt_tokens"],
- "completion_tok": u["completion_tokens"], "reasoning_tok": u["reasoning_tokens"],
- "finish_reason": fr, "n_tool_calls": len(tcs)}
- turns_log.append(tlog)
- tc_summary = ",".join((tc["function"]["name"] for tc in tcs)) or "(no tool call)"
- print(f" turn {turn:2d}: {dt:5.1f}s ptok={u['prompt_tokens']:6d} ctok={u['completion_tokens']:5d} "
- f"rtok={u['reasoning_tokens']:5d} fr={fr:8s} tools=[{tc_summary}]")
- if not tcs and "DONE" in content.upper():
- done_said = True
- tlog["done"] = True
- break
- if not tcs:
- no_tool_streak += 1
- if no_tool_streak >= 2:
- print(" -> giving up after 2 no-tool turns")
- break
- messages.append({"role": "assistant", "content": content})
- messages.append({"role": "user", "content":
- "You must either call a tool to keep working, or say DONE if "
- "you believe the task is complete and tests pass."})
- continue
- no_tool_streak = 0
- a_msg = {"role": "assistant", "content": content}
- if tcs: a_msg["tool_calls"] = tcs
- messages.append(a_msg)
- for tc in tcs:
- fn = tc["function"]
- name = fn["name"]
+ port = ws.allocate_port() if task.port_token else None
+ ws.materialize(task.starter)
+ user = task.user(ws) if callable(task.user) else task.user
+ messages = [{"role": "system", "content": task.system_for(port)},
+ {"role": "user", "content": user}]
+ loop_fn = claude_cli.agent_loop if claude_cli.is_claude(lane) else tools.agent_loop
+ loop = loop_fn(
+ ws, messages, task.toolset, max_turns=max_turns, max_tokens=task.max_tokens,
+ temperature=task.temperature, item_id=task.item_id, run_id=store.run_id,
+ lane=lane, done_word=task.done_word, give_up_after=task.give_up_after,
+ nudge=task.nudge, bad_json_fmt=task.bad_json_fmt, trunc_fmt=task.trunc_fmt,
+ log=log, tag=tag)
+ except Exception as e: # noqa: BLE001 — harness bug: record, still clean up + grade
+ harness_err = e
+ log(f" {tag}HARNESS ERROR {e!r}\n{traceback.format_exc()}")
+ if loop is not None and loop.get("harness_error") is not None:
+ harness_err = loop["harness_error"]
+ loop_s = time.time() - t0
+
+ # The model's leftover processes must not answer the gates.
+ survivors_tools = ws.kill_all()
+ gate_port = port
+ detail_pre = {}
+ if port is not None and not tools.wait_port_free(port, 5):
+ gate_port = ws.allocate_port()
+ detail_pre["port_conflict"] = f"plan port {port} still busy before gates; gate used {gate_port}"
+ tg = time.time()
+ try:
+ g, gd = task.gates(ws, gate_port)
+ gd = dict(detail_pre, **(gd or {}))
+ except Exception as e: # noqa: BLE001
+ g = {k: False for k in task.gate_names}
+ gd = dict(detail_pre, gate_error=repr(e)[:300])
+ log(f" {tag}GATE ERROR {e!r}\n{traceback.format_exc()}")
+ gates_s = time.time() - tg
+ g = {k: bool(v) for k, v in g.items()}
+ survivors = ws.kill_all()
+ released = None
+ if port is not None:
+ released = all(tools.wait_port_free(p, 5) for p in sorted({port, gate_port}))
+ extra = {}
+ if task.extra:
try:
- args = json.loads(fn["arguments"] or "{}")
- except json.JSONDecodeError as e:
- args = {}
- result = f"ERROR: invalid JSON args ({e}); re-emit the {name} call."
- else:
- impl = task_tool_impls.get(name)
- result = impl(args) if impl else f"ERROR: unknown tool {name!r}"
- if len(result) > 6000:
- result = result[:6000] + f"\n...[truncated, {len(result)} total]"
- messages.append({"role": "tool", "tool_call_id": tc.get("id", ""), "content": result})
- tlog.setdefault("tool_results", []).append({
- "tool": name, "result_head": result[:120].replace("\n", " ")})
+ extra = task.extra(ws) or {}
+ except Exception as e: # noqa: BLE001
+ extra = {"extra_error": repr(e)[:200]}
+ if not keep_work and task.prune:
+ tools.prune(ws.dir, task.prune)
wall = time.time() - t0
- gate_results = task["gates"](work_dir)
- fr_counter = {}
- for f in finish_reasons:
- if f: fr_counter[f] = fr_counter.get(f, 0) + 1
- rec = {
- "architecture": "solo",
- "task": task["TASK_NAME"],
- "model": client.MODEL,
- "max_tokens_per_turn": MAX_TOKENS,
- "max_turns": MAX_TURNS,
- "turns_used": turns,
- "done_said": done_said,
- "wall_s": round(wall, 1),
- "peak_prompt_tokens": peak_prompt,
- "total_completion_tokens": total_completion,
- "total_reasoning_tokens": total_reasoning,
- "finish_reasons": fr_counter,
- "checkpoints": gate_results,
- "all_pass": all(gate_results.values()),
- "turns_log": turns_log,
- }
- return rec
-
-
-def _report(rec):
- tag = safe_label(f"{rec['task']}__{rec['model']}")
- print("\n===================== V2-HARD RESULT =====================")
- print(f"task : {rec['task']}")
- print(f"model : {rec['model']}")
- print(f"turns used : {rec['turns_used']}/{rec['max_turns']}")
- print(f"done_said : {rec['done_said']}")
- print(f"wall clock : {rec['wall_s']}s ({rec['wall_s']/60:.1f} min)")
- print(f"peak prompt tok : {rec['peak_prompt_tokens']}")
- print(f"total completion : {rec['total_completion_tokens']}")
- print(f"total reasoning : {rec['total_reasoning_tokens']}")
- print(f"finish reasons : {rec['finish_reasons']}")
- print()
- print("--- gates ---")
- for k, v in rec["checkpoints"].items():
- print(f" {k:16s}: {'PASS' if v else 'fail'}")
- print(f" => {'ALL PASS' if rec['all_pass'] else 'INCOMPLETE'}")
- write_json(rec, tag, prefix="v2hard")
- print()
-
-
-def validate(task_name):
- task = load_task(task_name)
- work_dir = os.path.join(WORK_BASE, f"multitask_validate_{task_name}")
- print(f"=== VALIDATION: {task_name} reference app ===")
- task["validate"](work_dir)
-
-
-def run(task_name):
- task = load_task(task_name)
- work_dir = os.path.join(WORK_BASE, f"multitask_solo_{task_name}")
- rec = run_solo(task, work_dir)
- _report(rec)
-
-
-def cohort(*task_names):
- results = []
- for name in task_names:
- print(f"\n{'='*60}\n=== COHORT: {name} ===\n{'='*60}")
- task = load_task(name)
- work_dir = os.path.join(WORK_BASE, f"multitask_cohort_{name}")
- rec = run_solo(task, work_dir)
- _report(rec)
- results.append(rec)
- print(f"\n{'='*60}\n=== COHORT SUMMARY ===\n{'='*60}")
- print(f"{'task':16s} {'gates':>6s} {'wall':>8s} {'turns':>6s} {'comp tok':>9s} {'rsn tok':>9s}")
- for r in results:
- g = 'PASS' if r['all_pass'] else 'fail'
- print(f"{r['task']:16s} {g:>6s} {r['wall_s']/60:>7.1f}m {r['turns_used']:>6} {r['total_completion_tokens']:>9,} {r['total_reasoning_tokens']:>9,}")
-
-
-def main():
- if len(sys.argv) < 2:
- print(f"usage: python bench.py agentic-multitask [validate|run|cohort] <task>...")
- print(f"available tasks: {', '.join(available_tasks())}")
- sys.exit(1)
- cmd = sys.argv[1]
- if cmd == "validate":
- validate(sys.argv[2])
- elif cmd == "run":
- run(sys.argv[2])
- elif cmd == "cohort":
- cohort(*sys.argv[2:])
+
+ n_pass = sum(1 for v in g.values() if v)
+ row = {"gates": g, "gate_detail": gd, "max_turns": max_turns,
+ "loop_s": round(loop_s, 2), "gates_s": round(gates_s, 2),
+ "port": port, "port_released": released,
+ "survivors": len(survivors_tools) + len(survivors),
+ "item_hash": task.definition_hash()[:12], "work_dir": os.path.relpath(ws_dir, tools.WORK_ROOT)}
+ row.update(extra)
+ if harness_err is not None:
+ status_fields = client.error_meta(harness_err, wall)
+ row.update(status_fields)
+ row["stop_reason"] = "harness_error"
+ correct, score = None, None
+ elif loop["error"] is not None:
+ row.update(client.error_meta(loop["error"], wall))
+ row["error_call_s"] = round(loop["error_dt"] or 0, 2)
+ row["stop_reason"] = loop["stop_reason"]
+ correct, score = None, None
else:
- print(f"unknown command: {cmd}")
- sys.exit(1)
+ row["status"] = "ok"
+ row["stop_reason"] = loop["stop_reason"]
+ row["wall_s"] = round(wall, 2)
+ correct = bool(g) and n_pass == len(g)
+ score = round(n_pass / len(g), 4) if g else 0.0
+ if loop is not None:
+ row.update(loop.get("row_extra") or {})
+ last = loop.get("last_resp")
+ b = (last or {}).get("_bench") or {}
+ row.update({k: loop[k] for k in ("turns_used", "cut_off_turns", "prompt_tokens",
+ "completion_tokens", "reasoning_tokens",
+ "peak_prompt_tokens", "cost_usd", "finish_counts",
+ "tool_calls", "model_s")})
+ row["finish"] = client.finish_reason(last) if last else None
+ row["request_hash"] = b.get("request_hash")
+ rt = [t.get("reasoning_tokens") for t in loop["turns"] if t.get("reasoning_tokens") is not None]
+ row["max_reasoning_in_a_turn"] = max(rt) if rt else None
+ row["long_think_turns"] = sum(1 for r in rt if r > 4000) if rt else None
+ else:
+ row.update({"turns_used": 0, "cut_off_turns": 0})
+ side = {"item_id": task.item_id, "sample_idx": sample_idx, "stop_reason": row["stop_reason"],
+ "status": row.get("status"), "plan_port": port, "gates": g, "gate_detail": gd,
+ "toolset": task.toolset.describe(), "turns": (loop or {}).get("turns", [])}
+ if harness_err is not None:
+ side["harness_error"] = traceback.format_exception_only(type(harness_err), harness_err)
+ row["turn_log"] = store.sidecar(_sidecar_name(store, f"{task.item_id}-{sample_idx}.turns"), side)
+ row = store.add(item_id=task.item_id, sample_idx=sample_idx, category=task.category,
+ correct=correct, score=score, **row)
+ _report(row, log)
+ if loop is not None and loop["error"] is not None and loop["error"].label() == "budget_stop":
+ raise loop["error"]
+ return row
+
+
+# ============================================================ a run
+
+def _print_table(rows, log=print):
+ log(f"\n{'=' * 60}\n=== SUMMARY ===\n{'=' * 60}")
+ log(f"{'task':16s} {'#':>2s} {'gates':>8s} {'stop':>12s} {'wall':>8s} {'turns':>6s} "
+ f"{'comp tok':>9s} {'rsn tok':>9s} {'cut':>4s}")
+ for r in rows:
+ g = r.get("gates") or {}
+ gs = f"{sum(1 for v in g.values() if v)}/{len(g)}"
+ rt = r.get("reasoning_tokens")
+ log(f"{r['item_id']:16s} {r['sample_idx']:>2d} {gs:>8s} {str(r.get('stop_reason'))[:12]:>12s} "
+ f"{(r.get('wall_s') or 0) / 60:>7.1f}m {r.get('turns_used', 0):>6} "
+ f"{(r.get('completion_tokens') or 0):>9,} {('-' if rt is None else format(rt, ',')):>9s} "
+ f"{r.get('cut_off_turns', 0):>4}")
+
+
+def run_instrument(instrument, set_name, tasks, *, samples=1, concurrency=1, resume=None,
+ max_turns=MAX_TURNS_DEFAULT, items=None, keep_work=False, lane=None,
+ log=print):
+ """Run every (task, sample) not yet done; returns the run dir."""
+ args = {"items": items, "samples": samples, "concurrency": concurrency,
+ "max_turns": max_turns, "keep_work": keep_work,
+ "defaults": {t.item_id: {"max_tokens": t.max_tokens, "temperature": t.temperature}
+ for t in tasks},
+ "toolsets": {t.item_id: t.toolset.describe() for t in tasks},
+ "env": {t.item_id: t.env for t in tasks if t.env},
+ "work_root": tools.WORK_ROOT}
+
+ def attempt(store, lane, task, k):
+ a = store.run["args"]
+ log(f"\n{'=' * 60}\n=== {task.item_id} sample {k} ===\n{'=' * 60}")
+ run_item(task, store, k, max_turns=a["max_turns"], keep_work=a.get("keep_work"),
+ lane=lane, log=log)
+
+ plan = lambda _args: (item_set(set_name, tasks), [(t.item_id, t) for t in tasks]) # noqa: E731
+ store, _summary = results.run_attempts(instrument, args, plan, attempt, resume=resume,
+ lane=lane, log=log)
+ _print_table(store.rows(), log)
+ return store.dir
+
+
+def run_validate(tasks, log=print):
+ """Reference solutions against the gates, offline (no model)."""
+ stamp = time.strftime("%Y%m%d-%H%M%S")
+ ok_all = True
+ for t in tasks:
+ if t.validate is None:
+ log(f"{t.item_id}: no reference solution to validate")
+ continue
+ log(f"=== VALIDATION: {t.item_id} reference ===")
+ with tools.Workspace(os.path.join(tools.WORK_ROOT, f"validate-{stamp}", t.item_id),
+ env=t.env) as ws:
+ port = ws.allocate_port() if t.port_token else None
+ try:
+ ok, g, d = t.validate(ws, port)
+ except Exception as e: # noqa: BLE001
+ ok, g, d = False, {}, {"error": repr(e)}
+ log(traceback.format_exc())
+ survivors = ws.kill_all()
+ released = tools.wait_port_free(port, 5) if port is not None else None
+ if t.prune:
+ tools.prune(ws.dir, t.prune)
+ log(f"{t.item_id}: gates={g} -> {'OK' if ok else 'BAD'}"
+ f"{'' if not d else ' detail=' + json.dumps(d)[:600]}"
+ f"{'' if released in (None, True) else ' PORT NOT RELEASED'}"
+ f"{'' if not survivors else ' SURVIVORS ' + str(survivors)}")
+ ok_all = ok_all and ok and released is not False and not survivors
+ return ok_all
+
+
+# ============================================================ CLI
+
+def _parser(prog, multi):
+ p = argparse.ArgumentParser(prog=prog)
+ sub = p.add_subparsers(dest="cmd")
+ for name in (("run", "cohort", "validate") if multi else ("run", "validate")):
+ sp = sub.add_parser(name)
+ if multi:
+ sp.add_argument("tasks", nargs="*", help="task names (default: all)")
+ if name == "validate":
+ sp.add_argument("--items", default="", help="comma-separated item ids")
+ continue
+ results.add_run_args(sp)
+ sp.add_argument("--max-turns", type=int, default=None,
+ help="tool-loop cap (default: $MAX_TURNS, else per instrument)")
+ sp.add_argument("--keep-work", action="store_true",
+ help="keep node_modules/target/.next in work dirs")
+ return p
+
+
+def cli_main(instrument, set_name, all_tasks, argv, *, multi, default_cmd, max_turns_default,
+ log=print):
+ """Shared CLI. all_tasks: list of AgenticTask (multi: loaded lazily from names)."""
+ argv = list(argv)
+ if not argv:
+ argv = [default_cmd]
+ p = _parser(f"bench.py {instrument}", multi)
+ a = p.parse_args(argv)
+ if a.cmd is None:
+ p.print_help()
+ return 1
+ names = [t.item_id for t in all_tasks]
+ sel = list(getattr(a, "tasks", []) or [])
+ sel += [i for i in (a.items or "").split(",") if i]
+ for s in sel:
+ if s not in names:
+ p.error(f"unknown task {s!r}; available: {', '.join(names)}")
+ if a.cmd == "validate":
+ chosen = [t for t in all_tasks if not sel or t.item_id in sel]
+ return 0 if run_validate(chosen, log=log) else 1
+ if a.cmd == "cohort" and not sel:
+ p.error("cohort needs task names")
+ max_turns = a.max_turns or int(os.environ.get("MAX_TURNS") or max_turns_default)
+ run_instrument(instrument, set_name, all_tasks, samples=a.samples,
+ concurrency=a.concurrency, resume=a.resume, max_turns=max_turns,
+ items=sel or None, keep_work=a.keep_work, log=log)
+ return 0
+
+
+def main(argv=None):
+ pre = argparse.ArgumentParser(add_help=False)
+ pre.add_argument("--tier", choices=("easy", "hard", "all"), default="all")
+ a, rest = pre.parse_known_args(sys.argv[1:] if argv is None else argv)
+ named = [x for x in rest if x in available_tasks()]
+ tiers = [t for t in (("easy", "hard") if a.tier == "all" else (a.tier,))
+ if not named or set(named) & set(TIERS[t])]
+ if not tiers:
+ raise SystemExit(f"--tier {a.tier} has none of {named}; tiers: {TIERS}")
+ rc = 0
+ for tier in tiers:
+ args = [x for x in rest if x not in named or x in TIERS[tier]]
+ rc = cli_main("agentic-multitask", f"multitask-{tier}", [load_task(n) for n in TIERS[tier]],
+ args, multi=True, default_cmd="--help", max_turns_default=MAX_TURNS_DEFAULT) or rc
+ sys.exit(rc)
if __name__ == "__main__":
diff --git a/bench/tasks/coding_suite.py b/bench/tasks/coding_suite.py
deleted file mode 100644
index 812c02c..0000000
--- a/bench/tasks/coding_suite.py
+++ /dev/null
@@ -1,421 +0,0 @@
-"""Coding-suite instrument — single-turn bug-fix + tool-calling tasks.
-
-Two tiers of difficulty. Each bug-fix answer is compiled and run against
-hidden tests with the real toolchain (Go/Rust/Swift/TS/Python). Tool-calling
-answers are parse-validated. The suite is pre-validated (buggy provably
-fails, reference fix provably passes) by the `validate` command.
-
-Usage (via the bench.py CLI):
- python bench.py coding-suite validate
- python bench.py coding-suite run
- python bench.py coding-suite report
-
-Env (via .env): ENDPOINT, MODEL, API_KEY, MAX_TOKENS, TEMPERATURE.
-"""
-import json
-import os
-import re
-import sys
-
-from bench.core import client
-from bench.core.runners import RUNNERS, extract_code
-from bench.core.reporting import jsonl_path, append_jsonl, write_json, coding_suite_summary
-
-HERE = os.path.dirname(os.path.abspath(__file__))
-
-# ---------------------------------------------------------------- task registry
-# Tier 1 — straightforward bug-fixes
-BUGFIX_T1 = [
- {
- "id": "go-average", "lang": "go", "cat": "bugfix",
- "symptom": "It should return the arithmetic mean as a float, but returns truncated values (e.g. 1 instead of 1.5 for [1,2]).",
- "buggy": "package solution\n\nfunc Average(xs []int) float64 {\n\tsum := 0\n\tfor _, x := range xs {\n\t\tsum += x\n\t}\n\treturn float64(sum / len(xs))\n}\n",
- "fix": "package solution\n\nfunc Average(xs []int) float64 {\n\tsum := 0\n\tfor _, x := range xs {\n\t\tsum += x\n\t}\n\treturn float64(sum) / float64(len(xs))\n}\n",
- "test": 'package solution\n\nimport "testing"\n\nfunc almost(a, b float64) bool { d := a - b; if d < 0 { d = -d }; return d < 1e-9 }\n\nfunc TestAverage(t *testing.T) {\n\tif !almost(Average([]int{1, 2}), 1.5) { t.Fatalf("[1,2]=%v want 1.5", Average([]int{1, 2})) }\n\tif !almost(Average([]int{2, 2, 2}), 2.0) { t.Fatalf("[2,2,2]=%v want 2", Average([]int{2, 2, 2})) }\n\tif !almost(Average([]int{1, 2, 3, 4}), 2.5) { t.Fatalf("[1,2,3,4]=%v want 2.5", Average([]int{1, 2, 3, 4})) }\n}\n',
- },
- {
- "id": "go-nilmap", "lang": "go", "cat": "bugfix",
- "symptom": "It panics at runtime ('assignment to entry in nil map') instead of grouping the integers by parity.",
- "buggy": 'package solution\n\nfunc GroupByParity(xs []int) map[string][]int {\n\tvar m map[string][]int\n\tfor _, x := range xs {\n\t\tif x%2 == 0 {\n\t\t\tm["even"] = append(m["even"], x)\n\t\t} else {\n\t\t\tm["odd"] = append(m["odd"], x)\n\t\t}\n\t}\n\treturn m\n}\n',
- "fix": 'package solution\n\nfunc GroupByParity(xs []int) map[string][]int {\n\tm := make(map[string][]int)\n\tfor _, x := range xs {\n\t\tif x%2 == 0 {\n\t\t\tm["even"] = append(m["even"], x)\n\t\t} else {\n\t\t\tm["odd"] = append(m["odd"], x)\n\t\t}\n\t}\n\treturn m\n}\n',
- "test": 'package solution\n\nimport (\n\t"reflect"\n\t"testing"\n)\n\nfunc TestGroup(t *testing.T) {\n\tgot := GroupByParity([]int{1, 2, 3, 4})\n\twant := map[string][]int{"odd": {1, 3}, "even": {2, 4}}\n\tif !reflect.DeepEqual(got, want) { t.Fatalf("got %v want %v", got, want) }\n}\n',
- },
- {
- "id": "rust-sumeven", "lang": "rust", "cat": "bugfix",
- "symptom": "sum_even is supposed to sum the EVEN numbers, but it currently sums the odd ones (e.g. returns 4 instead of 6 for [1,2,3,4]).",
- "buggy": "pub fn sum_even(v: &[i32]) -> i32 {\n v.iter().filter(|&&x| x % 2 == 1).sum()\n}\n",
- "fix": "pub fn sum_even(v: &[i32]) -> i32 {\n v.iter().filter(|&&x| x % 2 == 0).sum()\n}\n",
- "test": "#[cfg(test)]\nmod hidden {\n use super::*;\n #[test]\n fn t() {\n assert_eq!(sum_even(&[1, 2, 3, 4]), 6);\n assert_eq!(sum_even(&[2, 4, 6]), 12);\n assert_eq!(sum_even(&[1, 3, 5]), 0);\n }\n}\n",
- },
- {
- "id": "rust-safediv", "lang": "rust", "cat": "bugfix",
- "symptom": "safe_div should return none when dividing by zero, but it panics (attempt to divide by zero) instead.",
- "buggy": "pub fn safe_div(a: i32, b: i32) -> Option<i32> {\n Some(a / b)\n}\n",
- "fix": "pub fn safe_div(a: i32, b: i32) -> Option<i32> {\n if b == 0 { None } else { Some(a / b) }\n}\n",
- "test": "#[cfg(test)]\nmod hidden {\n use super::*;\n #[test]\n fn t() {\n assert_eq!(safe_div(10, 2), Some(5));\n assert_eq!(safe_div(7, 0), None);\n assert_eq!(safe_div(-6, 3), Some(-2));\n }\n}\n",
- },
- {
- "id": "swift-parseage", "lang": "swift", "cat": "bugfix",
- "symptom": "parseAge should return nil for non-numeric input, but it crashes (force-unwrap of nil) on input like \"abc\".",
- "buggy": "func parseAge(_ s: String) -> Int? {\n return Int(s)!\n}\n",
- "fix": "func parseAge(_ s: String) -> Int? {\n return Int(s)\n}\n",
- "test": 'import Foundation\n\nfunc check(_ cond: Bool, _ msg: String) {\n if !cond { FileHandle.standardError.write(("FAIL: " + msg + "\\n").data(using: .utf8)!); exit(1) }\n}\n\ncheck(parseAge("34") == 34, "parseAge(34)")\ncheck(parseAge("abc") == nil, "parseAge(abc) should be nil")\ncheck(parseAge("0") == 0, "parseAge(0)")\nprint("OK")\n',
- },
- {
- "id": "swift-median", "lang": "swift", "cat": "bugfix",
- "symptom": "median returns the wrong value because it indexes the array without sorting it first (e.g. median([3,1,2]) returns 1 instead of 2).",
- "buggy": "func median(_ xs: [Double]) -> Double {\n let n = xs.count\n if n % 2 == 1 {\n return xs[n / 2]\n } else {\n return (xs[n / 2 - 1] + xs[n / 2]) / 2\n }\n}\n",
- "fix": "func median(_ xs: [Double]) -> Double {\n let s = xs.sorted()\n let n = s.count\n if n % 2 == 1 {\n return s[n / 2]\n } else {\n return (s[n / 2 - 1] + s[n / 2]) / 2\n }\n}\n",
- "test": 'import Foundation\n\nfunc check(_ cond: Bool, _ msg: String) {\n if !cond { FileHandle.standardError.write(("FAIL: " + msg + "\\n").data(using: .utf8)!); exit(1) }\n}\n\ncheck(median([3, 1, 2]) == 2, "median odd")\ncheck(median([4, 1, 3, 2]) == 2.5, "median even")\ncheck(median([10, 2, 8, 4]) == 6, "median even2")\nprint("OK")\n',
- },
- {
- "id": "ts-sort", "lang": "ts", "cat": "bugfix",
- "symptom": "sortNums sorts numbers lexicographically instead of numerically (e.g. [10,2,1] becomes [1,10,2] instead of [1,2,10]).",
- "buggy": "export function sortNums(a: number[]): number[] {\n return a.sort();\n}\n",
- "fix": "export function sortNums(a: number[]): number[] {\n return [...a].sort((x, y) => x - y);\n}\n",
- "test": 'import { sortNums } from "./solution";\nfunction eq(a: number[], b: number[]) { return a.length === b.length && a.every((v, i) => v === b[i]); }\nlet ok = true;\nif (!eq(sortNums([10, 2, 1]), [1, 2, 10])) { console.error("FAIL sort1"); ok = false; }\nif (!eq(sortNums([3, 30, 1, 2]), [1, 2, 3, 30])) { console.error("FAIL sort2"); ok = false; }\nif (!ok) process.exit(1);\nconsole.log("OK");\n',
- },
- {
- "id": "ts-reduce", "lang": "ts", "cat": "bugfix",
- "symptom": "total throws a TypeError on an empty array because reduce has no initial value; total([]) should be 0.",
- "buggy": "export function total(arr: number[]): number {\n return arr.reduce((a, b) => a + b);\n}\n",
- "fix": "export function total(arr: number[]): number {\n return arr.reduce((a, b) => a + b, 0);\n}\n",
- "test": 'import { total } from "./solution";\nlet ok = true;\nif (total([1, 2, 3]) !== 6) { console.error("FAIL t1"); ok = false; }\nif (total([]) !== 0) { console.error("FAIL empty"); ok = false; }\nif (total([5]) !== 5) { console.error("FAIL t3"); ok = false; }\nif (!ok) process.exit(1);\nconsole.log("OK");\n',
- },
-]
-
-# Tier 2 — harder, discriminating bug-fixes (type reasoning, language traps)
-BUGFIX_T2 = [
- {
- "id": "go-json-tags", "lang": "go", "cat": "bugfix",
- "symptom": "ToJSON should produce JSON with exactly the keys \"name\", \"emailAddress\", and \"age\", but the name key comes out capitalized and the age field is missing.",
- "buggy": 'package solution\n\nimport "encoding/json"\n\ntype User struct {\n\tName string\n\tEmail string `json:"emailAddress"`\n\tage int `json:"age"`\n}\n\nfunc ToJSON(name, email string, age int) (string, error) {\n\tu := User{Name: name, Email: email, age: age}\n\tb, err := json.Marshal(u)\n\treturn string(b), err\n}\n',
- "fix": 'package solution\n\nimport "encoding/json"\n\ntype User struct {\n\tName string `json:"name"`\n\tEmail string `json:"emailAddress"`\n\tAge int `json:"age"`\n}\n\nfunc ToJSON(name, email string, age int) (string, error) {\n\tu := User{Name: name, Email: email, Age: age}\n\tb, err := json.Marshal(u)\n\treturn string(b), err\n}\n',
- "test": 'package solution\n\nimport (\n\t"encoding/json"\n\t"testing"\n)\n\nfunc TestToJSON(t *testing.T) {\n\ts, err := ToJSON("Ada", "ada@x.com", 36)\n\tif err != nil { t.Fatal(err) }\n\tvar m map[string]interface{}\n\tif err := json.Unmarshal([]byte(s), &m); err != nil { t.Fatal(err) }\n\tif m["name"] != "Ada" { t.Fatalf("name key wrong; got map %v", m) }\n\tif m["emailAddress"] != "ada@x.com" { t.Fatalf("email key wrong; got %v", m) }\n\tif m["age"] != float64(36) { t.Fatalf("age key wrong/missing; got %v", m) }\n}\n',
- },
- {
- "id": "go-generics", "lang": "go", "cat": "bugfix",
- "symptom": "MapSlice should return a new slice with f applied to each element, but the result has extra leading zero values (e.g. [0 0 0 2 4 6] instead of [2 4 6]).",
- "buggy": "package solution\n\nfunc MapSlice[T any, U any](xs []T, f func(T) U) []U {\n\tresult := make([]U, len(xs))\n\tfor _, x := range xs {\n\t\tresult = append(result, f(x))\n\t}\n\treturn result\n}\n",
- "fix": "package solution\n\nfunc MapSlice[T any, U any](xs []T, f func(T) U) []U {\n\tresult := make([]U, 0, len(xs))\n\tfor _, x := range xs {\n\t\tresult = append(result, f(x))\n\t}\n\treturn result\n}\n",
- "test": 'package solution\n\nimport (\n\t"reflect"\n\t"testing"\n)\n\nfunc TestMapSlice(t *testing.T) {\n\tgot := MapSlice([]int{1, 2, 3}, func(x int) int { return x * 2 })\n\tif !reflect.DeepEqual(got, []int{2, 4, 6}) { t.Fatalf("got %v want [2 4 6]", got) }\n\tgs := MapSlice([]int{1, 2}, func(x int) string { return string(rune(\'a\' + x)) })\n\tif !reflect.DeepEqual(gs, []string{"b", "c"}) { t.Fatalf("got %v want [b c]", gs) }\n}\n',
- },
- {
- "id": "rust-sumall", "lang": "rust", "cat": "bugfix",
- "symptom": "sum_all does not compile because the generic type T is unconstrained. It should sum any slice of numbers (integers or floats) and return the total.",
- "buggy": "pub fn sum_all<T>(items: &[T]) -> T {\n let mut total = 0;\n for x in items {\n total += x;\n }\n total\n}\n",
- "fix": "pub fn sum_all<T: Copy + std::iter::Sum<T>>(items: &[T]) -> T {\n items.iter().copied().sum()\n}\n",
- "test": "#[cfg(test)]\nmod hidden {\n use super::*;\n #[test]\n fn t() {\n assert_eq!(sum_all(&[1, 2, 3]), 6);\n assert_eq!(sum_all(&[10, 20]), 30);\n let f: f64 = sum_all(&[1.5, 2.5]);\n assert!((f - 4.0).abs() < 1e-9);\n }\n}\n",
- },
- {
- "id": "rust-dedup", "lang": "rust", "cat": "bugfix",
- "symptom": "dedup_sorted should sort the vector and remove consecutive duplicates in place, but it panics with an index-out-of-bounds error.",
- "buggy": "pub fn dedup_sorted(v: &mut Vec<i32>) {\n v.sort();\n for i in 1..v.len() {\n if v[i] == v[i - 1] {\n v.remove(i);\n }\n }\n}\n",
- "fix": "pub fn dedup_sorted(v: &mut Vec<i32>) {\n v.sort();\n v.dedup();\n}\n",
- "test": "#[cfg(test)]\nmod hidden {\n use super::*;\n #[test]\n fn t() {\n let mut a = vec![3, 1, 2, 2, 3, 1];\n dedup_sorted(&mut a);\n assert_eq!(a, vec![1, 2, 3]);\n let mut b = vec![5, 5, 5];\n dedup_sorted(&mut b);\n assert_eq!(b, vec![5]);\n }\n}\n",
- },
- {
- "id": "swift-generic-max", "lang": "swift", "cat": "bugfix",
- "symptom": "maxElement does not compile because the generic type T is not constrained. It should return the largest element, or nil for an empty array.",
- "buggy": "func maxElement<T>(_ xs: [T]) -> T? {\n guard !xs.isEmpty else { return nil }\n var m = xs[0]\n for x in xs {\n if x > m { m = x }\n }\n return m\n}\n",
- "fix": "func maxElement<T: Comparable>(_ xs: [T]) -> T? {\n guard !xs.isEmpty else { return nil }\n var m = xs[0]\n for x in xs {\n if x > m { m = x }\n }\n return m\n}\n",
- "test": 'import Foundation\n\nfunc check(_ cond: Bool, _ msg: String) {\n if !cond { FileHandle.standardError.write(("FAIL: " + msg + "\\n").data(using: .utf8)!); exit(1) }\n}\n\ncheck(maxElement([3, 1, 2]) == 3, "max ints")\ncheck(maxElement([Int]()) == nil, "max empty")\ncheck(maxElement(["b", "a", "c"]) == "c", "max strings")\nprint("OK")\n',
- },
- {
- "id": "swift-mutating", "lang": "swift", "cat": "bugfix",
- "symptom": "This code does not compile: a struct method modifies a stored property, and the calling code prevents mutation. After fixing, runCounter(5) must return 5.",
- "buggy": "struct Counter {\n var count = 0\n func increment() {\n count += 1\n }\n}\n\nfunc runCounter(_ times: Int) -> Int {\n let c = Counter()\n for _ in 0..<times { c.increment() }\n return c.count\n}\n",
- "fix": "struct Counter {\n var count = 0\n mutating func increment() {\n count += 1\n }\n}\n\nfunc runCounter(_ times: Int) -> Int {\n var c = Counter()\n for _ in 0..<times { c.increment() }\n return c.count\n}\n",
- "test": 'import Foundation\n\nfunc check(_ cond: Bool, _ msg: String) {\n if !cond { FileHandle.standardError.write(("FAIL: " + msg + "\\n").data(using: .utf8)!); exit(1) }\n}\n\ncheck(runCounter(5) == 5, "runCounter(5)")\ncheck(runCounter(0) == 0, "runCounter(0)")\nprint("OK")\n',
- },
- {
- "id": "ts-matrix-alias", "lang": "ts", "cat": "bugfix",
- "symptom": "makeMatrix should return independent rows, but every row is the SAME array reference (writing to one row changes them all).",
- "buggy": "export function makeMatrix(rows: number, cols: number): number[][] {\n return new Array(rows).fill(new Array(cols).fill(0));\n}\n",
- "fix": "export function makeMatrix(rows: number, cols: number): number[][] {\n return Array.from({ length: rows }, () => new Array(cols).fill(0));\n}\n",
- "test": 'import { makeMatrix } from "./solution";\nconst m = makeMatrix(2, 2);\nm[0][0] = 5;\nif (m[1][0] !== 0) { console.error("FAIL aliasing", m); process.exit(1); }\nif (m.length !== 2 || m[0].length !== 2) { console.error("FAIL shape", m); process.exit(1); }\nconsole.log("OK");\n',
- },
- {
- "id": "ts-closure-var", "lang": "ts", "cat": "bugfix",
- "symptom": "makeAdders should return functions that return 0, 1, and 2, but every function returns 3 (they all share the same loop variable).",
- "buggy": "export function makeAdders(): Array<() => number> {\n const fns: Array<() => number> = [];\n for (var i = 0; i < 3; i++) {\n fns.push(() => i);\n }\n return fns;\n}\n",
- "fix": "export function makeAdders(): Array<() => number> {\n const fns: Array<() => number> = [];\n for (let i = 0; i < 3; i++) {\n fns.push(() => i);\n }\n return fns;\n}\n",
- "test": 'import { makeAdders } from "./solution";\nconst vals = makeAdders().map((f) => f());\nfunction eq(a: number[], b: number[]) { return a.length === b.length && a.every((v, i) => v === b[i]); }\nif (!eq(vals, [0, 1, 2])) { console.error("FAIL", vals); process.exit(1); }\nconsole.log("OK");\n',
- },
-]
-
-BUGFIX = BUGFIX_T1 + BUGFIX_T2
-
-# ---------------------------------------------------------------- tool-calling
-WEATHER_TOOL = [{"type": "function", "function": {
- "name": "get_weather",
- "description": "Get the current weather for a location.",
- "parameters": {"type": "object", "properties": {
- "location": {"type": "string", "description": "City name"},
- "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}},
- "required": ["location", "unit"]}}}]
-CALC_TOOL = [{"type": "function", "function": {
- "name": "calculator",
- "description": "Evaluate an arithmetic expression.",
- "parameters": {"type": "object", "properties": {"expression": {"type": "string"}},
- "required": ["expression"]}}}]
-WEB_TOOL = {"type": "function", "function": {
- "name": "web_search", "description": "Search the web.",
- "parameters": {"type": "object", "properties": {"query": {"type": "string"}, "limit": {"type": "integer"}},
- "required": ["query"]}}}
-THREE_TOOLS = [WEATHER_TOOL[0], CALC_TOOL[0], WEB_TOOL]
-TIMER_TOOL = [{"type": "function", "function": {
- "name": "set_timer", "description": "Set a countdown timer.",
- "parameters": {"type": "object", "properties": {"seconds": {"type": "integer", "description": "duration in seconds"}},
- "required": ["seconds"]}}}]
-
-
-def _v_native(resp):
- tcs = client.tool_calls(resp)
- if not tcs:
- return False, "no tool_calls returned (content=%r)" % client.content(resp)[:120]
- fn = tcs[0]["function"]
- if fn["name"] != "get_weather":
- return False, "wrong tool: %s" % fn["name"]
- try:
- args = json.loads(fn["arguments"])
- except Exception:
- return False, "args not valid JSON: %r" % fn["arguments"][:120]
- loc_ok = "paris" in str(args.get("location", "")).lower()
- unit_ok = str(args.get("unit", "")).lower() == "celsius"
- return (loc_ok and unit_ok), "args=%s loc_ok=%s unit_ok=%s" % (args, loc_ok, unit_ok)
-
-
-# The XML tool-call format uses angle brackets around a JSON object.
-# We build the regex pattern and system prompt here to avoid the literal
-# string being misinterpreted by tooling.
-_XML_PATTERN = re.compile(r"[\<\u003c]\s*(\{.*?\})\s*[\>\u003e]", re.DOTALL)
-
-def _v_xml(resp):
- c = client.content(resp)
- m = _XML_PATTERN.search(c)
- if not m:
- return False, "no XML tool-call found: %r" % c[:160]
- try:
- obj = json.loads(m.group(1))
- except Exception:
- return False, "inner JSON did not parse: %r" % m.group(1)[:160]
- args = obj.get("arguments", obj.get("parameters", {}))
- name_ok = obj.get("name") == "web_search"
- q_ok = "gemma" in str(args.get("query", "")).lower()
- limit_ok = str(args.get("limit")) == "5"
- return (name_ok and q_ok and limit_ok), "obj=%s name_ok=%s q_ok=%s limit_ok=%s" % (obj, name_ok, q_ok, limit_ok)
-
-
-def _v_json(resp):
- c = client.content(resp).strip()
- m = re.search(r"\{.*\}", c, re.DOTALL)
- if not m:
- return False, "no JSON object in output: %r" % c[:160]
- try:
- obj = json.loads(m.group(0))
- except Exception as e:
- return False, "JSON parse error: %s | %r" % (e, m.group(0)[:160])
- name_ok = isinstance(obj.get("name"), str) and "maria" in obj["name"].lower()
- age_ok = obj.get("age") == 34
- sk = obj.get("skills")
- skills_ok = isinstance(sk, list) and {"go", "rust"} <= {str(x).lower() for x in sk}
- return (name_ok and age_ok and skills_ok), "obj=%s name=%s age=%s skills=%s" % (obj, name_ok, age_ok, skills_ok)
-
-
-def _v_notool(resp):
- tcs = client.tool_calls(resp)
- if tcs:
- return False, "incorrectly called a tool: %s" % tcs[0]["function"]["name"]
- c = client.content(resp).lower()
- return ("paris" in c), "answered in text, mentions Paris=%s" % ("paris" in c)
-
-
-def _v_multi(resp):
- tcs = client.tool_calls(resp)
- locs = []
- for tc in tcs:
- try:
- a = json.loads(tc["function"]["arguments"])
- except Exception:
- a = {}
- locs.append(str(a.get("location", "")).lower())
- blob = " ".join(locs)
- ok = len(tcs) >= 2 and "paris" in blob and "tokyo" in blob
- return ok, "n_calls=%d locs=%s" % (len(tcs), locs)
-
-
-def _v_select(resp):
- tcs = client.tool_calls(resp)
- if not tcs:
- return False, "no tool call; content=%r" % client.content(resp)[:140]
- fn = tcs[0]["function"]
- if fn["name"] != "calculator":
- return False, "picked %s" % fn["name"]
- try:
- a = json.loads(fn["arguments"])
- except Exception:
- return False, "bad args %r" % fn["arguments"][:120]
- expr = str(a.get("expression", ""))
- return ("47" in expr and "89" in expr), "expr=%r" % expr
-
-
-def _v_nested(resp):
- c = client.content(resp).strip()
- m = re.search(r"\{.*\}", c, re.DOTALL)
- if not m:
- return False, "no json: %r" % c[:140]
- try:
- o = json.loads(m.group(0))
- except Exception as e:
- return False, "parse err %s" % e
- svc = o.get("service", {})
- ok = (isinstance(svc, dict) and str(svc.get("name", "")).lower() == "api"
- and svc.get("port") == 8080 and o.get("replicas") == 3
- and "prod" in str(o.get("env", "")).lower())
- return ok, "obj=%s" % o
-
-
-def _v_derived(resp):
- tcs = client.tool_calls(resp)
- if not tcs:
- return False, "no tool call; content=%r" % client.content(resp)[:140]
- fn = tcs[0]["function"]
- if fn["name"] != "set_timer":
- return False, "picked %s" % fn["name"]
- try:
- a = json.loads(fn["arguments"])
- except Exception:
- return False, "bad args"
- return a.get("seconds") == 150, "args=%s" % a
-
-
-# Build the XML tool-call system prompt without a literal angle-bracket tag.
-# The model is told to emit: <JSON object> on one line.
-_XML_SYS = ("You can call tools. To call a tool you MUST output exactly one line "
- "of the form " + chr(60) + "{\"name\": \"<tool>\", \"arguments\": {...}}" + chr(62) +
- " and nothing else — no prose, no markdown. Available tool: web_search(query: string, limit: integer).")
-
-
-TOOLCALL = [
- {"id": "tc-native", "cat": "toolcall", "tools": WEATHER_TOOL, "validator": _v_native,
- "messages": [{"role": "user", "content": "What is the current weather in Paris? Use celsius."}]},
- {"id": "tc-xml", "cat": "toolcall", "tools": None, "validator": _v_xml,
- "messages": [
- {"role": "system", "content": _XML_SYS},
- {"role": "user", "content": "Search the web for 'gemma benchmarks' and return at most 5 results."}]},
- {"id": "tc-json", "cat": "toolcall", "tools": None, "validator": _v_json,
- "messages": [
- {"role": "system", "content": "Output ONLY a single JSON object and nothing else. No markdown fences, no commentary."},
- {"role": "user", "content": "Extract this person into JSON with keys name (string), age (integer), skills (array of strings): 'Maria is 34 years old and knows Go and Rust.'"}]},
- {"id": "tc-notool", "cat": "toolcall", "tools": CALC_TOOL, "validator": _v_notool,
- "messages": [{"role": "user", "content": "What is the capital of France? Answer in one word."}]},
- {"id": "tc-multi", "cat": "toolcall", "tools": WEATHER_TOOL, "validator": _v_multi,
- "messages": [{"role": "user", "content": "What's the weather in Paris and in Tokyo right now? Use celsius for both."}]},
- {"id": "tc-select", "cat": "toolcall", "tools": THREE_TOOLS, "validator": _v_select,
- "messages": [{"role": "user", "content": "Using the tools available to you, compute 47 * 89 and give me the exact product."}]},
- {"id": "tc-nested-json", "cat": "toolcall", "tools": None, "validator": _v_nested,
- "messages": [
- {"role": "system", "content": "Output ONLY a single JSON object, no markdown, no commentary."},
- {"role": "user", "content": "Produce a deployment config JSON with this shape: {\"service\": {\"name\": string, \"port\": integer}, \"replicas\": integer, \"env\": string}. The service is named 'api', listens on port 8080, runs 3 replicas, in the production environment."}]},
- {"id": "tc-derived", "cat": "toolcall", "tools": TIMER_TOOL, "validator": _v_derived,
- "messages": [{"role": "user", "content": "Set a timer for two and a half minutes."}]},
-]
-
-
-def all_tasks():
- return TOOLCALL + BUGFIX
-
-
-# ---------------------------------------------------------------- phases
-def validate():
- print("=== VALIDATION: proving each bug-fix task is well-formed ===\n")
- allok = True
- for t in BUGFIX:
- runner = RUNNERS[t["lang"]]
- bug_pass, bug_out = runner(t, t["buggy"])
- fix_pass, fix_out = runner(t, t["fix"])
- valid = (not bug_pass) and fix_pass
- allok = allok and valid
- status = "OK " if valid else "BAD"
- print("[%s] %-16s buggy_fails=%-5s fix_passes=%-5s" %
- (status, t["id"], (not bug_pass), fix_pass))
- if not valid:
- if bug_pass:
- print(" !! buggy code unexpectedly PASSED tests")
- if not fix_pass:
- print(" !! reference fix FAILED:\n " + fix_out.replace("\n", "\n ")[:800])
- print("\nVALIDATION %s" % ("PASSED — all tasks well-formed" if allok else "FAILED"))
- return allok
-
-
-def run():
- tasks = all_tasks()
- path = jsonl_path(client.MODEL, prefix="coding-suite")
- open(path, "w").close()
- results = []
- print("=== RUN: %d tasks against %s ===\n" % (len(tasks), client.MODEL), flush=True)
- for i, t in enumerate(tasks, 1):
- print("[%d/%d] %-16s ..." % (i, len(tasks), t["id"]), end=" ", flush=True)
- rec = {"id": t["id"], "cat": t["cat"]}
- try:
- if t["cat"] == "toolcall":
- resp, dt = client.call_model(t["messages"], tools=t.get("tools"))
- passed, detail = t["validator"](resp)
- else:
- sysmsg = ("You are an expert %s developer. Fix the bug in the code. "
- "Respond with ONLY the corrected code in a single fenced code block. "
- "Keep the same names and signatures. Do NOT add tests, a main function, "
- "explanations, or extra declarations." % t["lang"].upper())
- user = ("The following %s code has a bug. %s\n\n```%s\n%s```\n\nReturn the corrected code."
- % (t["lang"], t["symptom"], t["lang"], t["buggy"]))
- resp, dt = client.call_model(
- [{"role": "system", "content": sysmsg},
- {"role": "user", "content": user}])
- code = extract_code(client.content(resp))
- rec["code"] = code
- passed, detail = RUNNERS[t["lang"]](t, code)
- u = client.usage(resp)
- rec.update({
- "passed": bool(passed),
- "detail": detail[:1200],
- "latency_s": round(dt, 1),
- "finish": client.finish_reason(resp),
- "total_tokens": u["prompt_tokens"] + u["completion_tokens"],
- "completion_tokens": u["completion_tokens"],
- "reasoning_tokens": u["reasoning_tokens"],
- "lang": t.get("lang", "-"),
- })
- print("%s (%.0fs, %s tok)" % ("PASS" if passed else "FAIL", dt, rec.get("total_tokens")), flush=True)
- except Exception as e:
- rec.update({"passed": False, "detail": "HARNESS/REQUEST ERROR: %r" % e, "lang": t.get("lang", "-")})
- print("ERROR: %r" % e, flush=True)
- results.append(rec)
- append_jsonl(path, rec)
- coding_suite_summary(results)
- write_json(results, client.MODEL, prefix="coding-suite")
-
-
-def report():
- path = jsonl_path(client.MODEL, prefix="coding-suite")
- results = [json.loads(l) for l in open(path)]
- coding_suite_summary(results)
-
-
-
-
-def main():
- mode = sys.argv[1] if len(sys.argv) > 1 else 'validate'
- if mode == 'validate':
- sys.exit(0 if validate() else 1)
- elif mode == 'run':
- run()
- elif mode == 'report':
- report()
- else:
- print(f'usage: python bench.py coding-suite [validate|run|report]')
- sys.exit(1)
-
-
-if __name__ == "__main__":
- main()
diff --git a/bench/tasks/conformance.py b/bench/tasks/conformance.py
new file mode 100644
index 0000000..884ece7
--- /dev/null
+++ b/bench/tasks/conformance.py
@@ -0,0 +1,470 @@
+"""Per-lane conformance preflight. NOT a benchmark: it rules out non-model problems (lane settings,
+chat template, reasoning and tool-call parsing, a provider that eats output) before a run.
+
+ LANE=<id> python3 bench.py conformance [--checks a,b,...] [--list]
+
+Every `run` of a scoring instrument calls require() first (results.run_attempts): the PREFLIGHT
+checks run unless they passed for the same lane settings in the last 24 h; any FAIL stops the run.
+BENCH_PREFLIGHT=0 skips it (tests, deliberate reruns); --resume never re-checks.
+
+Verdicts: PASS; FAIL = a non-model problem (blocks a run); WARN = the model got a probe wrong
+but the pipeline delivered it intact (recorded, does not block); INFO. One row per check
+(category "conformance", item_id = check name, correct True / False / None for WARN and INFO).
+Output tokens stay small: every call passes override={"max_tokens": ...}.
+
+Checks
+ sampler_card no request: the sampler the lane sends (lane.request + extra_body, as the client
+ builds it) vs its card's block for its thinking mode in lanes/cards.json. FAIL on
+ a missing or different value unless lane.sampler_overrides pins the sent value
+ with a reason; FAIL if the lane names no card
+ basic_reply the lane answers a trivial arithmetic question with non-empty content
+ (shared response also feeds the thinking checks below)
+ max_tokens override max_tokens=64 is honoured (completion_tokens <= 70)
+ reasoning_field thinking-on lanes: records WHICH field carries the reasoning
+ (reasoning_content / reasoning / reasoning_details / inline <think>) and whether
+ reasoning_tokens is reported or None. FAIL if no reasoning is observed.
+ no_reasoning thinking-off lanes: zero reasoning chars AND reasoning_tokens in {None, 0}
+ system_messages two system messages + a user message succeed (the client merges them when the
+ lane sets merge_system_messages; INFO note if the lane lacks it)
+ tool_roundtrip the model calls a provided tool with valid JSON-object arguments, then answers
+ after a tool result
+ tc-* the 8 tool-call / JSON probes (toolcall_probes.py, from coding-suite). FAIL when
+ the pipeline lost the answer: a tool call that came back as text, output the
+ provider swallowed (stripped), no answer and no call at finish=stop; WARN when
+ a well-formed answer is just wrong
+ think_tags over every response above: <think>/</think> left in the content or inside the
+ reasoning field, a <think> that never closed, the basic answer found only in
+ the reasoning. FAIL on any
+ determinism INFO only, not in the preflight: two runs at temperature 0 / top_k 1, identical
+ content? (never part of a run: temperature 0 loops Qwen)
+ provider_pin openrouter lanes: every response's `provider` equals the pinned provider
+ (extra_body.provider.order[0], case-insensitive); FAIL otherwise
+ server_snapshot INFO: n_ctx / total_slots / model ids from the RunStore's run.json
+"""
+import argparse
+import hashlib
+import json
+import os
+import re
+import sys
+import time
+
+from bench.core import client, lane as lane_mod, results
+from bench.tasks import toolcall_probes
+
+INSTRUMENT = "conformance"
+CAP_ON, CAP_OFF = 2048, 256 # trivial answers: reasoners need room, non-reasoners do not
+CAP_TOOL_ON, CAP_TOOL_OFF = 4096, 512
+CAP_SMALL = 64
+CHECKS = ["sampler", "basic", "maxtok", "thinking", "system", "tools", "toolcalls", "think_tags",
+ "determinism", "provider", "server"]
+PREFLIGHT = ["sampler", "basic", "maxtok", "thinking", "system", "tools", "toolcalls", "think_tags",
+ "provider"]
+PREFLIGHT_TTL = 24 * 3600
+ITEM_SET = "conformance@2"
+CARDS = os.path.join(lane_mod.LANES_DIR, "cards.json")
+TOOL_TEXT = re.compile(r"<tool_call>|<function[=>]|\"name\"\s*:\s*\"(get_weather|calculator|web_search|set_timer)\"")
+THINK_TAG = re.compile(r"</?think>")
+
+TOOL = [{"type": "function", "function": {
+ "name": "get_weather", "description": "Get the current weather for a city.",
+ "parameters": {"type": "object", "properties": {"city": {"type": "string"}},
+ "required": ["city"]}}}]
+
+
+class Result:
+ def __init__(self, name, verdict, detail, meta=None):
+ self.name, self.verdict, self.detail, self.meta = name, verdict, detail, meta or {}
+
+
+def reasoning_fields(resp):
+ """Which fields of the message carry reasoning text."""
+ msg = resp["choices"][0].get("message") or {}
+ found = [k for k in ("reasoning_content", "reasoning") if msg.get(k)]
+ det = msg.get("reasoning_details")
+ if isinstance(det, list) and any((d.get("text") or d.get("summary")) for d in det if isinstance(d, dict)):
+ found.append("reasoning_details")
+ c = msg.get("content")
+ if isinstance(c, str) and c.lstrip().startswith("<think>"):
+ found.append("inline_think")
+ return found
+
+
+def load_cards(path=CARDS):
+ with open(path) as f:
+ return json.load(f)
+
+
+def _same(a, b):
+ if isinstance(a, (int, float)) and isinstance(b, (int, float)):
+ return abs(a - b) < 1e-9
+ return a == b
+
+
+def sampler_check(lane, cards):
+ """The sampler this lane sends vs its model card's recommendation for its thinking mode."""
+ name = "sampler_card"
+ card_id = lane.raw.get("card")
+ if not card_id:
+ return Result(name, "FAIL", 'lane names no model card (set "card" to a key of lanes/cards.json)')
+ mode = "thinking" if lane.thinking == "on" else "non_thinking"
+ card = cards.get(card_id) or {}
+ if mode not in card:
+ return Result(name, "FAIL", "lanes/cards.json has no %s sampler for %s" % (mode, card_id),
+ {"card": card_id})
+ sent = client.build_body([{"role": "user", "content": "."}], lane=lane)
+ overrides = lane.raw.get("sampler_overrides") or {}
+ bad, notes = [], []
+ for key, want in sorted(card[mode].items()):
+ got, ov = sent.get(key), overrides.get(key)
+ if got is None:
+ bad.append("%s not sent (card %s)" % (key, want))
+ elif ov is None:
+ if not _same(got, want):
+ bad.append("%s=%s (card %s)" % (key, got, want))
+ elif not _same(got, ov.get("value")):
+ bad.append("%s=%s but sampler_overrides pins %s" % (key, got, ov.get("value")))
+ elif not ov.get("reason"):
+ bad.append("%s=%s override has no reason" % (key, got))
+ else:
+ notes.append("%s=%s overridden (card %s): %s" % (key, got, want, ov["reason"]))
+ where = "%s@%s %s" % (card_id, card.get("revision", "?")[:7], mode)
+ meta = {"card": card_id, "card_revision": card.get("revision"), "card_mode": mode,
+ "mismatches": bad, "overridden": sorted(k for k in overrides if k in card[mode])}
+ if bad:
+ return Result(name, "FAIL", "%s: %s" % (where, "; ".join(bad + notes)), meta)
+ return Result(name, "PASS", "; ".join([where + ": matches"] + notes), meta)
+
+
+class Preflight:
+ def __init__(self, lane, store):
+ self.lane, self.store = lane, store
+ self.on = lane.thinking == "on"
+ self.cap = CAP_ON if self.on else CAP_OFF
+ self.cap_tool = CAP_TOOL_ON if self.on else CAP_TOOL_OFF
+ self.providers = []
+ self.seen = [] # (check name, response) for think_tags
+ self.out_tokens = 0
+ self.basic_resp = None
+ self.budget_stop = False
+
+ def call(self, name, messages, tools=None, cap=None, extra=None):
+ ov = {"max_tokens": cap or self.cap}
+ ov.update(extra or {})
+ resp, dt = client.call_model(messages, tools, override=ov, item_id="conformance-" + name,
+ run_id=self.store.run_id, lane=self.lane)
+ u = client.usage(resp)
+ self.out_tokens += u["completion_tokens"]
+ self.providers.append(resp.get("provider"))
+ self.seen.append((name, resp))
+ return resp, dt
+
+ def guard(self, name, fn, info_on_error=False):
+ """Run a check; an error becomes FAIL (INFO for informational checks)."""
+ try:
+ return fn()
+ except client.CallError as e:
+ if e.label() == "budget_stop":
+ self.budget_stop = True
+ return Result(name, "INFO" if info_on_error else "FAIL", "request failed: %s" % e,
+ client.error_meta(e))
+ except Exception as e: # noqa: BLE001
+ return Result(name, "FAIL", "harness error: %r" % (e,), client.error_meta(e))
+
+ # ---- checks -----------------------------------------------------------
+ def sampler(self):
+ return sampler_check(self.lane, load_cards())
+
+ def basic(self):
+ resp, dt = self.call("basic_reply", [{"role": "user", "content":
+ "What is 17 * 23? Answer with just the number."}])
+ self.basic_resp = resp
+ meta = client.meta(resp, dt)
+ text = client.content(resp).strip()
+ if meta["status"] == "truncated":
+ return Result("basic_reply", "FAIL", "truncated at the %d-token cap (content=%r)" % (self.cap, text[:60]), meta)
+ if not text:
+ return Result("basic_reply", "FAIL", "empty content", meta)
+ return Result("basic_reply", "PASS", "content=%r%s" % (text[:40], "" if "391" in text else " (not 391)"), meta)
+
+ def maxtok(self):
+ resp, dt = self.call("max_tokens", [{"role": "user", "content": "Count from 1 to 500, one number per line."}],
+ cap=CAP_SMALL)
+ meta = client.meta(resp, dt)
+ ct, fin = meta["completion_tokens"], meta["finish"]
+ sent = (resp.get("_bench", {}).get("request") or {}).get("max_tokens")
+ if not ct:
+ return Result("max_tokens", "INFO", "server reported no completion_tokens (finish=%s)" % fin, meta)
+ if ct > 70:
+ return Result("max_tokens", "FAIL", "asked max_tokens=%s, got completion_tokens=%d (finish=%s)" % (sent, ct, fin), meta)
+ return Result("max_tokens", "PASS", "max_tokens=%s -> completion_tokens=%d finish=%s" % (sent, ct, fin), meta)
+
+ def thinking(self):
+ resp = self.basic_resp
+ if resp is None:
+ resp, dt = self.call("reasoning_field", [{"role": "user", "content":
+ "What is 17 * 23? Answer with just the number."}])
+ meta = client.meta(resp, dt)
+ else:
+ meta = client.meta(resp)
+ chars = len(client.reasoning(resp))
+ rt = client.usage(resp)["reasoning_tokens"]
+ fields = reasoning_fields(resp)
+ rts = "None (not reported)" if rt is None else str(rt)
+ if self.on:
+ name = "reasoning_field"
+ if chars > 0:
+ return Result(name, "PASS", "field=%s reasoning_chars=%d reasoning_tokens=%s"
+ % ("+".join(fields) or "?", chars, rts), meta)
+ if rt:
+ return Result(name, "INFO", "reasoning_tokens=%s reported but no reasoning text returned" % rt, meta)
+ return Result(name, "FAIL", "lane is thinking=on but no reasoning observed "
+ "(reasoning_tokens=%s)" % rts, meta)
+ name = "no_reasoning"
+ if chars == 0 and rt in (None, 0):
+ return Result(name, "PASS", "reasoning_chars=0 reasoning_tokens=%s mechanism=%s"
+ % (rts, (self.lane.nothink or {}).get("mechanism")), meta)
+ return Result(name, "FAIL", "thinking=off lane leaked reasoning: chars=%d reasoning_tokens=%s fields=%s"
+ % (chars, rts, "+".join(fields) or "-"), meta)
+
+ def system(self):
+ merged = bool(self.lane.raw.get("merge_system_messages"))
+ resp, dt = self.call("system_messages", [
+ {"role": "system", "content": "You are a terse assistant."},
+ {"role": "system", "content": "Always answer in lowercase."},
+ {"role": "user", "content": "Say hello."}])
+ meta = client.meta(resp, dt)
+ note = "client merges system messages" if merged else "NOTE: lane lacks merge_system_messages (sent as two messages)"
+ if meta["status"] in ("empty", "truncated"):
+ return Result("system_messages", "FAIL", "accepted but status=%s; %s" % (meta["status"], note), meta)
+ return Result("system_messages", "PASS", note, meta)
+
+ def tools(self):
+ msgs = [{"role": "user", "content": "What is the weather in Paris right now? Use the get_weather tool."}]
+ resp, dt = self.call("tool_roundtrip", msgs, tools=TOOL, cap=self.cap_tool)
+ meta = client.meta(resp, dt)
+ tcs = client.tool_calls(resp)
+ if not tcs:
+ why = pipeline_fault(resp, {"tools": TOOL}, meta)
+ return Result("tool_roundtrip", "FAIL" if why else "WARN", "%sno tool call (content=%r)" % (
+ why + " | " if why else "model: ", client.content(resp)[:80]), meta)
+ fn = tcs[0].get("function") or {}
+ try:
+ args = json.loads(fn.get("arguments") or "")
+ except ValueError:
+ args = None
+ if fn.get("name") != "get_weather" or not isinstance(args, dict):
+ return Result("tool_roundtrip", "FAIL", "bad tool call name=%r arguments=%r"
+ % (fn.get("name"), str(fn.get("arguments"))[:80]), meta)
+ msgs.append(resp["choices"][0]["message"])
+ msgs.append({"role": "tool", "tool_call_id": tcs[0].get("id") or "call_0",
+ "content": json.dumps({"city": "Paris", "temp_c": 18, "sky": "cloudy"})})
+ resp2, dt2 = self.call("tool_roundtrip", msgs, tools=TOOL, cap=self.cap_tool)
+ text = client.content(resp2).strip()
+ meta["turn2_status"] = client.status(resp2)
+ if not text:
+ return Result("tool_roundtrip", "FAIL", "valid call args=%s but no answer after the tool result "
+ "(status=%s, tool_calls=%d)" % (args, client.status(resp2), len(client.tool_calls(resp2))), meta)
+ return Result("tool_roundtrip", "PASS", "args=%s; answer mentions 18: %s" % (args, "18" in text), meta)
+
+ def probe(self, p):
+ resp, dt = self.call(p["id"], p["messages"], tools=p["tools"], cap=self.cap_tool)
+ meta = client.meta(resp, dt)
+ res = p["validator"](resp)
+ meta.update(res[2] if len(res) > 2 else {})
+ if res[0]:
+ return Result(p["id"], "PASS", res[1], meta)
+ why = pipeline_fault(resp, p, meta)
+ return Result(p["id"], "FAIL" if why else "WARN", (why + " | " if why else "model: ") + res[1], meta)
+
+ def think_tags(self):
+ if not self.seen:
+ return Result("think_tags", "INFO", "no responses to check")
+ issues = []
+ for name, resp in self.seen:
+ msg = resp["choices"][0].get("message") or {}
+ raw = client._raw_content(resp)
+ if THINK_TAG.search(client.content(resp)):
+ issues.append(f"{name}: think tag left in the content")
+ field = msg.get("reasoning_content") or msg.get("reasoning")
+ if isinstance(field, str) and THINK_TAG.search(field):
+ issues.append(f"{name}: think tag inside the reasoning field")
+ if raw.lstrip().startswith("<think>") and "</think>" not in raw \
+ and client.finish_reason(resp) != "length":
+ issues.append(f"{name}: <think> never closed (finish={client.finish_reason(resp)})")
+ if name == "basic_reply" and "391" in client.reasoning(resp) and "391" not in client.content(resp) \
+ and client.finish_reason(resp) != "length":
+ issues.append("basic_reply: the answer is only in the reasoning")
+ inline = sum(1 for _, r in self.seen if client._raw_content(r).lstrip().startswith("<think>"))
+ if issues:
+ return Result("think_tags", "FAIL", "; ".join(issues)[:480])
+ return Result("think_tags", "PASS", "clean across %d responses%s" % (len(self.seen), (
+ "; reasoning arrives inline in the content on %d (the client splits it)" % inline) if inline else ""))
+
+ def determinism(self):
+ outs = []
+ for _ in range(2):
+ resp, dt = self.call("determinism", [{"role": "user", "content": "Write one sentence about the sea."}],
+ extra={"temperature": 0, "top_k": 1})
+ outs.append(client.content(resp))
+ same = outs[0] == outs[1]
+ return Result("determinism", "INFO", "temperature=0 top_k=1: %s%s" % (
+ "identical content" if same else "content DIFFERS between runs",
+ "" if outs[0].strip() else " (empty content)"), {"identical": same})
+
+ def provider(self):
+ order = ((self.lane.extra_body.get("provider") or {}).get("order") or [])
+ if not order:
+ return Result("provider_pin", "FAIL", "openrouter lane has no extra_body.provider.order pin")
+ pinned = str(order[0])
+ seen = [p for p in self.providers]
+ if not seen:
+ return Result("provider_pin", "FAIL", "no responses to check")
+ bad = sorted({str(p) for p in seen if not p or str(p).lower() != pinned.lower()})
+ if bad:
+ return Result("provider_pin", "FAIL", "pinned %r but responses came from %s" % (pinned, bad))
+ return Result("provider_pin", "PASS", "all %d responses from %r" % (len(seen), pinned))
+
+ def server(self):
+ with open(os.path.join(self.store.dir, "run.json")) as f:
+ srv = json.load(f).get("server") or {}
+ parts = ["kind=%s" % srv.get("kind")]
+ props = srv.get("props") or {}
+ if props:
+ parts.append("n_ctx=%s" % (props.get("default_generation_settings") or {}).get("n_ctx"))
+ parts.append("total_slots=%s" % props.get("total_slots"))
+ if props.get("build_info"):
+ parts.append("build=%s" % props.get("build_info"))
+ models = srv.get("models") or {}
+ ids = [m.get("id") for m in (models.get("data") or []) if isinstance(m, dict)]
+ if ids:
+ parts.append("models=%s" % ",".join(str(i) for i in ids))
+ ep = (srv.get("endpoints") or {}).get("data") or {}
+ if isinstance(ep, dict) and ep.get("endpoints"):
+ parts.append("endpoints=%s" % ",".join(str(e.get("provider_name") or e.get("tag")) for e in ep["endpoints"]))
+ errs = [k for k, v in srv.items() if isinstance(v, dict) and "_error" in v]
+ if errs or "_error" in props:
+ parts.append("snapshot errors in %s" % (errs or ["props"]))
+ return Result("server_snapshot", "INFO", " ".join(parts))
+
+
+def pipeline_fault(resp, probe, meta):
+ """Why a failed probe points at the template / parser / provider rather than the model, or ""."""
+ tcs, c, r = client.tool_calls(resp), client.content(resp), client.reasoning(resp)
+ if results.effective_status(meta) == "stripped":
+ return "output swallowed: %s answer tokens, no content, no tool call" % (
+ (meta.get("completion_tokens") or 0) - (meta.get("reasoning_tokens") or 0))
+ if THINK_TAG.search(c):
+ return "think tag in the content"
+ if not tcs and TOOL_TEXT.search(c + "\n" + r):
+ return "the call came back as text, not as a tool_calls entry (template / parser)"
+ if not tcs and not c.strip() and client.finish_reason(resp) != "length":
+ return "no answer and no tool call at finish=%s" % client.finish_reason(resp)
+ return ""
+
+
+def run_conformance(lane, store, checks=None, out=print):
+ """Run the selected checks; returns the list of Results (rows already stored)."""
+ sel = set(checks or CHECKS)
+ pf = Preflight(lane, store)
+ plan = [("sampler", pf.sampler, "sampler_card", False),
+ ("basic", pf.basic, "basic_reply", False),
+ ("maxtok", pf.maxtok, "max_tokens", False),
+ ("thinking", pf.thinking, "reasoning_field" if pf.on else "no_reasoning", False),
+ ("system", pf.system, "system_messages", False),
+ ("tools", pf.tools, "tool_roundtrip", False)]
+ plan += [("toolcalls", (lambda p=p: pf.probe(p)), p["id"], False) for p in toolcall_probes.TOOLCALL]
+ plan += [("think_tags", pf.think_tags, "think_tags", False),
+ ("determinism", pf.determinism, "determinism", True)]
+ out_results = []
+ for key, fn, name, info in plan:
+ if key not in sel or pf.budget_stop:
+ continue
+ out_results.append(pf.guard(name, fn, info_on_error=info))
+ if "provider" in sel and lane.snapshot_kind == "openrouter":
+ out_results.append(pf.guard("provider_pin", pf.provider))
+ if "server" in sel:
+ out_results.append(pf.guard("server_snapshot", pf.server, info_on_error=True))
+ for r in out_results:
+ store.add(item_id=r.name, sample_idx=0, category="conformance",
+ correct={"PASS": True, "FAIL": False}.get(r.verdict), verdict=r.verdict,
+ detail=r.detail[:500], **r.meta)
+ out("conformance: lane=%s thinking=%s kind=%s" % (lane.lane_id, lane.thinking, lane.snapshot_kind))
+ out("%-18s %-5s %s" % ("check", "", "detail"))
+ for r in out_results:
+ out("%-18s %-5s %s" % (r.name, r.verdict, r.detail))
+ out("total output tokens: %d" % pf.out_tokens)
+ return out_results
+
+
+def _lane_hash(lane):
+ return hashlib.sha256(json.dumps(lane.record(), sort_keys=True).encode()).hexdigest()[:16]
+
+
+def _marker(lane):
+ return os.path.join(results.RESULTS_DIR, "_preflight", lane.lane_id + ".json")
+
+
+def require(lane, log=print):
+ """The automatic preflight before a run: PREFLIGHT checks, cached 24 h per lane settings. Raises
+ SystemExit on any FAIL."""
+ if lane.raw.get("runner") or os.environ.get("BENCH_PREFLIGHT", "1") == "0":
+ return
+ h, path = _lane_hash(lane), _marker(lane)
+ try:
+ with open(path) as f:
+ m = json.load(f)
+ if m.get("lane_hash") == h and m.get("ok") and time.time() - m.get("t", 0) < PREFLIGHT_TTL:
+ log("preflight: passed %s for these lane settings (%s); skipping" % (m.get("at"), m.get("run_id")))
+ return
+ except (OSError, ValueError):
+ pass
+ log("preflight: checking lane %s before the run (BENCH_PREFLIGHT=0 skips)" % lane.lane_id)
+ store = results.RunStore(INSTRUMENT, item_set=ITEM_SET, lane=lane, args={"checks": PREFLIGHT, "auto": True})
+ res = run_conformance(lane, store, PREFLIGHT, out=log)
+ fails = [r for r in res if r.verdict == "FAIL"]
+ store.finish(_summary(res), complete=True)
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ with open(path, "w") as f:
+ json.dump({"lane_hash": h, "ok": not fails, "t": time.time(), "run_id": store.run_id,
+ "at": time.strftime("%Y-%m-%d %H:%M")}, f)
+ if fails:
+ raise SystemExit("preflight FAILED on %s: %s\nnot a model problem; fix the lane or server, or "
+ "rerun with BENCH_PREFLIGHT=0 to override" % (
+ lane.lane_id, "; ".join("%s: %s" % (r.name, r.detail[:160]) for r in fails)))
+
+
+def _summary(res):
+ return {"pass": sum(r.verdict == "PASS" for r in res), "fail": sum(r.verdict == "FAIL" for r in res),
+ "warn": sum(r.verdict == "WARN" for r in res), "info": sum(r.verdict == "INFO" for r in res),
+ "checks": {r.name: r.verdict for r in res}}
+
+
+def main(argv=None):
+ ap = argparse.ArgumentParser(prog="bench.py conformance")
+ ap.add_argument("--checks", default="", help="comma list of: " + ",".join(CHECKS))
+ ap.add_argument("--list", action="store_true")
+ args = ap.parse_args(sys.argv[1:] if argv is None else argv)
+ if args.list:
+ print("\n".join(CHECKS))
+ return
+ checks = [c for c in args.checks.split(",") if c] or None
+ if checks and [c for c in checks if c not in CHECKS]:
+ print("ERROR: unknown checks; choose from %s" % ",".join(CHECKS))
+ sys.exit(2)
+ lane = lane_mod.current()
+ if lane.raw.get("runner"):
+ print("conformance: lane %s runs through %s, not an HTTP endpoint; nothing to check"
+ % (lane.lane_id, lane.raw["runner"]))
+ sys.exit(2)
+ store = results.RunStore(INSTRUMENT, item_set=ITEM_SET, lane=lane,
+ args={"checks": checks or CHECKS})
+ res = run_conformance(lane, store, checks)
+ fails = [r for r in res if r.verdict == "FAIL"]
+ store.finish(_summary(res), complete=True)
+ print("\n%s" % ("FAIL: %s" % ", ".join(r.name for r in fails) if fails else "all checks passed"))
+ sys.exit(1 if fails else 0)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/bench/tasks/fix_easy/__init__.py b/bench/tasks/fix_easy/__init__.py
new file mode 100644
index 0000000..6993196
--- /dev/null
+++ b/bench/tasks/fix_easy/__init__.py
@@ -0,0 +1,29 @@
+"""Easy-tier bug fixes for agentic-fix: one module per language, each with ITEMS = [item, ...].
+
+An item is one single-turn fix, graded by bench/core/runners.py with the real toolchain:
+ id unique, "<lang>-<name>"
+ lang a key of runners.RUNNERS (go, rust, ts, swift, python, sh, sql)
+ symptom what the user sees, one or two sentences (shown with the code)
+ buggy the code the model must fix: the whole solution file (sql: one query)
+ fix a reference fix (validate: buggy fails, fix passes)
+ test the hidden test: Go/Rust test code, a TS/Swift script, a Python script that imports
+ solution, a bash script that sources ./solution.sh (sql: none)
+ context optional text shown before the code (sql: the schema)
+ fixture sql only: the SQL that builds the database the query runs on
+ expect sql only: the expected CSV output (sqlite3 -csv, no header); compared as sorted lines
+ unless "ordered": True
+Shell items must run on macOS's bash 3.2 (no declare -A, ${x,,}, mapfile, |&, ;&).
+"""
+import importlib
+import os
+
+LANGS = ("go", "rust", "ts", "swift", "python", "sh", "sql")
+
+
+def load():
+ here = os.path.dirname(os.path.abspath(__file__))
+ items = []
+ for lang in LANGS:
+ if os.path.exists(os.path.join(here, lang + ".py")):
+ items += importlib.import_module("bench.tasks.fix_easy." + lang).ITEMS
+ return items
diff --git a/bench/tasks/fix_easy/go.py b/bench/tasks/fix_easy/go.py
new file mode 100644
index 0000000..74844cd
--- /dev/null
+++ b/bench/tasks/fix_easy/go.py
@@ -0,0 +1,33 @@
+"""Easy-tier Go fixes, moved verbatim from coding-suite (2026-10-12): two from its tier 1, then two
+from its tier 2."""
+
+ITEMS = [
+ {
+ "id": "go-average", "lang": "go", "cat": "bugfix",
+ "symptom": "It should return the arithmetic mean as a float, but returns truncated values (e.g. 1 instead of 1.5 for [1,2]).",
+ "buggy": "package solution\n\nfunc Average(xs []int) float64 {\n\tsum := 0\n\tfor _, x := range xs {\n\t\tsum += x\n\t}\n\treturn float64(sum / len(xs))\n}\n",
+ "fix": "package solution\n\nfunc Average(xs []int) float64 {\n\tsum := 0\n\tfor _, x := range xs {\n\t\tsum += x\n\t}\n\treturn float64(sum) / float64(len(xs))\n}\n",
+ "test": 'package solution\n\nimport "testing"\n\nfunc almost(a, b float64) bool { d := a - b; if d < 0 { d = -d }; return d < 1e-9 }\n\nfunc TestAverage(t *testing.T) {\n\tif !almost(Average([]int{1, 2}), 1.5) { t.Fatalf("[1,2]=%v want 1.5", Average([]int{1, 2})) }\n\tif !almost(Average([]int{2, 2, 2}), 2.0) { t.Fatalf("[2,2,2]=%v want 2", Average([]int{2, 2, 2})) }\n\tif !almost(Average([]int{1, 2, 3, 4}), 2.5) { t.Fatalf("[1,2,3,4]=%v want 2.5", Average([]int{1, 2, 3, 4})) }\n}\n',
+ },
+ {
+ "id": "go-nilmap", "lang": "go", "cat": "bugfix",
+ "symptom": "It panics at runtime ('assignment to entry in nil map') instead of grouping the integers by parity.",
+ "buggy": 'package solution\n\nfunc GroupByParity(xs []int) map[string][]int {\n\tvar m map[string][]int\n\tfor _, x := range xs {\n\t\tif x%2 == 0 {\n\t\t\tm["even"] = append(m["even"], x)\n\t\t} else {\n\t\t\tm["odd"] = append(m["odd"], x)\n\t\t}\n\t}\n\treturn m\n}\n',
+ "fix": 'package solution\n\nfunc GroupByParity(xs []int) map[string][]int {\n\tm := make(map[string][]int)\n\tfor _, x := range xs {\n\t\tif x%2 == 0 {\n\t\t\tm["even"] = append(m["even"], x)\n\t\t} else {\n\t\t\tm["odd"] = append(m["odd"], x)\n\t\t}\n\t}\n\treturn m\n}\n',
+ "test": 'package solution\n\nimport (\n\t"reflect"\n\t"testing"\n)\n\nfunc TestGroup(t *testing.T) {\n\tgot := GroupByParity([]int{1, 2, 3, 4})\n\twant := map[string][]int{"odd": {1, 3}, "even": {2, 4}}\n\tif !reflect.DeepEqual(got, want) { t.Fatalf("got %v want %v", got, want) }\n}\n',
+ },
+ {
+ "id": "go-json-tags", "lang": "go", "cat": "bugfix",
+ "symptom": "ToJSON should produce JSON with exactly the keys \"name\", \"emailAddress\", and \"age\", but the name key comes out capitalized and the age field is missing from the output entirely.",
+ "buggy": 'package solution\n\nimport "encoding/json"\n\ntype User struct {\n\tName string\n\tEmail string `json:"emailAddress"`\n\tage int `json:"age"`\n}\n\nfunc ToJSON(name, email string, age int) (string, error) {\n\tu := User{Name: name, Email: email, age: age}\n\tb, err := json.Marshal(u)\n\treturn string(b), err\n}\n',
+ "fix": 'package solution\n\nimport "encoding/json"\n\ntype User struct {\n\tName string `json:"name"`\n\tEmail string `json:"emailAddress"`\n\tAge int `json:"age"`\n}\n\nfunc ToJSON(name, email string, age int) (string, error) {\n\tu := User{Name: name, Email: email, Age: age}\n\tb, err := json.Marshal(u)\n\treturn string(b), err\n}\n',
+ "test": 'package solution\n\nimport (\n\t"encoding/json"\n\t"testing"\n)\n\nfunc TestToJSON(t *testing.T) {\n\ts, err := ToJSON("Ada", "ada@x.com", 36)\n\tif err != nil { t.Fatal(err) }\n\tvar m map[string]interface{}\n\tif err := json.Unmarshal([]byte(s), &m); err != nil { t.Fatal(err) }\n\tif m["name"] != "Ada" { t.Fatalf("name key wrong; got map %v", m) }\n\tif m["emailAddress"] != "ada@x.com" { t.Fatalf("email key wrong; got %v", m) }\n\tif m["age"] != float64(36) { t.Fatalf("age key wrong/missing; got %v", m) }\n}\n',
+ },
+ {
+ "id": "go-generics", "lang": "go", "cat": "bugfix",
+ "symptom": "MapSlice should return a new slice with f applied to each element, but the result has extra leading zero values (e.g. [0 0 0 2 4 6] instead of [2 4 6]).",
+ "buggy": "package solution\n\nfunc MapSlice[T any, U any](xs []T, f func(T) U) []U {\n\tresult := make([]U, len(xs))\n\tfor _, x := range xs {\n\t\tresult = append(result, f(x))\n\t}\n\treturn result\n}\n",
+ "fix": "package solution\n\nfunc MapSlice[T any, U any](xs []T, f func(T) U) []U {\n\tresult := make([]U, 0, len(xs))\n\tfor _, x := range xs {\n\t\tresult = append(result, f(x))\n\t}\n\treturn result\n}\n",
+ "test": 'package solution\n\nimport (\n\t"reflect"\n\t"testing"\n)\n\nfunc TestMapSlice(t *testing.T) {\n\tgot := MapSlice([]int{1, 2, 3}, func(x int) int { return x * 2 })\n\tif !reflect.DeepEqual(got, []int{2, 4, 6}) { t.Fatalf("got %v want [2 4 6]", got) }\n\tgs := MapSlice([]int{1, 2}, func(x int) string { return string(rune(\'a\' + x)) })\n\tif !reflect.DeepEqual(gs, []string{"b", "c"}) { t.Fatalf("got %v want [b c]", gs) }\n}\n',
+ },
+]
diff --git a/bench/tasks/fix_easy/python.py b/bench/tasks/fix_easy/python.py
new file mode 100644
index 0000000..22d905e
--- /dev/null
+++ b/bench/tasks/fix_easy/python.py
@@ -0,0 +1,205 @@
+"""Easy-tier Python fixes (written 2026-10-12): two straightforward (mutable default argument,
+rstrip used as suffix removal), then two subtler ones (split(" ") vs split() with a maxsplit that
+must survive the fix; removing from a list while iterating it, where the contract is in place so
+rebinding to a comprehension does not count). Graded with python3 (3.9 on the Mac)."""
+
+CONTEXT = "Target: Python 3.9, standard library only."
+
+ITEMS = [
+ {
+ "id": "python-mutable-default", "lang": "python", "cat": "bugfix", "context": CONTEXT,
+ "symptom": "Calling collect_errors(['10:01 ERROR disk full']) and then collect_errors(['11:00 INFO all good']) returns ['10:01 ERROR disk full'] from the second call, which should be [] because that log has no errors.",
+ "buggy": '''def collect_errors(lines, errors=[]):
+ """Append the ERROR lines of lines (stripped) to errors and return it.
+
+ Callers pass their own list to accumulate into, or leave it out to get a new list.
+ """
+ for line in lines:
+ if " ERROR " in line:
+ errors.append(line.strip())
+ return errors
+''',
+ "fix": '''def collect_errors(lines, errors=None):
+ """Append the ERROR lines of lines (stripped) to errors and return it.
+
+ Callers pass their own list to accumulate into, or leave it out to get a new list.
+ """
+ if errors is None:
+ errors = []
+ for line in lines:
+ if " ERROR " in line:
+ errors.append(line.strip())
+ return errors
+''',
+ "test": '''import sys
+from solution import collect_errors
+
+fails = []
+
+
+def check(label, got, want):
+ if got != want:
+ fails.append("%s: got %r, want %r" % (label, got, want))
+
+
+first = collect_errors(["10:01 ERROR disk full\\n", "10:02 INFO rotated\\n"])
+check("first call", first, ["10:01 ERROR disk full"])
+second = collect_errors(["11:00 INFO all good\\n"])
+check("second call on a clean log", second, [])
+check("first result left alone", first, ["10:01 ERROR disk full"])
+acc = ["09:00 ERROR earlier"]
+out = collect_errors(["12:00 ERROR timeout", "12:01 WARN slow"], acc)
+check("accumulates into the caller's list", acc, ["09:00 ERROR earlier", "12:00 ERROR timeout"])
+check("returns the caller's list", out is acc, True)
+empty = []
+out = collect_errors(["13:00 ERROR boom"], empty)
+check("fills an empty caller list", empty, ["13:00 ERROR boom"])
+check("returns that empty caller list", out is empty, True)
+check("later default call", collect_errors([]), [])
+if fails:
+ print("\\n".join(fails))
+ sys.exit(1)
+print("OK")
+''',
+ },
+ {
+ "id": "python-strip-domain", "lang": "python", "cat": "bugfix", "context": CONTEXT,
+ "symptom": "short_name('mail.example.com', 'example.com') returns 'mai' instead of 'mail', and short_name('pool.corp.lan', 'corp.lan') returns '' instead of 'pool' (short_name('web01.example.com', 'example.com') correctly gives 'web01').",
+ "buggy": '''def short_name(fqdn, domain):
+ """Return fqdn without its trailing ".<domain>"; names outside domain come back unchanged."""
+ return fqdn.rstrip("." + domain)
+''',
+ "fix": '''def short_name(fqdn, domain):
+ """Return fqdn without its trailing ".<domain>"; names outside domain come back unchanged."""
+ suffix = "." + domain
+ if fqdn.endswith(suffix):
+ return fqdn[:-len(suffix)]
+ return fqdn
+''',
+ "test": '''import sys
+from solution import short_name
+
+cases = [
+ ("web01.example.com", "example.com", "web01"),
+ ("mail.example.com", "example.com", "mail"),
+ ("pool.corp.lan", "corp.lan", "pool"),
+ ("app.prod.example.com", "example.com", "app.prod"),
+ ("db01.example.org", "example.com", "db01.example.org"),
+ ("mail.example.com.au", "example.com", "mail.example.com.au"),
+ ("notexample.com", "example.com", "notexample.com"),
+ ("example.com", "example.com", "example.com"),
+]
+fails = []
+for fqdn, domain, want in cases:
+ got = short_name(fqdn, domain)
+ if got != want:
+ fails.append("short_name(%r, %r) = %r, want %r" % (fqdn, domain, got, want))
+if fails:
+ print("\\n".join(fails))
+ sys.exit(1)
+print("OK")
+''',
+ },
+ {
+ "id": "python-df-columns", "lang": "python", "cat": "bugfix", "context": CONTEXT,
+ "symptom": "parse_df_line('/dev/sda1 41152736 12345678 26693908 32% /') returns ('26693908 32% /', 12345678) instead of ('/', 32); lines where the columns are separated by single spaces parse correctly.",
+ "buggy": '''def parse_df_line(line):
+ """Parse one data line of `df -P -k` output into (mount_point, percent_used).
+
+ Columns: Filesystem, 1024-blocks, Used, Available, Capacity, Mounted on.
+ The mount point is the last column and may contain spaces.
+ """
+ fields = line.split(" ", 5)
+ return fields[5], int(fields[4].rstrip("%"))
+''',
+ "fix": '''def parse_df_line(line):
+ """Parse one data line of `df -P -k` output into (mount_point, percent_used).
+
+ Columns: Filesystem, 1024-blocks, Used, Available, Capacity, Mounted on.
+ The mount point is the last column and may contain spaces.
+ """
+ fields = line.split(None, 5)
+ return fields[5], int(fields[4].rstrip("%"))
+''',
+ "test": '''import sys
+from solution import parse_df_line
+
+cases = [
+ ("/dev/sda1 41152736 12345678 26693908 32% /", ("/", 32)),
+ ("/dev/sdb1 976284628 878656165 97628463 91% /srv/backup", ("/srv/backup", 91)),
+ ("tmpfs 819200 0 819200 0% /run/user/1000", ("/run/user/1000", 0)),
+ ("/dev/disk5s2 1953513560 1758162204 195351356 91% /Volumes/Backup Disk",
+ ("/Volumes/Backup Disk", 91)),
+ ("//user@fileserv/media 3906250000 3906250000 0 100% /Volumes/media (nas) 2",
+ ("/Volumes/media (nas) 2", 100)),
+ ("/dev/nvme0n1p2 487652564 12 487652552 1% /mnt/old disk", ("/mnt/old disk", 1)),
+]
+fails = []
+for line, want in cases:
+ try:
+ got = parse_df_line(line)
+ except Exception as e: # noqa: BLE001
+ got = "raised %r" % e
+ if got != want or not isinstance(got[1], int):
+ fails.append("parse_df_line(%r) = %r, want %r" % (line, got, want))
+if fails:
+ print("\\n".join(fails))
+ sys.exit(1)
+print("OK")
+''',
+ },
+ {
+ "id": "python-prune-in-place", "lang": "python", "cat": "bugfix", "context": CONTEXT,
+ "symptom": "With hosts a(up), b(down), c(down), d(up), drop_down returns 1 and leaves the list as [a, c, d]; it should return 2 and leave [a, d].",
+ "buggy": '''def drop_down(hosts):
+ """Remove every host whose status is "down" from hosts and return how many were removed.
+
+ hosts is a list of dicts with "name" and "status"; callers keep using the same list
+ object afterwards, so it is changed in place.
+ """
+ removed = 0
+ for host in hosts:
+ if host["status"] == "down":
+ hosts.remove(host)
+ removed += 1
+ return removed
+''',
+ "fix": '''def drop_down(hosts):
+ """Remove every host whose status is "down" from hosts and return how many were removed.
+
+ hosts is a list of dicts with "name" and "status"; callers keep using the same list
+ object afterwards, so it is changed in place.
+ """
+ kept = [host for host in hosts if host["status"] != "down"]
+ removed = len(hosts) - len(kept)
+ hosts[:] = kept
+ return removed
+''',
+ "test": '''import sys
+from solution import drop_down
+
+fails = []
+
+
+def run(spec, want_removed, want_names):
+ hosts = [{"name": n, "status": s} for n, s in spec]
+ inventory = hosts
+ removed = drop_down(hosts)
+ names = [h["name"] for h in inventory]
+ if removed != want_removed or names != want_names:
+ fails.append("%r: removed=%r left=%r, want removed=%r left=%r"
+ % (spec, removed, names, want_removed, want_names))
+
+
+run([("a", "up"), ("b", "down"), ("c", "down"), ("d", "up")], 2, ["a", "d"])
+run([("p", "down"), ("q", "down"), ("r", "down")], 3, [])
+run([("e", "down"), ("f", "up"), ("g", "down"), ("h", "down"), ("i", "up")], 3, ["f", "i"])
+run([("x", "up"), ("y", "maintenance")], 0, ["x", "y"])
+run([], 0, [])
+if fails:
+ print("\\n".join(fails))
+ sys.exit(1)
+print("OK")
+''',
+ },
+]
diff --git a/bench/tasks/fix_easy/rust.py b/bench/tasks/fix_easy/rust.py
new file mode 100644
index 0000000..26e6211
--- /dev/null
+++ b/bench/tasks/fix_easy/rust.py
@@ -0,0 +1,33 @@
+"""Easy-tier Rust fixes, moved verbatim from coding-suite (2026-10-12): two from its tier 1, then two
+from its tier 2."""
+
+ITEMS = [
+ {
+ "id": "rust-sumeven", "lang": "rust", "cat": "bugfix",
+ "symptom": "sum_even is supposed to sum the EVEN numbers, but it currently sums the odd ones (e.g. returns 4 instead of 6 for [1,2,3,4]).",
+ "buggy": "pub fn sum_even(v: &[i32]) -> i32 {\n v.iter().filter(|&&x| x % 2 == 1).sum()\n}\n",
+ "fix": "pub fn sum_even(v: &[i32]) -> i32 {\n v.iter().filter(|&&x| x % 2 == 0).sum()\n}\n",
+ "test": "#[cfg(test)]\nmod hidden {\n use super::*;\n #[test]\n fn t() {\n assert_eq!(sum_even(&[1, 2, 3, 4]), 6);\n assert_eq!(sum_even(&[2, 4, 6]), 12);\n assert_eq!(sum_even(&[1, 3, 5]), 0);\n }\n}\n",
+ },
+ {
+ "id": "rust-safediv", "lang": "rust", "cat": "bugfix",
+ "symptom": "safe_div should return None when dividing by zero, but it panics (attempt to divide by zero) instead.",
+ "buggy": "pub fn safe_div(a: i32, b: i32) -> Option<i32> {\n Some(a / b)\n}\n",
+ "fix": "pub fn safe_div(a: i32, b: i32) -> Option<i32> {\n if b == 0 { None } else { Some(a / b) }\n}\n",
+ "test": "#[cfg(test)]\nmod hidden {\n use super::*;\n #[test]\n fn t() {\n assert_eq!(safe_div(10, 2), Some(5));\n assert_eq!(safe_div(7, 0), None);\n assert_eq!(safe_div(-6, 3), Some(-2));\n }\n}\n",
+ },
+ {
+ "id": "rust-sumall", "lang": "rust", "cat": "bugfix",
+ "symptom": "sum_all does not compile because the generic type T is unconstrained. It should sum any slice of numbers (integers or floats) and return the total.",
+ "buggy": "pub fn sum_all<T>(items: &[T]) -> T {\n let mut total = 0;\n for x in items {\n total += x;\n }\n total\n}\n",
+ "fix": "pub fn sum_all<T: Copy + std::iter::Sum<T>>(items: &[T]) -> T {\n items.iter().copied().sum()\n}\n",
+ "test": "#[cfg(test)]\nmod hidden {\n use super::*;\n #[test]\n fn t() {\n assert_eq!(sum_all(&[1, 2, 3]), 6);\n assert_eq!(sum_all(&[10, 20]), 30);\n let f: f64 = sum_all(&[1.5, 2.5]);\n assert!((f - 4.0).abs() < 1e-9);\n }\n}\n",
+ },
+ {
+ "id": "rust-dedup", "lang": "rust", "cat": "bugfix",
+ "symptom": "dedup_sorted should sort the vector and remove consecutive duplicates in place, but it panics with an index-out-of-bounds error.",
+ "buggy": "pub fn dedup_sorted(v: &mut Vec<i32>) {\n v.sort();\n for i in 1..v.len() {\n if v[i] == v[i - 1] {\n v.remove(i);\n }\n }\n}\n",
+ "fix": "pub fn dedup_sorted(v: &mut Vec<i32>) {\n v.sort();\n v.dedup();\n}\n",
+ "test": "#[cfg(test)]\nmod hidden {\n use super::*;\n #[test]\n fn t() {\n let mut a = vec![3, 1, 2, 2, 3, 1];\n dedup_sorted(&mut a);\n assert_eq!(a, vec![1, 2, 3]);\n let mut b = vec![5, 5, 5];\n dedup_sorted(&mut b);\n assert_eq!(b, vec![5]);\n }\n}\n",
+ },
+]
diff --git a/bench/tasks/fix_easy/sh.py b/bench/tasks/fix_easy/sh.py
new file mode 100644
index 0000000..8d2f8d2
--- /dev/null
+++ b/bench/tasks/fix_easy/sh.py
@@ -0,0 +1,239 @@
+"""Easy-tier shell fixes (written 2026-10-12): two straightforward (unquoted paths with spaces in a
+log rotator, string comparison of disk percentages), then two subtler ones (counters set inside
+`cmd | while read` are lost in the subshell, and the test's last line has no trailing newline so
+reading the file directly drops it; `read` without IFS= and -r, where -r alone still loses the
+indentation). Tests source ./solution.sh; everything stays bash-3.2-safe for macOS /bin/bash."""
+
+CONTEXT = "Target: macOS /bin/bash 3.2 as well as Linux bash 5."
+
+ITEMS = [
+ {
+ "id": "sh-rotate-spaces", "lang": "sh", "cat": "bugfix", "context": CONTEXT,
+ "symptom": "rotate_log '/srv/my logs/app server.log' 3 prints errors such as '[: too many arguments' and 'ambiguous redirect' and leaves every file where it was; paths without spaces rotate fine.",
+ "buggy": '''# rotate_log FILE KEEP: shift FILE.1 .. FILE.(KEEP-1) up by one, move FILE to FILE.1,
+# then start a new empty FILE.
+rotate_log() {
+ local log keep i
+ log=$1
+ keep=$2
+ i=$((keep - 1))
+ while [ $i -ge 1 ]; do
+ if [ -f $log.$i ]; then
+ mv $log.$i $log.$((i + 1))
+ fi
+ i=$((i - 1))
+ done
+ if [ -f $log ]; then
+ mv $log $log.1
+ fi
+ : > $log
+}
+''',
+ "fix": '''# rotate_log FILE KEEP: shift FILE.1 .. FILE.(KEEP-1) up by one, move FILE to FILE.1,
+# then start a new empty FILE.
+rotate_log() {
+ local log keep i
+ log=$1
+ keep=$2
+ i=$((keep - 1))
+ while [ "$i" -ge 1 ]; do
+ if [ -f "$log.$i" ]; then
+ mv "$log.$i" "$log.$((i + 1))"
+ fi
+ i=$((i - 1))
+ done
+ if [ -f "$log" ]; then
+ mv "$log" "$log.1"
+ fi
+ : > "$log"
+}
+''',
+ "test": '''. ./solution.sh
+status=0
+fail() { echo "FAIL: $*"; status=1; }
+base=$(mktemp -d "${TMPDIR:-/tmp}/sh-rotate.XXXXXX") || exit 2
+dir="$base/my logs"
+mkdir "$dir"
+log="$dir/app server.log"
+printf 'current\\n' > "$log"
+printf 'one\\n' > "$log.1"
+printf 'two\\n' > "$log.2"
+rotate_log "$log" 3 2>/dev/null
+{ [ -f "$log" ] && [ ! -s "$log" ]; } || fail "a new empty log should exist"
+[ "$(cat "$log.1" 2>/dev/null)" = current ] || fail ".1 should hold the old log"
+[ "$(cat "$log.2" 2>/dev/null)" = one ] || fail ".2 should hold the old .1"
+[ "$(cat "$log.3" 2>/dev/null)" = two ] || fail ".3 should hold the old .2"
+printf 'newer\\n' > "$log"
+rotate_log "$log" 3 2>/dev/null
+[ "$(cat "$log.1" 2>/dev/null)" = newer ] || fail "second rotation: .1"
+[ "$(cat "$log.2" 2>/dev/null)" = current ] || fail "second rotation: .2"
+[ "$(cat "$log.3" 2>/dev/null)" = one ] || fail "second rotation: .3"
+[ ! -e "$log.4" ] || fail "KEEP=3 must not create .4"
+plain="$base/plain.log"
+rotate_log "$plain" 2 2>/dev/null
+{ [ -f "$plain" ] && [ ! -e "$plain.1" ]; } || fail "a missing log should just be created"
+printf 'x\\n' > "$plain"
+rotate_log "$plain" 2 2>/dev/null
+[ "$(cat "$plain.1" 2>/dev/null)" = x ] || fail "plain path rotation"
+rm -f "$dir"/* "$base"/*.log "$base"/*.log.*
+rmdir "$dir" "$base" 2>/dev/null
+exit $status
+''',
+ },
+ {
+ "id": "sh-disk-threshold", "lang": "sh", "cat": "bugfix", "context": CONTEXT,
+ "symptom": "check_disk 9% 80 prints 'ALERT 9% > 80%' and returns 1, while check_disk 100% 90 prints 'ok'.",
+ "buggy": r'''# check_disk USED LIMIT: USED is a df capacity such as 93%, LIMIT a plain number.
+# Print "ALERT <used>% > <limit>%" and return 1 when usage is above the limit,
+# otherwise print "ok" and return 0.
+check_disk() {
+ local used limit
+ used=${1%\%}
+ limit=$2
+ if [[ $used > $limit ]]; then
+ echo "ALERT ${used}% > ${limit}%"
+ return 1
+ fi
+ echo "ok"
+ return 0
+}
+''',
+ "fix": r'''# check_disk USED LIMIT: USED is a df capacity such as 93%, LIMIT a plain number.
+# Print "ALERT <used>% > <limit>%" and return 1 when usage is above the limit,
+# otherwise print "ok" and return 0.
+check_disk() {
+ local used limit
+ used=${1%\%}
+ limit=$2
+ if [ "$used" -gt "$limit" ]; then
+ echo "ALERT ${used}% > ${limit}%"
+ return 1
+ fi
+ echo "ok"
+ return 0
+}
+''',
+ "test": '''. ./solution.sh
+status=0
+expect() {
+ local want_rc want_out out rc
+ want_rc=$1
+ want_out=$2
+ shift 2
+ out=$(check_disk "$@")
+ rc=$?
+ if [ "$rc" != "$want_rc" ] || [ "$out" != "$want_out" ]; then
+ echo "FAIL: check_disk $*: got rc=$rc out='$out', want rc=$want_rc out='$want_out'"
+ status=1
+ fi
+}
+expect 0 "ok" 9% 80
+expect 1 "ALERT 100% > 90%" 100% 90
+expect 1 "ALERT 85% > 80%" 85% 80
+expect 0 "ok" 80% 80
+expect 0 "ok" 5% 10
+expect 1 "ALERT 79% > 8%" 79% 8
+expect 0 "ok" 0% 0
+exit $status
+''',
+ },
+ {
+ "id": "sh-failed-summary", "lang": "sh", "cat": "bugfix", "context": CONTEXT,
+ "symptom": "For a job log with two FAILED lines (the last one for db-dump), failed_summary prints 'count=0 last=' instead of 'count=2 last=db-dump'.",
+ "buggy": '''# failed_summary LOGFILE: log lines look like "2026-10-12 03:05:12 FAILED db-dump".
+# Print "count=N last=JOB": N is the number of FAILED lines, JOB the job name (last field)
+# of the last FAILED line, empty when there are none.
+failed_summary() {
+ local count=0 last="" line
+ grep ' FAILED ' "$1" | while read -r line; do
+ count=$((count + 1))
+ last=${line##* }
+ done
+ echo "count=$count last=$last"
+}
+''',
+ "fix": '''# failed_summary LOGFILE: log lines look like "2026-10-12 03:05:12 FAILED db-dump".
+# Print "count=N last=JOB": N is the number of FAILED lines, JOB the job name (last field)
+# of the last FAILED line, empty when there are none.
+failed_summary() {
+ local count=0 last="" line
+ while read -r line; do
+ count=$((count + 1))
+ last=${line##* }
+ done < <(grep ' FAILED ' "$1")
+ echo "count=$count last=$last"
+}
+''',
+ "test": '''. ./solution.sh
+status=0
+check() {
+ local got
+ got=$(failed_summary "$1" 2>&1)
+ if [ "$got" != "$2" ]; then
+ echo "FAIL: $(basename "$1"): got '$got', want '$2'"
+ status=1
+ fi
+}
+base=$(mktemp -d "${TMPDIR:-/tmp}/sh-failed.XXXXXX") || exit 2
+printf '%s\\n' '2026-10-12 03:00:01 OK nightly-backup' '2026-10-12 03:05:12 FAILED cert-renew' \\
+ '2026-10-12 03:10:00 OK rsync-offsite' > "$base/a.log"
+printf '%s' '2026-10-12 03:15:42 FAILED db-dump' >> "$base/a.log"
+check "$base/a.log" "count=2 last=db-dump"
+printf '%s\\n' '2026-10-13 03:00:01 OK nightly-backup' '2026-10-13 03:10:00 OK rsync-offsite' > "$base/b.log"
+check "$base/b.log" "count=0 last="
+printf '%s\\n' '2026-10-14 03:00:01 OK nightly-backup' '2026-10-14 03:02:00 FAILED zfs-scrub' \\
+ '2026-10-14 03:10:00 OK rsync-offsite' > "$base/c.log"
+check "$base/c.log" "count=1 last=zfs-scrub"
+check "$base/a.log" "count=2 last=db-dump"
+rm -f "$base/a.log" "$base/b.log" "$base/c.log"
+rmdir "$base" 2>/dev/null
+exit $status
+''',
+ },
+ {
+ "id": "sh-comment-out", "lang": "sh", "cat": "bugfix", "context": CONTEXT,
+ "symptom": r"Commenting out an nginx block turns the line 'location ~ \.php$ {' into '#location ~ .php$ {', so removing the '#' later does not give back the original config.",
+ "buggy": '''# comment_out FILE: print FILE with "#" put in front of every line and the lines otherwise
+# untouched, so stripping the first character of each line gives the original back.
+comment_out() {
+ local line
+ while read line; do
+ printf '#%s\\n' "$line"
+ done < "$1"
+}
+''',
+ "fix": '''# comment_out FILE: print FILE with "#" put in front of every line and the lines otherwise
+# untouched, so stripping the first character of each line gives the original back.
+comment_out() {
+ local line
+ while IFS= read -r line; do
+ printf '#%s\\n' "$line"
+ done < "$1"
+}
+''',
+ "test": r'''. ./solution.sh
+status=0
+base=$(mktemp -d "${TMPDIR:-/tmp}/sh-comment.XXXXXX") || exit 2
+f="$base/site.conf"
+printf '%s\n' 'location ~ \.php$ {' ' fastcgi_pass unix:/run/php/php-fpm.sock;' > "$f"
+printf '\tinclude fastcgi_params;\n' >> "$f"
+printf '%s\n' ' rewrite ^/old/(.*)$ /new/$1 permanent;' '' \
+ ' return 301 https://$host$request_uri; ' ' set $path C:\new\temp;' '}' >> "$f"
+comment_out "$f" > "$base/got" 2>&1
+sed 's/^/#/' "$f" > "$base/want"
+if ! cmp -s "$base/got" "$base/want"; then
+ echo "FAIL: output differs from the input with '#' prepended:"
+ diff "$base/want" "$base/got"
+ status=1
+fi
+printf '%s\n' 'plain line' 'another one' > "$base/simple.conf"
+if [ "$(comment_out "$base/simple.conf")" != "$(printf '#plain line\n#another one')" ]; then
+ echo "FAIL: simple file"
+ status=1
+fi
+rm -f "$f" "$base/got" "$base/want" "$base/simple.conf"
+rmdir "$base" 2>/dev/null
+exit $status
+''',
+ },
+]
diff --git a/bench/tasks/fix_easy/sql.py b/bench/tasks/fix_easy/sql.py
new file mode 100644
index 0000000..c890836
--- /dev/null
+++ b/bench/tasks/fix_easy/sql.py
@@ -0,0 +1,140 @@
+"""Easy-tier SQL (SQLite) fixes (written 2026-10-12): two straightforward (`= NULL`, integer
+division in a percentage), then two subtler ones (a WHERE on the right table of a LEFT JOIN, where
+adding `OR ... IS NULL` still drops hosts that only have resolved alerts; a join fan-out that
+COUNT(DISTINCT)/SUM(DISTINCT) only appears to fix, because two hosts share a disk size). Graded by
+running the query on the fixture with sqlite3 -csv and comparing to "expect"."""
+
+SERVERS = """CREATE TABLE servers (
+ id INTEGER PRIMARY KEY,
+ name TEXT NOT NULL,
+ role TEXT NOT NULL,
+ decommissioned_at TEXT -- date the server was retired; NULL while in service
+);"""
+
+BACKUP_RUNS = """CREATE TABLE backup_runs (
+ id INTEGER PRIMARY KEY,
+ host TEXT NOT NULL,
+ started_at TEXT NOT NULL,
+ status TEXT NOT NULL -- 'ok' or 'failed'
+);"""
+
+ALERTS = """CREATE TABLE hosts (
+ id INTEGER PRIMARY KEY,
+ name TEXT NOT NULL
+);
+CREATE TABLE alerts (
+ id INTEGER PRIMARY KEY,
+ host_id INTEGER NOT NULL REFERENCES hosts(id),
+ severity TEXT NOT NULL, -- 'warning' or 'critical'
+ status TEXT NOT NULL -- 'open' or 'resolved'
+);"""
+
+ADDRESSES = """CREATE TABLE hosts (
+ id INTEGER PRIMARY KEY,
+ name TEXT NOT NULL,
+ site TEXT NOT NULL,
+ disk_gb INTEGER NOT NULL
+);
+CREATE TABLE addresses (
+ host_id INTEGER NOT NULL REFERENCES hosts(id),
+ ip TEXT NOT NULL,
+ public INTEGER NOT NULL -- 1 = internet-facing address, 0 = internal
+);"""
+
+ITEMS = [
+ {
+ "id": "sql-null-compare", "lang": "sql", "cat": "bugfix",
+ "context": "The table `servers` is the server inventory; a server is in service until it gets a decommissioned_at date.\n\n```sql\n" + SERVERS + "\n```",
+ "symptom": "The query should list the name and role of every server still in service, ordered by name, but it returns no rows at all (expected db01, db02, web01 and web03).",
+ "fixture": SERVERS + """
+INSERT INTO servers VALUES
+ (1, 'web01', 'web', NULL),
+ (2, 'web02', 'web', '2026-03-01'),
+ (3, 'db01', 'db', NULL),
+ (4, 'db02', 'db', NULL),
+ (5, 'mail01', 'mail', '2025-11-15'),
+ (6, 'web03', 'web', NULL),
+ (7, 'db00', 'db', '2024-06-30');
+""",
+ "buggy": "SELECT name, role\nFROM servers\nWHERE decommissioned_at = NULL\nORDER BY name;\n",
+ "fix": "SELECT name, role\nFROM servers\nWHERE decommissioned_at IS NULL\nORDER BY name;\n",
+ "expect": "db01,db\ndb02,db\nweb01,web\nweb03,web\n",
+ "ordered": True,
+ },
+ {
+ "id": "sql-failure-rate", "lang": "sql", "cat": "bugfix",
+ "context": "The table `backup_runs` has one row per nightly backup job run, with its outcome.\n\n```sql\n" + BACKUP_RUNS + "\n```",
+ "symptom": "The failure percentage per host comes out as 0.0 for every host except mail01 (whose only run failed, 100.0); nas01 had 1 failed run out of 3 and should show 33.3, and the hosts should be ordered by that percentage, highest first.",
+ "fixture": BACKUP_RUNS + """
+INSERT INTO backup_runs (host, started_at, status) VALUES
+ ('nas01', '2026-10-01 02:00', 'ok'),
+ ('nas01', '2026-10-02 02:00', 'failed'),
+ ('nas01', '2026-10-03 02:00', 'ok'),
+ ('web01', '2026-10-01 02:30', 'ok'),
+ ('web01', '2026-10-02 02:30', 'ok'),
+ ('web01', '2026-10-03 02:30', 'failed'),
+ ('web01', '2026-10-04 02:30', 'ok'),
+ ('db01', '2026-10-01 03:00', 'ok'),
+ ('db01', '2026-10-02 03:00', 'ok'),
+ ('mail01', '2026-10-01 03:30', 'failed'),
+ ('vm07', '2026-10-01 04:00', 'ok'),
+ ('vm07', '2026-10-02 04:00', 'ok'),
+ ('vm07', '2026-10-03 04:00', 'ok'),
+ ('vm07', '2026-10-04 04:00', 'failed'),
+ ('vm07', '2026-10-05 04:00', 'ok'),
+ ('vm07', '2026-10-06 04:00', 'ok');
+""",
+ "buggy": "SELECT host,\n COUNT(*) AS runs,\n ROUND(SUM(status = 'failed') / COUNT(*) * 100, 1) AS failed_pct\nFROM backup_runs\nGROUP BY host\nORDER BY failed_pct DESC, host;\n",
+ "fix": "SELECT host,\n COUNT(*) AS runs,\n ROUND(100.0 * SUM(status = 'failed') / COUNT(*), 1) AS failed_pct\nFROM backup_runs\nGROUP BY host\nORDER BY failed_pct DESC, host;\n",
+ "expect": "mail01,1,100.0\nnas01,3,33.3\nweb01,4,25.0\nvm07,6,16.7\ndb01,2,0.0\n",
+ "ordered": True,
+ },
+ {
+ "id": "sql-open-alerts", "lang": "sql", "cat": "bugfix",
+ "context": "The table `hosts` lists monitored hosts and `alerts` holds every alert raised for them, open or resolved.\n\n```sql\n" + ALERTS + "\n```",
+ "symptom": "The query should list every host with its number of open alerts, ordered by name, but it returns only db01 (1) and web01 (2); hosts with no open alerts, such as fw01, are missing instead of showing 0.",
+ "fixture": ALERTS + """
+INSERT INTO hosts VALUES (1, 'web01'), (2, 'web02'), (3, 'db01'), (4, 'nas01'), (5, 'fw01');
+INSERT INTO alerts VALUES
+ (1, 1, 'warning', 'open'),
+ (2, 1, 'critical', 'open'),
+ (3, 1, 'warning', 'resolved'),
+ (4, 2, 'critical', 'resolved'),
+ (5, 3, 'warning', 'open'),
+ (6, 4, 'critical', 'resolved'),
+ (7, 4, 'warning', 'resolved');
+""",
+ "buggy": "SELECT h.name, COUNT(a.id) AS open_alerts\nFROM hosts h\nLEFT JOIN alerts a ON a.host_id = h.id\nWHERE a.status = 'open'\nGROUP BY h.id, h.name\nORDER BY h.name;\n",
+ "fix": "SELECT h.name, COUNT(a.id) AS open_alerts\nFROM hosts h\nLEFT JOIN alerts a ON a.host_id = h.id AND a.status = 'open'\nGROUP BY h.id, h.name\nORDER BY h.name;\n",
+ "expect": "db01,1\nfw01,0\nnas01,0\nweb01,2\nweb02,0\n",
+ "ordered": True,
+ },
+ {
+ "id": "sql-public-disk", "lang": "sql", "cat": "bugfix",
+ "context": "The table `hosts` lists servers per site with their disk size, and `addresses` holds each host's IP addresses (a host can have several, or none).\n\n```sql\n" + ADDRESSES + "\n```",
+ "symptom": "Per site, the query should give the number of internet-facing hosts (hosts with at least one public address) and their total disk_gb, but site dal comes out as 3 hosts and 1500 GB when it has only two such hosts (web01 and web02, 500 GB each): expected dal,2,1000.",
+ "fixture": ADDRESSES + """
+INSERT INTO hosts VALUES
+ (1, 'web01', 'dal', 500),
+ (2, 'web02', 'dal', 500),
+ (3, 'db01', 'dal', 2000),
+ (4, 'vpn01', 'chi', 100),
+ (5, 'nas01', 'chi', 8000),
+ (6, 'mx01', 'chi', 250),
+ (7, 'lab01', 'hou', 1000);
+INSERT INTO addresses VALUES
+ (1, '203.0.113.10', 1),
+ (1, '203.0.113.11', 1),
+ (1, '10.0.1.10', 0),
+ (2, '203.0.113.12', 1),
+ (3, '10.0.1.20', 0),
+ (4, '198.51.100.5', 1),
+ (4, '10.1.0.5', 0),
+ (5, '10.1.0.9', 0),
+ (6, '198.51.100.25', 1);
+""",
+ "buggy": "SELECT h.site, COUNT(*) AS hosts, SUM(h.disk_gb) AS disk_gb\nFROM hosts h\nJOIN addresses a ON a.host_id = h.id\nWHERE a.public = 1\nGROUP BY h.site;\n",
+ "fix": "SELECT h.site, COUNT(*) AS hosts, SUM(h.disk_gb) AS disk_gb\nFROM hosts h\nWHERE EXISTS (SELECT 1 FROM addresses a WHERE a.host_id = h.id AND a.public = 1)\nGROUP BY h.site;\n",
+ "expect": "chi,2,350\ndal,2,1000\n",
+ },
+]
diff --git a/bench/tasks/fix_easy/swift.py b/bench/tasks/fix_easy/swift.py
new file mode 100644
index 0000000..31b59a0
--- /dev/null
+++ b/bench/tasks/fix_easy/swift.py
@@ -0,0 +1,33 @@
+"""Easy-tier Swift fixes, moved verbatim from coding-suite (2026-10-12): two from its tier 1, then two
+from its tier 2. Runs on macOS only (xcrun); elsewhere the rows are skipped (infra)."""
+
+ITEMS = [
+ {
+ "id": "swift-parseage", "lang": "swift", "cat": "bugfix",
+ "symptom": "parseAge should return nil for non-numeric input, but it crashes (force-unwrap of nil) on input like \"abc\".",
+ "buggy": "func parseAge(_ s: String) -> Int? {\n return Int(s)!\n}\n",
+ "fix": "func parseAge(_ s: String) -> Int? {\n return Int(s)\n}\n",
+ "test": 'import Foundation\n\nfunc check(_ cond: Bool, _ msg: String) {\n if !cond { FileHandle.standardError.write(("FAIL: " + msg + "\\n").data(using: .utf8)!); exit(1) }\n}\n\ncheck(parseAge("34") == 34, "parseAge(34)")\ncheck(parseAge("abc") == nil, "parseAge(abc) should be nil")\ncheck(parseAge("0") == 0, "parseAge(0)")\nprint("OK")\n',
+ },
+ {
+ "id": "swift-median", "lang": "swift", "cat": "bugfix",
+ "symptom": "median returns the wrong value because it indexes the array without sorting it first (e.g. median([3,1,2]) returns 1 instead of 2).",
+ "buggy": "func median(_ xs: [Double]) -> Double {\n let n = xs.count\n if n % 2 == 1 {\n return xs[n / 2]\n } else {\n return (xs[n / 2 - 1] + xs[n / 2]) / 2\n }\n}\n",
+ "fix": "func median(_ xs: [Double]) -> Double {\n let s = xs.sorted()\n let n = s.count\n if n % 2 == 1 {\n return s[n / 2]\n } else {\n return (s[n / 2 - 1] + s[n / 2]) / 2\n }\n}\n",
+ "test": 'import Foundation\n\nfunc check(_ cond: Bool, _ msg: String) {\n if !cond { FileHandle.standardError.write(("FAIL: " + msg + "\\n").data(using: .utf8)!); exit(1) }\n}\n\ncheck(median([3, 1, 2]) == 2, "median odd")\ncheck(median([4, 1, 3, 2]) == 2.5, "median even")\ncheck(median([10, 2, 8, 4]) == 6, "median even2")\nprint("OK")\n',
+ },
+ {
+ "id": "swift-generic-max", "lang": "swift", "cat": "bugfix",
+ "symptom": "maxElement does not compile because the generic type T is not constrained. It should return the largest element, or nil for an empty array.",
+ "buggy": "func maxElement<T>(_ xs: [T]) -> T? {\n guard !xs.isEmpty else { return nil }\n var m = xs[0]\n for x in xs {\n if x > m { m = x }\n }\n return m\n}\n",
+ "fix": "func maxElement<T: Comparable>(_ xs: [T]) -> T? {\n guard !xs.isEmpty else { return nil }\n var m = xs[0]\n for x in xs {\n if x > m { m = x }\n }\n return m\n}\n",
+ "test": 'import Foundation\n\nfunc check(_ cond: Bool, _ msg: String) {\n if !cond { FileHandle.standardError.write(("FAIL: " + msg + "\\n").data(using: .utf8)!); exit(1) }\n}\n\ncheck(maxElement([3, 1, 2]) == 3, "max ints")\ncheck(maxElement([Int]()) == nil, "max empty")\ncheck(maxElement(["b", "a", "c"]) == "c", "max strings")\nprint("OK")\n',
+ },
+ {
+ "id": "swift-mutating", "lang": "swift", "cat": "bugfix",
+ "symptom": "This code does not compile: a struct method modifies a stored property, and the calling code prevents mutation. After fixing, runCounter(5) must return 5.",
+ "buggy": "struct Counter {\n var count = 0\n func increment() {\n count += 1\n }\n}\n\nfunc runCounter(_ times: Int) -> Int {\n let c = Counter()\n for _ in 0..<times { c.increment() }\n return c.count\n}\n",
+ "fix": "struct Counter {\n var count = 0\n mutating func increment() {\n count += 1\n }\n}\n\nfunc runCounter(_ times: Int) -> Int {\n var c = Counter()\n for _ in 0..<times { c.increment() }\n return c.count\n}\n",
+ "test": 'import Foundation\n\nfunc check(_ cond: Bool, _ msg: String) {\n if !cond { FileHandle.standardError.write(("FAIL: " + msg + "\\n").data(using: .utf8)!); exit(1) }\n}\n\ncheck(runCounter(5) == 5, "runCounter(5)")\ncheck(runCounter(0) == 0, "runCounter(0)")\nprint("OK")\n',
+ },
+]
diff --git a/bench/tasks/fix_easy/ts.py b/bench/tasks/fix_easy/ts.py
new file mode 100644
index 0000000..f36598f
--- /dev/null
+++ b/bench/tasks/fix_easy/ts.py
@@ -0,0 +1,33 @@
+"""Easy-tier TypeScript fixes, moved verbatim from coding-suite (2026-10-12): two from its tier 1, then two
+from its tier 2."""
+
+ITEMS = [
+ {
+ "id": "ts-sort", "lang": "ts", "cat": "bugfix",
+ "symptom": "sortNums sorts numbers lexicographically instead of numerically (e.g. [10,2,1] becomes [1,10,2] instead of [1,2,10]).",
+ "buggy": "export function sortNums(a: number[]): number[] {\n return a.sort();\n}\n",
+ "fix": "export function sortNums(a: number[]): number[] {\n return [...a].sort((x, y) => x - y);\n}\n",
+ "test": 'import { sortNums } from "./solution";\nfunction eq(a: number[], b: number[]) { return a.length === b.length && a.every((v, i) => v === b[i]); }\nlet ok = true;\nif (!eq(sortNums([10, 2, 1]), [1, 2, 10])) { console.error("FAIL sort1"); ok = false; }\nif (!eq(sortNums([3, 30, 1, 2]), [1, 2, 3, 30])) { console.error("FAIL sort2"); ok = false; }\nif (!ok) process.exit(1);\nconsole.log("OK");\n',
+ },
+ {
+ "id": "ts-reduce", "lang": "ts", "cat": "bugfix",
+ "symptom": "total throws a TypeError on an empty array because reduce has no initial value; total([]) should be 0.",
+ "buggy": "export function total(arr: number[]): number {\n return arr.reduce((a, b) => a + b);\n}\n",
+ "fix": "export function total(arr: number[]): number {\n return arr.reduce((a, b) => a + b, 0);\n}\n",
+ "test": 'import { total } from "./solution";\nlet ok = true;\nif (total([1, 2, 3]) !== 6) { console.error("FAIL t1"); ok = false; }\nif (total([]) !== 0) { console.error("FAIL empty"); ok = false; }\nif (total([5]) !== 5) { console.error("FAIL t3"); ok = false; }\nif (!ok) process.exit(1);\nconsole.log("OK");\n',
+ },
+ {
+ "id": "ts-matrix-alias", "lang": "ts", "cat": "bugfix",
+ "symptom": "makeMatrix should return independent rows, but every row is the SAME array reference (writing to one row changes them all).",
+ "buggy": "export function makeMatrix(rows: number, cols: number): number[][] {\n return new Array(rows).fill(new Array(cols).fill(0));\n}\n",
+ "fix": "export function makeMatrix(rows: number, cols: number): number[][] {\n return Array.from({ length: rows }, () => new Array(cols).fill(0));\n}\n",
+ "test": 'import { makeMatrix } from "./solution";\nconst m = makeMatrix(2, 2);\nm[0][0] = 5;\nif (m[1][0] !== 0) { console.error("FAIL aliasing", m); process.exit(1); }\nif (m.length !== 2 || m[0].length !== 2) { console.error("FAIL shape", m); process.exit(1); }\nconsole.log("OK");\n',
+ },
+ {
+ "id": "ts-closure-var", "lang": "ts", "cat": "bugfix",
+ "symptom": "makeAdders should return functions that return 0, 1, and 2, but every function returns 3 (they all share the same loop variable).",
+ "buggy": "export function makeAdders(): Array<() => number> {\n const fns: Array<() => number> = [];\n for (var i = 0; i < 3; i++) {\n fns.push(() => i);\n }\n return fns;\n}\n",
+ "fix": "export function makeAdders(): Array<() => number> {\n const fns: Array<() => number> = [];\n for (let i = 0; i < 3; i++) {\n fns.push(() => i);\n }\n return fns;\n}\n",
+ "test": 'import { makeAdders } from "./solution";\nconst vals = makeAdders().map((f) => f());\nfunction eq(a: number[], b: number[]) { return a.length === b.length && a.every((v, i) => v === b[i]); }\nif (!eq(vals, [0, 1, 2])) { console.error("FAIL", vals); process.exit(1); }\nconsole.log("OK");\n',
+ },
+]
diff --git a/bench/tasks/fix_hard/__init__.py b/bench/tasks/fix_hard/__init__.py
new file mode 100644
index 0000000..6e7ce4f
--- /dev/null
+++ b/bench/tasks/fix_hard/__init__.py
@@ -0,0 +1,30 @@
+"""Hard-tier bug fixes for agentic-fix: one module per item, a small project whose failing test
+needs reading across files to explain. The model sees the failing test output, explores with
+read-only tools (list_files, read_file, search) and calls submit_fix once with the complete new
+contents of ONE file. Module attributes:
+
+ ITEM_ID unique, "<lang>-<name>"
+ LANG go | rust | ts | python | sh | sql | swift (prompt wording + category hard/<LANG>)
+ TOOL binary that must be on PATH (go, cargo, bun, python3, bash, sqlite3, swift); missing ->
+ the attempt is infra, never a fail
+ MAC_ONLY optional; True for items that only run on macOS (Swift)
+ PROJECT {path: content}: every file the model can list, read and search, tests included
+ HIDDEN tuple of PROJECT paths (the tests) restored as written before grading, so rewriting a
+ test cannot pass
+ FIX {path: content}: the reference fix, exactly one file
+ TEST_CMD argv run in the materialized project; its output is the failing signal shown first
+ PASS_RE regex over TEST_CMD output; group 1 names a passing test
+ TESTS names that must all match PASS_RE (and TEST_CMD must exit 0)
+ WRONG optional [{path: content}, ...]: plausible single-file fixes that must fail the gate
+
+Rules: no comment or name may point at the bug (no "BUG", "FIXME", "wrong"); the fix is one file and
+the explanation needs at least two; the project is stdlib-only and builds offline.
+"""
+import importlib
+import os
+
+
+def load():
+ here = os.path.dirname(os.path.abspath(__file__))
+ mods = sorted(f[:-3] for f in os.listdir(here) if f.endswith(".py") and not f.startswith("_"))
+ return [importlib.import_module("bench.tasks.fix_hard." + m) for m in mods]
diff --git a/bench/tasks/fix_hard/go_kvstore.py b/bench/tasks/fix_hard/go_kvstore.py
new file mode 100644
index 0000000..4e4f385
--- /dev/null
+++ b/bench/tasks/fix_hard/go_kvstore.py
@@ -0,0 +1,301 @@
+"""Go: an in-memory TTL cache split across files. Set() stores expireAt = now instead of
+now.Add(ttl), so Get() right after Set() misses; it only makes sense once Set() and ttl.go's
+isExpired() are both read. Was agentic-fix v1's only item; its `// BUG:` comment is gone (v3)."""
+import re
+
+ITEM_ID = "go-kvstore-ttl"
+LANG = "go"
+TOOL = "go"
+
+PROJECT = {
+"go.mod": "module kvstore\n\ngo 1.26\n",
+
+"doc.go": '''// Package kvstore is a small concurrency-safe in-memory key/value cache with
+// per-entry TTL expiry and a background sweeper that evicts expired entries.
+//
+// Typical use:
+//
+// s := kvstore.New(kvstore.WithSweepInterval(time.Second))
+// defer s.Close()
+// s.Set("session:42", token, 30*time.Minute)
+// v, ok := s.Get("session:42")
+//
+// Expiry is lazy (checked on Get) and eager (the sweeper). Both paths agree on
+// one definition of "expired": see ttl.go.
+package kvstore
+''',
+
+"store.go": '''package kvstore
+
+import (
+ "sync"
+ "time"
+)
+
+// entry is a single stored value plus its bookkeeping. See ttl.go for the
+// expiry predicate that reads expireAt.
+type entry struct {
+ value any
+ expireAt time.Time
+ created time.Time
+}
+
+// Store is a concurrency-safe TTL cache.
+type Store struct {
+ mu sync.RWMutex
+ items map[string]*entry
+ stats *Stats
+ opts options
+ stopCh chan struct{}
+ closed bool
+}
+
+// New builds a Store and starts its background sweeper.
+func New(optFns ...Option) *Store {
+ o := defaultOptions()
+ for _, fn := range optFns {
+ fn(&o)
+ }
+ s := &Store{
+ items: make(map[string]*entry),
+ stats: &Stats{},
+ opts: o,
+ stopCh: make(chan struct{}),
+ }
+ go s.sweepLoop()
+ return s
+}
+
+// Set stores value under key with a time-to-live. A ttl <= 0 means the entry
+// never expires (expireAt stays the zero time, which isExpired treats as live).
+func (s *Store) Set(key string, value any, ttl time.Duration) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ now := time.Now()
+ e := &entry{value: value, created: now}
+ if ttl > 0 {
+ e.expireAt = now
+ }
+ s.items[key] = e
+}
+
+// Get returns the value for key. The second result is false if the key is
+// absent or has expired (a lazily-expired entry is deleted on read).
+func (s *Store) Get(key string) (any, bool) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ e, ok := s.items[key]
+ if !ok {
+ s.stats.recordMiss()
+ return nil, false
+ }
+ if isExpired(e, time.Now()) {
+ delete(s.items, key)
+ s.stats.recordMiss()
+ return nil, false
+ }
+ s.stats.recordHit()
+ return e.value, true
+}
+
+// Delete removes key if present, reporting whether it existed.
+func (s *Store) Delete(key string) bool {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ _, ok := s.items[key]
+ delete(s.items, key)
+ return ok
+}
+
+// Len returns the number of entries currently held (including any not-yet-swept
+// expired ones).
+func (s *Store) Len() int {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+ return len(s.items)
+}
+
+// Keys returns a snapshot of the current keys in unspecified order.
+func (s *Store) Keys() []string {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+ ks := make([]string, 0, len(s.items))
+ for k := range s.items {
+ ks = append(ks, k)
+ }
+ return ks
+}
+
+// Close stops the background sweeper. Safe to call more than once.
+func (s *Store) Close() {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if !s.closed {
+ close(s.stopCh)
+ s.closed = true
+ }
+}
+''',
+
+"ttl.go": '''package kvstore
+
+import "time"
+
+// isExpired reports whether e is past its time-to-live as of now. The zero
+// expireAt (used for never-expire entries) is always live. This is the single
+// source of truth for expiry, shared by Get (lazy) and the sweeper (eager).
+func isExpired(e *entry, now time.Time) bool {
+ if e.expireAt.IsZero() {
+ return false
+ }
+ return now.After(e.expireAt)
+}
+
+// remaining returns how long until e expires, or 0 if already expired / never.
+func remaining(e *entry, now time.Time) time.Duration {
+ if e.expireAt.IsZero() {
+ return 0
+ }
+ d := e.expireAt.Sub(now)
+ if d < 0 {
+ return 0
+ }
+ return d
+}
+''',
+
+"sweeper.go": '''package kvstore
+
+import "time"
+
+// sweepLoop runs until Close, evicting expired entries every SweepInterval so
+// memory does not grow unbounded when callers never re-Get expired keys.
+func (s *Store) sweepLoop() {
+ t := time.NewTicker(s.opts.sweepInterval)
+ defer t.Stop()
+ for {
+ select {
+ case <-s.stopCh:
+ return
+ case <-t.C:
+ s.sweepOnce()
+ }
+ }
+}
+
+// sweepOnce evicts every currently-expired entry in one pass.
+func (s *Store) sweepOnce() {
+ now := time.Now()
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ for k, e := range s.items {
+ if isExpired(e, now) {
+ delete(s.items, k)
+ s.stats.recordEviction()
+ }
+ }
+}
+''',
+
+"stats.go": '''package kvstore
+
+import "sync/atomic"
+
+// Stats holds cache counters. All methods are safe for concurrent use.
+type Stats struct {
+ hits atomic.Int64
+ misses atomic.Int64
+ evictions atomic.Int64
+}
+
+func (s *Stats) recordHit() { s.hits.Add(1) }
+func (s *Stats) recordMiss() { s.misses.Add(1) }
+func (s *Stats) recordEviction() { s.evictions.Add(1) }
+
+// Snapshot returns the current counter values.
+func (s *Stats) Snapshot() (hits, misses, evictions int64) {
+ return s.hits.Load(), s.misses.Load(), s.evictions.Load()
+}
+
+// Stats exposes the live counters for this store.
+func (s *Store) Stats() *Stats { return s.stats }
+''',
+
+"options.go": '''package kvstore
+
+import "time"
+
+// options is the internal, fully-resolved configuration for a Store.
+type options struct {
+ sweepInterval time.Duration
+}
+
+// Option customizes a Store at construction time.
+type Option func(*options)
+
+func defaultOptions() options {
+ return options{sweepInterval: 30 * time.Second}
+}
+
+// WithSweepInterval sets how often the background sweeper runs. Values <= 0 are
+// ignored and the default is kept.
+func WithSweepInterval(d time.Duration) Option {
+ return func(o *options) {
+ if d > 0 {
+ o.sweepInterval = d
+ }
+ }
+}
+''',
+
+"store_test.go": '''package kvstore
+
+import (
+ "testing"
+ "time"
+)
+
+// A value set with a long TTL must be readable immediately afterwards.
+func TestSetThenGetWithinTTL(t *testing.T) {
+ s := New(WithSweepInterval(time.Hour))
+ defer s.Close()
+ s.Set("k", "v", time.Hour)
+ got, ok := s.Get("k")
+ if !ok {
+ t.Fatalf("Get right after Set: want hit, got miss")
+ }
+ if got != "v" {
+ t.Fatalf("Get value = %v, want v", got)
+ }
+}
+
+// A short-TTL value must expire after enough time passes.
+func TestExpiresAfterTTL(t *testing.T) {
+ s := New(WithSweepInterval(time.Hour))
+ defer s.Close()
+ s.Set("k", "v", 10*time.Millisecond)
+ time.Sleep(25 * time.Millisecond)
+ if _, ok := s.Get("k"); ok {
+ t.Fatalf("Get after TTL: want miss, got hit")
+ }
+}
+
+// ttl <= 0 means never expire.
+func TestZeroTTLNeverExpires(t *testing.T) {
+ s := New(WithSweepInterval(time.Hour))
+ defer s.Close()
+ s.Set("k", "v", 0)
+ time.Sleep(15 * time.Millisecond)
+ if _, ok := s.Get("k"); !ok {
+ t.Fatalf("zero-ttl entry: want hit, got miss")
+ }
+}
+''',
+}
+
+HIDDEN = ("store_test.go",)
+FIX = {"store.go": PROJECT["store.go"].replace("\t\te.expireAt = now\n", "\t\te.expireAt = now.Add(ttl)\n")}
+TEST_CMD = ["go", "test", "-v", "./..."]
+PASS_RE = r"--- PASS: (\S+)"
+TESTS = tuple(re.findall(r"^func (Test\w+)\(", PROJECT["store_test.go"], re.M))
+WRONG = [{"ttl.go": PROJECT["ttl.go"].replace("return now.After(e.expireAt)", "return false")}]
diff --git a/bench/tasks/fix_hard/python_logrotate.py b/bench/tasks/fix_hard/python_logrotate.py
new file mode 100644
index 0000000..36a3301
--- /dev/null
+++ b/bench/tasks/fix_hard/python_logrotate.py
@@ -0,0 +1,549 @@
+"""Python: a logrotate-style rotation planner split across units / policy / conffile / planner.
+conffile.py hands `maxage N` to Policy.from_settings unconverted, and the shared duration parser
+reads a bare number as seconds (its documented contract, which flags and LOGROT_* env rely on)
+instead of logrotate's days. The symptom is planner output (every rotated copy deleted); the
+tempting patches (age-in-days in planner.py, bare-number-is-days in units.py, a max_age special
+case in Policy.from_settings) fix the config scenario but break the flag/env and unit tests."""
+import re
+
+ITEM_ID = "python-logrotate"
+LANG = "python"
+TOOL = "python3"
+
+PROJECT = {
+"logrot/__init__.py": r'''"""logrot: plan logrotate-style rotations without touching the disk.
+
+ blocks = parse(open("/etc/logrot.conf").read())
+ policy = policy_for(blocks, "/var/log/app/app.log")
+ for step in plan(policy, "app.log", listing, time.time()):
+ print(step)
+
+`listing` is a list of FileInfo(name, size, mtime) for the log's directory.
+"""
+from .conffile import ConfigError, parse, policy_for
+from .planner import FileInfo, plan
+from .policy import Policy
+from .units import UnitError, parse_duration, parse_size
+
+__all__ = ["ConfigError", "FileInfo", "Policy", "UnitError", "parse", "parse_duration",
+ "parse_size", "plan", "policy_for"]
+''',
+
+"logrot/units.py": r'''"""Unit parsing shared by every way of building a policy (flags, environment,
+config files).
+
+Everything that leaves this module is in base units: sizes in bytes, durations
+in seconds. Suffixes are case-insensitive.
+
+ parse_size("512") -> 512 a bare number is bytes
+ parse_size("10k") -> 10240 k, M, G are binary (KiB, MiB, GiB)
+ parse_duration("90") -> 90 a bare number is seconds
+ parse_duration("36h") -> 129600 s, m, h, d, w
+"""
+import re
+
+_NUMBER = re.compile(r"^\s*(\d+)\s*([A-Za-z]?)\s*$")
+_SIZE = {"": 1, "k": 1024, "m": 1024 ** 2, "g": 1024 ** 3}
+_DURATION = {"": 1, "s": 1, "m": 60, "h": 3600, "d": 86400, "w": 7 * 86400}
+_COUNT = {"": 1}
+_TRUE = ("1", "yes", "true", "on")
+_FALSE = ("0", "no", "false", "off")
+
+
+class UnitError(ValueError):
+ pass
+
+
+def _scaled(text, table, what):
+ m = _NUMBER.match(str(text))
+ if not m:
+ raise UnitError("bad %s: %r" % (what, text))
+ number, suffix = m.groups()
+ scale = table.get(suffix.lower())
+ if scale is None:
+ raise UnitError("bad %s suffix %r in %r" % (what, suffix, text))
+ return int(number) * scale
+
+
+def parse_size(text):
+ return _scaled(text, _SIZE, "size")
+
+
+def parse_duration(text):
+ return _scaled(text, _DURATION, "duration")
+
+
+def parse_flag(text):
+ word = str(text).strip().lower()
+ if word in _TRUE:
+ return True
+ if word in _FALSE:
+ return False
+ raise UnitError("bad flag: %r" % (text,))
+
+
+def coerce(kind, text):
+ """Convert one textual setting to its base-unit value. `kind` is one of the
+ values of policy.FIELD_KINDS: size, duration, count or flag."""
+ if kind == "size":
+ return parse_size(text)
+ if kind == "duration":
+ return parse_duration(text)
+ if kind == "count":
+ return _scaled(text, _COUNT, "count")
+ if kind == "flag":
+ return parse_flag(text)
+ raise UnitError("unknown kind %r" % (kind,))
+''',
+
+"logrot/policy.py": r'''"""Rotation policy for one family of logs.
+
+Fields are in base units (see units.py): max_bytes in bytes, max_age in seconds,
+keep is a count of rotated copies. None disables a limit.
+
+ max_bytes rotate the live log once it reaches this size
+ keep rotated copies to retain (.1 .. .keep)
+ max_age delete rotated copies whose mtime is older than this
+ compress gzip rotated copies
+ delay_compress leave the newest copy (.1) uncompressed until the next rotation
+"""
+from dataclasses import dataclass
+from typing import Optional
+
+from .units import coerce
+
+FIELD_KINDS = {
+ "max_bytes": "size",
+ "keep": "count",
+ "max_age": "duration",
+ "compress": "flag",
+ "delay_compress": "flag",
+}
+
+
+@dataclass
+class Policy:
+ max_bytes: Optional[int] = None
+ keep: int = 7
+ max_age: Optional[int] = None
+ compress: bool = False
+ delay_compress: bool = False
+
+ @classmethod
+ def from_settings(cls, settings):
+ """Build a policy from {field: text}, the shape produced by command-line
+ flags (`--max-age 36h` -> {"max_age": "36h"}) and by from_env. Each value
+ goes through units.coerce with its FIELD_KINDS kind; fields not mentioned
+ keep their defaults."""
+ unknown = sorted(set(settings) - set(FIELD_KINDS))
+ if unknown:
+ raise KeyError("unknown policy field(s): " + ", ".join(unknown))
+ return cls(**{name: coerce(FIELD_KINDS[name], text) for name, text in settings.items()})
+
+ @classmethod
+ def from_env(cls, environ, prefix="LOGROT_"):
+ """LOGROT_MAX_AGE=36h, LOGROT_KEEP=5, ... -> Policy. Other variables are ignored."""
+ settings = {}
+ for key, text in environ.items():
+ name = key[len(prefix):].lower()
+ if key.startswith(prefix) and name in FIELD_KINDS:
+ settings[name] = text
+ return cls.from_settings(settings)
+''',
+
+"logrot/conffile.py": r'''"""Parser for logrotate(8)-style config files.
+
+ compress # outside a block: default for later blocks
+ /var/log/app/*.log {
+ size 50M
+ rotate 4
+ maxage 14
+ delaycompress
+ }
+
+Directives keep their logrotate meanings: `size` rotates once the live log
+reaches that size (k, M, G suffixes; a bare number is bytes), `rotate N` keeps N
+rotated copies, `maxage N` deletes rotated copies older than N days, `compress`
+and `delaycompress` (and their `no` forms) toggle gzip. A block header may list
+several globs; each gets the same policy.
+"""
+import fnmatch
+
+from .policy import Policy
+
+DIRECTIVES = {
+ "size": "max_bytes",
+ "rotate": "keep",
+ "maxage": "max_age",
+ "compress": "compress",
+ "delaycompress": "delay_compress",
+}
+FLAGS = ("compress", "delaycompress")
+
+
+class ConfigError(ValueError):
+ pass
+
+
+def parse(text):
+ """Return [(glob, Policy)] in file order."""
+ defaults = {}
+ blocks = []
+ header = None
+ settings = None
+ for lineno, raw in enumerate(text.splitlines(), 1):
+ line = raw.split("#", 1)[0].strip()
+ if not line:
+ continue
+ if line.endswith("{"):
+ if header is not None:
+ raise ConfigError("line %d: nested block" % lineno)
+ header = line[:-1].split()
+ if not header:
+ raise ConfigError("line %d: block without a path" % lineno)
+ settings = dict(defaults)
+ elif line == "}":
+ if header is None:
+ raise ConfigError("line %d: unexpected }" % lineno)
+ policy = _build(settings, lineno)
+ blocks.extend((glob, policy) for glob in header)
+ header = None
+ else:
+ _apply(defaults if header is None else settings, line.split(), lineno)
+ if header is not None:
+ raise ConfigError("unterminated block for %s" % " ".join(header))
+ return blocks
+
+
+def policy_for(blocks, path):
+ """The policy of the first block whose glob matches `path`, or None."""
+ for glob, policy in blocks:
+ if fnmatch.fnmatchcase(path, glob):
+ return policy
+ return None
+
+
+def _apply(settings, words, lineno):
+ name = words[0].lower()
+ negated = name.startswith("no") and name[2:] in FLAGS
+ key = name[2:] if negated else name
+ if key not in DIRECTIVES:
+ raise ConfigError("line %d: unknown directive %r" % (lineno, words[0]))
+ if key in FLAGS:
+ if len(words) != 1:
+ raise ConfigError("line %d: %s takes no argument" % (lineno, name))
+ settings[DIRECTIVES[key]] = "no" if negated else "yes"
+ return
+ if len(words) != 2:
+ raise ConfigError("line %d: %s takes one argument" % (lineno, name))
+ settings[DIRECTIVES[key]] = words[1]
+
+
+def _build(settings, lineno):
+ try:
+ return Policy.from_settings(settings)
+ except (KeyError, ValueError) as e:
+ raise ConfigError("block ending line %d: %s" % (lineno, e))
+''',
+
+"logrot/planner.py": r'''"""Turn one policy plus a directory listing into an ordered rotation plan.
+
+`base` is the live log's file name (app.log). Rotated copies are base.N or
+base.N.gz with N >= 1, .1 being the newest. `files` is a list of
+FileInfo(name, size, mtime): size in bytes, mtime in epoch seconds; `now` is
+epoch seconds as well. Files that are neither the live log nor a rotated copy
+are ignored.
+
+The plan is a list of steps, to be applied in order:
+
+ delete <name> a rotated copy past `keep`, or older than `max_age`
+ rename <old> <new> a surviving copy moves up one index, highest first
+ rename <base> <base>.1 the live log, once it has reached `max_bytes`
+ compress <name> gzip a rotated copy that is not .gz yet
+
+Pruning happens on every run; shifting and compression only when the live log
+rotates. With delay_compress the new .1 stays plain and is compressed on the
+following rotation, when it has become .2.
+"""
+from collections import namedtuple
+
+FileInfo = namedtuple("FileInfo", "name size mtime")
+
+
+def rotated_index(base, name):
+ """app.log.3 or app.log.3.gz -> 3; anything else -> None."""
+ if not name.startswith(base + "."):
+ return None
+ rest = name[len(base) + 1:]
+ if rest.endswith(".gz"):
+ rest = rest[:-3]
+ if not rest.isdigit() or int(rest) < 1:
+ return None
+ return int(rest)
+
+
+def _renamed(base, name, index):
+ return "%s.%d%s" % (base, index, ".gz" if name.endswith(".gz") else "")
+
+
+def _expired(policy, info, now):
+ return policy.max_age is not None and now - info.mtime > policy.max_age
+
+
+def _due(policy, live):
+ return live is not None and policy.max_bytes is not None and live.size >= policy.max_bytes
+
+
+def plan(policy, base, files, now):
+ live = None
+ rotated = []
+ for info in files:
+ if info.name == base:
+ live = info
+ continue
+ index = rotated_index(base, info.name)
+ if index is not None:
+ rotated.append((index, info))
+ rotated.sort(key=lambda pair: pair[0])
+
+ rotate = _due(policy, live)
+ # a rotation moves every copy up one index, so one fewer old copy fits
+ limit = policy.keep - 1 if rotate else policy.keep
+ steps = []
+ survivors = []
+ for index, info in rotated:
+ if index > limit or _expired(policy, info, now):
+ steps.append("delete " + info.name)
+ else:
+ survivors.append((index, info))
+ if not rotate:
+ return steps
+
+ for index, info in reversed(survivors):
+ steps.append("rename %s %s" % (info.name, _renamed(base, info.name, index + 1)))
+ steps.append("rename %s %s.1" % (base, base))
+ if policy.compress:
+ for index, info in survivors:
+ if not info.name.endswith(".gz"):
+ steps.append("compress " + _renamed(base, info.name, index + 1))
+ if not policy.delay_compress:
+ steps.append("compress %s.1" % base)
+ return steps
+''',
+
+"test_units.py": r'''import unittest
+
+from logrot.units import UnitError, coerce, parse_duration, parse_size
+
+
+class UnitTests(unittest.TestCase):
+ def test_size_suffixes_are_binary(self):
+ self.assertEqual(parse_size("512"), 512)
+ self.assertEqual(parse_size("10k"), 10240)
+ self.assertEqual(parse_size("10K"), 10240)
+ self.assertEqual(parse_size("50M"), 50 * 1024 ** 2)
+ self.assertEqual(parse_size("1G"), 1024 ** 3)
+
+ def test_duration_suffixes(self):
+ self.assertEqual(parse_duration("90"), 90)
+ self.assertEqual(parse_duration("90s"), 90)
+ self.assertEqual(parse_duration("5m"), 300)
+ self.assertEqual(parse_duration("36h"), 129600)
+ self.assertEqual(parse_duration("2d"), 172800)
+ self.assertEqual(parse_duration("1w"), 604800)
+
+ def test_flags_and_counts(self):
+ self.assertIs(coerce("flag", "yes"), True)
+ self.assertIs(coerce("flag", "Off"), False)
+ self.assertEqual(coerce("count", "5"), 5)
+
+ def test_rejects_garbage(self):
+ cases = [("size", "10 MB"), ("size", "-5"), ("duration", "5y"),
+ ("count", "3k"), ("flag", "maybe")]
+ for kind, text in cases:
+ with self.assertRaises(UnitError, msg=text):
+ coerce(kind, text)
+
+
+if __name__ == "__main__":
+ unittest.main()
+''',
+
+"test_config.py": r'''import unittest
+
+from logrot.conffile import ConfigError, parse, policy_for
+from logrot.policy import Policy
+
+CONF = """
+# defaults for every block below
+rotate 9
+compress
+
+/var/log/app/*.log {
+ size 100k
+ rotate 2
+ nocompress
+}
+
+/var/log/nginx/access.log /var/log/nginx/error.log {
+ size 1G
+ delaycompress
+}
+"""
+
+
+class ConfigTests(unittest.TestCase):
+ def test_block_settings_and_defaults(self):
+ blocks = parse(CONF)
+ self.assertEqual([glob for glob, _ in blocks], [
+ "/var/log/app/*.log", "/var/log/nginx/access.log", "/var/log/nginx/error.log"])
+ self.assertEqual(blocks[0][1], Policy(max_bytes=102400, keep=2, compress=False))
+ nginx = Policy(max_bytes=1024 ** 3, keep=9, compress=True, delay_compress=True)
+ self.assertEqual(blocks[1][1], nginx)
+ self.assertEqual(blocks[2][1], nginx)
+
+ def test_first_matching_block_wins(self):
+ blocks = parse(CONF + "\n/var/log/app/debug.log {\n rotate 1\n}\n")
+ self.assertEqual(policy_for(blocks, "/var/log/app/debug.log").keep, 2)
+ self.assertEqual(policy_for(blocks, "/var/log/nginx/error.log").keep, 9)
+ self.assertIsNone(policy_for(blocks, "/var/log/syslog"))
+
+ def test_errors_name_the_line(self):
+ with self.assertRaises(ConfigError) as cm:
+ parse("/var/log/x.log {\n size 10M\n rotat 3\n}\n")
+ self.assertIn("line 3", str(cm.exception))
+ with self.assertRaises(ConfigError):
+ parse("/var/log/x.log {\n size ten\n}\n")
+ with self.assertRaises(ConfigError):
+ parse("/var/log/x.log {\n size 10M\n")
+
+
+if __name__ == "__main__":
+ unittest.main()
+''',
+
+"test_plan.py": r'''import unittest
+
+from logrot.conffile import parse, policy_for
+from logrot.planner import FileInfo, plan
+from logrot.policy import Policy
+from logrot.units import parse_size
+
+NOW = 1767225600
+DAY = 86400
+MIB = 1024 * 1024
+
+NIGHTLY = """
+compress
+
+/var/log/app/*.log {
+ size 50M
+ rotate 4
+ maxage 3
+ delaycompress
+}
+"""
+
+
+class PlanTests(unittest.TestCase):
+ def test_small_log_left_alone(self):
+ policy = Policy(max_bytes=parse_size("10M"), keep=3)
+ listing = [FileInfo("app.log", 2 * MIB, NOW), FileInfo("app.log.1", 9 * MIB, NOW - DAY)]
+ self.assertEqual(plan(policy, "app.log", listing, NOW), [])
+
+ def test_size_trigger_shifts_copies(self):
+ policy = Policy(max_bytes=parse_size("1M"), keep=3)
+ listing = [
+ FileInfo("app.log.2", MIB, NOW - 2 * DAY),
+ FileInfo("app.log", 2 * MIB, NOW - 60),
+ FileInfo("app.log.1", MIB, NOW - DAY),
+ ]
+ self.assertEqual(plan(policy, "app.log", listing, NOW), [
+ "rename app.log.2 app.log.3",
+ "rename app.log.1 app.log.2",
+ "rename app.log app.log.1",
+ ])
+
+ def test_keep_and_compress(self):
+ policy = Policy(max_bytes=parse_size("1k"), keep=2, compress=True)
+ listing = [
+ FileInfo("app.log", 4096, NOW),
+ FileInfo("app.log.1.gz", 300, NOW - DAY),
+ FileInfo("app.log.2.gz", 300, NOW - 2 * DAY),
+ ]
+ self.assertEqual(plan(policy, "app.log", listing, NOW), [
+ "delete app.log.2.gz",
+ "rename app.log.1.gz app.log.2.gz",
+ "rename app.log app.log.1",
+ "compress app.log.1",
+ ])
+
+ def test_age_limit_from_flags(self):
+ listing = [
+ FileInfo("app.log", 100, NOW),
+ FileInfo("app.log.1", 100, NOW - DAY),
+ FileInfo("app.log.2.gz", 100, NOW - 2 * DAY),
+ ]
+ policies = [
+ Policy.from_settings({"max_age": "36h", "keep": "5"}),
+ Policy.from_settings({"max_age": "129600", "keep": "5"}),
+ Policy.from_env({"LOGROT_MAX_AGE": "129600", "LOGROT_KEEP": "5", "HOME": "/root"}),
+ ]
+ for policy in policies:
+ self.assertEqual(plan(policy, "app.log", listing, NOW), ["delete app.log.2.gz"])
+
+ def test_nightly_config(self):
+ policy = policy_for(parse(NIGHTLY), "/var/log/app/app.log")
+ listing = [
+ FileInfo("app.log", 60 * MIB, NOW - 60),
+ FileInfo("app.log.1", 40 * MIB, NOW - 1 * DAY),
+ FileInfo("app.log.2.gz", 4 * MIB, NOW - 2 * DAY),
+ FileInfo("app.log.3.gz", 4 * MIB, NOW - 5 * DAY),
+ FileInfo("other.log", 10, NOW),
+ ]
+ self.assertEqual(plan(policy, "app.log", listing, NOW), [
+ "delete app.log.3.gz",
+ "rename app.log.2.gz app.log.3.gz",
+ "rename app.log.1 app.log.2",
+ "rename app.log app.log.1",
+ "compress app.log.2",
+ ])
+
+
+if __name__ == "__main__":
+ unittest.main()
+''',
+}
+
+
+def _patched(path, old, new):
+ """{path: PROJECT[path] with `old` replaced once}; fails loudly if `old` is not there."""
+ src = PROJECT[path]
+ assert src.count(old) == 1, (path, old)
+ return {path: src.replace(old, new)}
+
+
+HIDDEN = ("test_plan.py", "test_config.py", "test_units.py")
+FIX = _patched("logrot/conffile.py",
+ " settings[DIRECTIVES[key]] = words[1]\n",
+ " settings[DIRECTIVES[key]] = words[1] + \"d\" if key == \"maxage\" else words[1]\n")
+TEST_CMD = ["python3", "-B", "-m", "unittest", "-v"]
+PASS_RE = r"^(test_\w+) \(\S+\) \.\.\. ok$"
+TESTS = tuple(n for h in HIDDEN for n in re.findall(r"^ def (test_\w+)\(", PROJECT[h], re.M))
+WRONG = [
+ # the age check at the symptom site, read as days
+ _patched("logrot/planner.py",
+ "now - info.mtime > policy.max_age\n",
+ "now - info.mtime > policy.max_age * 86400\n"),
+ # bare durations as days in the shared parser
+ _patched("logrot/units.py",
+ '_DURATION = {"": 1, "s": 1,',
+ '_DURATION = {"": 86400, "s": 1,'),
+ # bare max_age as days for every policy source
+ _patched("logrot/policy.py",
+ " return cls(**{name: coerce(FIELD_KINDS[name], text) for name, text in settings.items()})\n",
+ " settings = dict(settings)\n"
+ " if str(settings.get(\"max_age\", \"\")).strip().isdigit():\n"
+ " settings[\"max_age\"] = str(settings[\"max_age\"]).strip() + \"d\"\n"
+ " return cls(**{name: coerce(FIELD_KINDS[name], text) for name, text in settings.items()})\n"),
+]
diff --git a/bench/tasks/fix_hard/rust_allowlist.py b/bench/tasks/fix_hard/rust_allowlist.py
new file mode 100644
index 0000000..1118de6
--- /dev/null
+++ b/bench/tasks/fix_hard/rust_allowlist.py
@@ -0,0 +1,513 @@
+"""Rust: an IPv4 allowlist (CIDR blocks, dash ranges, single hosts) merged into half-open spans.
+range.rs documents spans as [start, end); Cidr::to_range in cidr.rs returns base | !mask, the
+block's last address, as `end`, so every CIDR entry loses its last address and a /32 becomes
+empty. The symptom is IpSet::contains failing for a /32 bastion host (set.rs, via the test);
+the tempting patches (inclusive contains in range.rs or set.rs, a /32 special case in set.rs)
+either break the dash-range/host tests or still miss the last address of the /31 uplink."""
+import re
+
+ITEM_ID = "rust-allowlist"
+LANG = "rust"
+TOOL = "cargo"
+
+PROJECT = {
+"Cargo.toml": r'''[package]
+name = "allowlist"
+version = "0.1.0"
+edition = "2021"
+
+[dependencies]
+''',
+
+"src/lib.rs": r'''//! IPv4 allowlists for firewall and reverse-proxy configs.
+//!
+//! An allowlist file holds one entry per line:
+//!
+//! ```text
+//! 10.40.0.0/22 # CIDR block
+//! 10.8.0.10-10.8.0.250 # dash range, both ends included
+//! 198.51.100.10 # single host
+//! ```
+//!
+//! Every entry becomes an [`IpRange`] span (see [`range`] for the span
+//! convention) and an [`IpSet`] keeps the spans sorted and merged, so a lookup
+//! is one binary search.
+
+pub mod addr;
+pub mod cidr;
+pub mod range;
+pub mod set;
+
+pub use addr::{format_ipv4, parse_ipv4, AddrError};
+pub use cidr::Cidr;
+pub use range::IpRange;
+pub use set::{EntryError, IpSet};
+''',
+
+"src/addr.rs": r'''//! Dotted-quad IPv4 addresses as `u32`, plus prefix masks.
+
+use std::fmt;
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum AddrError {
+ /// Not four decimal octets in 0..=255.
+ Malformed(String),
+ /// A prefix length outside 0..=32, or not a number.
+ BadPrefix(String),
+ /// A CIDR whose base address has bits set below the prefix.
+ HostBits(String),
+ /// A dash range whose end comes before its start.
+ Reversed(String),
+}
+
+impl fmt::Display for AddrError {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ AddrError::Malformed(s) => write!(f, "malformed address {:?}", s),
+ AddrError::BadPrefix(s) => write!(f, "bad prefix length in {:?}", s),
+ AddrError::HostBits(s) => write!(f, "host bits set in {:?}", s),
+ AddrError::Reversed(s) => write!(f, "range ends before it starts: {:?}", s),
+ }
+ }
+}
+
+impl std::error::Error for AddrError {}
+
+/// Parses `a.b.c.d`. Octets with leading zeros are rejected, so `010.0.0.1`
+/// is never silently read as decimal.
+pub fn parse_ipv4(text: &str) -> Result<u32, AddrError> {
+ let bad = || AddrError::Malformed(text.to_string());
+ let mut value: u32 = 0;
+ let mut octets = 0;
+ for part in text.trim().split('.') {
+ let digits = !part.is_empty() && part.len() <= 3 && part.bytes().all(|b| b.is_ascii_digit());
+ if !digits || (part.len() > 1 && part.starts_with('0')) || octets == 4 {
+ return Err(bad());
+ }
+ let octet: u32 = part.parse().map_err(|_| bad())?;
+ if octet > 255 {
+ return Err(bad());
+ }
+ value = (value << 8) | octet;
+ octets += 1;
+ }
+ if octets != 4 {
+ return Err(bad());
+ }
+ Ok(value)
+}
+
+pub fn format_ipv4(ip: u32) -> String {
+ let [a, b, c, d] = ip.to_be_bytes();
+ format!("{}.{}.{}.{}", a, b, c, d)
+}
+
+/// The network mask for a prefix length: `/0` is 0.0.0.0, `/24` is
+/// 255.255.255.0, `/32` is 255.255.255.255. `len` must be at most 32.
+pub fn prefix_mask(len: u8) -> u32 {
+ if len == 0 {
+ 0
+ } else {
+ u32::MAX << (32 - u32::from(len))
+ }
+}
+''',
+
+"src/range.rs": r'''//! `IpRange`: a span of IPv4 addresses.
+//!
+//! Spans are half-open, `[start, end)`: `start` is the first address in the
+//! span and `end` is one past the last, so `len()` is `end - start`. They are
+//! held as u64 so that a span reaching 255.255.255.255 still has a
+//! representable `end` (2^32). Every producer of spans (dash ranges, single
+//! hosts, CIDR blocks) and every consumer (`merge`, `IpSet`) uses this
+//! convention.
+//!
+//! The text form `a-b` is inclusive on both ends, the way people write it in
+//! firewall configs: `10.0.0.1-10.0.0.9` is nine addresses.
+
+use crate::addr::{format_ipv4, parse_ipv4, AddrError};
+use std::fmt;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
+pub struct IpRange {
+ pub start: u64,
+ pub end: u64,
+}
+
+impl IpRange {
+ pub fn new(start: u64, end: u64) -> IpRange {
+ debug_assert!(start <= end && end <= 1 << 32, "bad span {}..{}", start, end);
+ IpRange { start, end }
+ }
+
+ pub fn single(ip: u32) -> IpRange {
+ IpRange::new(u64::from(ip), u64::from(ip) + 1)
+ }
+
+ /// Parses the inclusive text form `first-last`.
+ pub fn parse(text: &str) -> Result<IpRange, AddrError> {
+ let (first, last) = text
+ .split_once('-')
+ .ok_or_else(|| AddrError::Malformed(text.to_string()))?;
+ let (first, last) = (parse_ipv4(first)?, parse_ipv4(last)?);
+ if last < first {
+ return Err(AddrError::Reversed(text.to_string()));
+ }
+ Ok(IpRange::new(u64::from(first), u64::from(last) + 1))
+ }
+
+ pub fn len(&self) -> u64 {
+ self.end - self.start
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.start == self.end
+ }
+
+ pub fn contains(&self, ip: u32) -> bool {
+ let ip = u64::from(ip);
+ self.start <= ip && ip < self.end
+ }
+}
+
+impl fmt::Display for IpRange {
+ /// The inclusive text form, the inverse of `parse`.
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ if self.is_empty() {
+ return write!(f, "(empty at {})", format_ipv4(self.start as u32));
+ }
+ write!(f, "{}-{}", format_ipv4(self.start as u32), format_ipv4((self.end - 1) as u32))
+ }
+}
+
+/// Sorts spans and joins any that overlap or touch: `[1,5)` and `[5,9)` become
+/// `[1,9)`, while `[1,5)` and `[6,9)` stay apart.
+pub fn merge(mut spans: Vec<IpRange>) -> Vec<IpRange> {
+ spans.sort();
+ let mut out: Vec<IpRange> = Vec::with_capacity(spans.len());
+ for span in spans {
+ match out.last_mut() {
+ Some(prev) if span.start <= prev.end => prev.end = prev.end.max(span.end),
+ _ => out.push(span),
+ }
+ }
+ out
+}
+''',
+
+"src/cidr.rs": r'''//! CIDR blocks: an aligned base address and a prefix length.
+
+use crate::addr::{format_ipv4, parse_ipv4, prefix_mask, AddrError};
+use crate::range::IpRange;
+use std::fmt;
+use std::str::FromStr;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
+pub struct Cidr {
+ base: u32,
+ len: u8,
+}
+
+impl Cidr {
+ /// A block from its parts. The base must be aligned to the prefix:
+ /// `10.0.0.0/8` is fine, `10.0.0.1/8` is `HostBits`.
+ pub fn new(base: u32, len: u8) -> Result<Cidr, AddrError> {
+ let text = || format!("{}/{}", format_ipv4(base), len);
+ if len > 32 {
+ return Err(AddrError::BadPrefix(text()));
+ }
+ if base & !prefix_mask(len) != 0 {
+ return Err(AddrError::HostBits(text()));
+ }
+ Ok(Cidr { base, len })
+ }
+
+ pub fn parse(text: &str) -> Result<Cidr, AddrError> {
+ let (addr, len) = text
+ .trim()
+ .split_once('/')
+ .ok_or_else(|| AddrError::Malformed(text.to_string()))?;
+ let len: u8 = len.parse().map_err(|_| AddrError::BadPrefix(text.to_string()))?;
+ Cidr::new(parse_ipv4(addr)?, len)
+ }
+
+ pub fn base(&self) -> u32 {
+ self.base
+ }
+
+ pub fn prefix_len(&self) -> u8 {
+ self.len
+ }
+
+ /// Number of addresses in the block.
+ pub fn size(&self) -> u64 {
+ 1u64 << (32 - u32::from(self.len))
+ }
+
+ pub fn contains(&self, ip: u32) -> bool {
+ ip & prefix_mask(self.len) == self.base
+ }
+
+ /// The block as a span, for merging with the other entries of an `IpSet`.
+ pub fn to_range(&self) -> IpRange {
+ let mask = prefix_mask(self.len);
+ IpRange::new(u64::from(self.base), u64::from(self.base | !mask))
+ }
+}
+
+impl FromStr for Cidr {
+ type Err = AddrError;
+
+ fn from_str(text: &str) -> Result<Cidr, AddrError> {
+ Cidr::parse(text)
+ }
+}
+
+impl fmt::Display for Cidr {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "{}/{}", format_ipv4(self.base), self.len)
+ }
+}
+''',
+
+"src/set.rs": r'''//! `IpSet`: the union of allowlist entries, kept as sorted, merged spans.
+
+use crate::addr::{parse_ipv4, AddrError};
+use crate::cidr::Cidr;
+use crate::range::{merge, IpRange};
+use std::fmt;
+
+#[derive(Debug, Clone, Default, PartialEq, Eq)]
+pub struct IpSet {
+ spans: Vec<IpRange>,
+}
+
+/// A line of allowlist text that could not be read (`line` counts from 1).
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct EntryError {
+ pub line: usize,
+ pub reason: AddrError,
+}
+
+impl fmt::Display for EntryError {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "line {}: {}", self.line, self.reason)
+ }
+}
+
+impl std::error::Error for EntryError {}
+
+impl IpSet {
+ /// Reads allowlist text: one entry per line; `#` starts a comment and
+ /// blank lines are skipped.
+ pub fn parse(text: &str) -> Result<IpSet, EntryError> {
+ let mut spans = Vec::new();
+ for (index, raw) in text.lines().enumerate() {
+ let entry = raw.split('#').next().unwrap_or("").trim();
+ if entry.is_empty() {
+ continue;
+ }
+ let span = entry_span(entry).map_err(|reason| EntryError { line: index + 1, reason })?;
+ spans.push(span);
+ }
+ Ok(IpSet::from_spans(spans))
+ }
+
+ pub fn from_spans(spans: Vec<IpRange>) -> IpSet {
+ IpSet { spans: merge(spans) }
+ }
+
+ pub fn spans(&self) -> &[IpRange] {
+ &self.spans
+ }
+
+ pub fn contains(&self, ip: u32) -> bool {
+ let after = self.spans.partition_point(|s| s.start <= u64::from(ip));
+ after > 0 && self.spans[after - 1].contains(ip)
+ }
+
+ /// Total number of addresses in the set.
+ pub fn size(&self) -> u64 {
+ self.spans.iter().map(IpRange::len).sum()
+ }
+
+ /// The fewest CIDR blocks that cover exactly this set, in address order.
+ pub fn to_cidrs(&self) -> Vec<Cidr> {
+ let mut out = Vec::new();
+ for span in &self.spans {
+ let mut start = span.start;
+ while start < span.end {
+ // the largest block aligned at `start` that stays inside the span
+ let mut bits = start.trailing_zeros().min(32);
+ while (1u64 << bits) > span.end - start {
+ bits -= 1;
+ }
+ out.push(Cidr::new(start as u32, (32 - bits) as u8).expect("aligned block"));
+ start += 1u64 << bits;
+ }
+ }
+ out
+ }
+}
+
+/// One entry as a span: `a.b.c.d/len`, `a.b.c.d-e.f.g.h` or `a.b.c.d`.
+fn entry_span(entry: &str) -> Result<IpRange, AddrError> {
+ if entry.contains('/') {
+ Ok(Cidr::parse(entry)?.to_range())
+ } else if entry.contains('-') {
+ IpRange::parse(entry)
+ } else {
+ Ok(IpRange::single(parse_ipv4(entry)?))
+ }
+}
+''',
+
+"tests/allowlist.rs": r'''use allowlist::range::merge;
+use allowlist::{format_ipv4, parse_ipv4, Cidr, IpRange, IpSet};
+
+fn ip(text: &str) -> u32 {
+ parse_ipv4(text).unwrap()
+}
+
+fn cidrs(set: &IpSet) -> Vec<String> {
+ set.to_cidrs().iter().map(|c| c.to_string()).collect()
+}
+
+#[test]
+fn dotted_quads() {
+ assert_eq!(ip("10.0.0.1"), 0x0a00_0001);
+ assert_eq!(format_ipv4(0xc0a8_0101), "192.168.1.1");
+ for bad in ["10.0.0", "10.0.0.256", "010.0.0.1", "10.0.0.1.5", "a.b.c.d", ""] {
+ assert!(parse_ipv4(bad).is_err(), "{:?} accepted", bad);
+ }
+}
+
+#[test]
+fn dash_ranges_are_inclusive() {
+ let r = IpRange::parse("10.0.0.1-10.0.0.9").unwrap();
+ assert_eq!(r.len(), 9);
+ assert!(r.contains(ip("10.0.0.1")));
+ assert!(r.contains(ip("10.0.0.9")));
+ assert!(!r.contains(ip("10.0.0.10")));
+ assert_eq!(r.to_string(), "10.0.0.1-10.0.0.9");
+ assert!(IpRange::parse("10.0.0.9-10.0.0.1").is_err());
+ assert_eq!(IpRange::parse("0.0.0.0-255.255.255.255").unwrap().len(), 1 << 32);
+}
+
+#[test]
+fn merge_joins_touching_spans_only() {
+ let a = IpRange::parse("10.0.0.1-10.0.0.4").unwrap();
+ let b = IpRange::parse("10.0.0.5-10.0.0.9").unwrap();
+ let c = IpRange::parse("10.0.0.11-10.0.0.20").unwrap();
+ let merged: Vec<String> = merge(vec![c, b, a]).iter().map(|s| s.to_string()).collect();
+ assert_eq!(merged, ["10.0.0.1-10.0.0.9", "10.0.0.11-10.0.0.20"]);
+}
+
+#[test]
+fn cidr_parse_and_display() {
+ for text in ["10.0.0.0/8", "192.168.4.0/22", "0.0.0.0/0", "203.0.113.7/32"] {
+ assert_eq!(text.parse::<Cidr>().unwrap().to_string(), text);
+ }
+ assert_eq!(Cidr::parse("192.168.4.0/22").unwrap().size(), 1024);
+ assert!(Cidr::parse("10.0.0.1/24").is_err());
+ assert!(Cidr::parse("10.0.0.0/33").is_err());
+ assert!(Cidr::parse("10.0.0.0").is_err());
+}
+
+#[test]
+fn cidr_contains_by_prefix() {
+ let c = Cidr::parse("192.168.4.0/22").unwrap();
+ assert!(c.contains(ip("192.168.4.0")));
+ assert!(c.contains(ip("192.168.7.255")));
+ assert!(!c.contains(ip("192.168.8.0")));
+ assert!(!c.contains(ip("192.168.3.255")));
+}
+
+#[test]
+fn hosts_and_ranges() {
+ let set = IpSet::parse("10.0.0.1\n10.0.0.2-10.0.0.3 # pair\n\n10.0.0.4\n").unwrap();
+ assert_eq!(set.size(), 4);
+ assert!(set.contains(ip("10.0.0.4")));
+ assert!(!set.contains(ip("10.0.0.5")));
+ assert!(!set.contains(ip("10.0.0.0")));
+ assert_eq!(cidrs(&set), ["10.0.0.1/32", "10.0.0.2/31", "10.0.0.4/32"]);
+}
+
+#[test]
+fn ranges_summarize_to_blocks() {
+ let set = IpSet::parse("192.168.0.0-192.168.1.255\n192.168.2.0-192.168.2.9\n").unwrap();
+ assert_eq!(set.size(), 522);
+ assert_eq!(cidrs(&set), ["192.168.0.0/23", "192.168.2.0/29", "192.168.2.8/31"]);
+}
+
+#[test]
+fn bad_lines_are_reported() {
+ let err = IpSet::parse("10.0.0.0/8\n# fine\n10.0.0.300\n").unwrap_err();
+ assert_eq!(err.line, 3);
+ assert!(IpSet::parse("10.0.0.1/16").is_err());
+}
+
+const SITE: &str = "
+# office LAN
+10.40.0.0/22
+# bastion
+198.51.100.10/32
+# uplink to the ISP router
+10.255.0.0/31
+# VPN pool
+10.8.0.10-10.8.0.250
+";
+
+#[test]
+fn site_allowlist() {
+ let set = IpSet::parse(SITE).unwrap();
+ let expected = [
+ "10.40.0.1",
+ "10.40.2.17",
+ "198.51.100.10",
+ "10.255.0.0",
+ "10.255.0.1",
+ "10.8.0.10",
+ "10.8.0.250",
+ ];
+ for addr in expected {
+ assert!(set.contains(ip(addr)), "{} not matched", addr);
+ }
+}
+''',
+}
+
+
+def _patched(path, old, new):
+ """{path: PROJECT[path] with `old` replaced once}; fails loudly if `old` is not there."""
+ src = PROJECT[path]
+ assert src.count(old) == 1, (path, old)
+ return {path: src.replace(old, new)}
+
+
+HIDDEN = ("tests/allowlist.rs",)
+FIX = _patched("src/cidr.rs",
+ "u64::from(self.base | !mask))\n",
+ "u64::from(self.base | !mask) + 1)\n")
+TEST_CMD = ["cargo", "test", "--offline"]
+PASS_RE = r"^test (\S+) \.\.\. ok$"
+TESTS = tuple(re.findall(r"^#\[test\]\nfn (\w+)\(", PROJECT["tests/allowlist.rs"], re.M))
+WRONG = [
+ # inclusive end in the span type
+ _patched("src/range.rs",
+ "self.start <= ip && ip < self.end\n",
+ "self.start <= ip && ip <= self.end\n"),
+ # inclusive end at the lookup site
+ _patched("src/set.rs",
+ "after > 0 && self.spans[after - 1].contains(ip)\n",
+ "after > 0 && u64::from(ip) <= self.spans[after - 1].end\n"),
+ # a /32 entry read as a single host
+ _patched("src/set.rs",
+ " Ok(Cidr::parse(entry)?.to_range())\n",
+ " let block = Cidr::parse(entry)?;\n"
+ " if block.prefix_len() == 32 {\n"
+ " Ok(IpRange::single(block.base()))\n"
+ " } else {\n"
+ " Ok(block.to_range())\n"
+ " }\n"),
+]
diff --git a/bench/tasks/fix_hard/sh_backup_retention.py b/bench/tasks/fix_hard/sh_backup_retention.py
new file mode 100644
index 0000000..c752e88
--- /dev/null
+++ b/bench/tasks/fix_hard/sh_backup_retention.py
@@ -0,0 +1,416 @@
+"""Bash: a backup retention pruner (keep-daily/weekly/monthly/within) split across prune.sh and
+lib/{calendar,dates,backups,policy}.sh. calendar.sh's is_leap prints 1 or 0 for arithmetic, but
+dates.sh's day_number tests it as `[ "$(is_leap "$y")" ]`, which is true for "0" too, so every
+year gets a February 29th: March-December dates of common years land one day late. Only a
+keep-within window that crosses the end of February in a common year shows it (a 7-day-old
+archive is dropped); leap-year windows, same-month windows and the Jan/Feb weekly fixtures come
+out right. The tempting patches (a looser age bound in policy.sh, is_leap printing nothing for
+common years, dropping the leap-day adjustment) each fix that test but break the boundary,
+helper or leap-year tests. Runs on macOS /bin/bash 3.2 and Linux bash 5."""
+import re
+
+ITEM_ID = "sh-backup-retention"
+LANG = "sh"
+TOOL = "bash"
+
+PROJECT = {
+"prune.sh": r'''#!/bin/bash
+# prune.sh: thin out one job's NAME-YYYY-MM-DD[_HHMM].tar.gz archives in a backup directory.
+#
+# prune.sh [-n] [-d DAILY] [-w WEEKLY] [-m MONTHLY] [-k DAYS] DIR NAME
+#
+# -n dry run: print the plan, delete nothing
+# -d -w -m keep the newest archive of each of the N most recent days / ISO weeks /
+# calendar months that have archives
+# -k DAYS keep every archive dated at most DAYS days before the newest one
+#
+# Prints the plan ("keep FILE RULES" / "drop FILE", newest first), then deletes the dropped
+# archives unless -n is given. Runs on bash 3.2 (macOS) and later.
+
+here=$(cd "$(dirname "$0")" && pwd)
+. "$here/lib/calendar.sh"
+. "$here/lib/dates.sh"
+. "$here/lib/backups.sh"
+. "$here/lib/policy.sh"
+
+usage() {
+ echo "usage: prune.sh [-n] [-d DAILY] [-w WEEKLY] [-m MONTHLY] [-k DAYS] DIR NAME" >&2
+ exit 2
+}
+
+dry_run=0 daily=0 weekly=0 monthly=0 within=-1
+while getopts nd:w:m:k: opt; do
+ case $opt in
+ n) dry_run=1 ;;
+ d) daily=$OPTARG ;;
+ w) weekly=$OPTARG ;;
+ m) monthly=$OPTARG ;;
+ k) within=$OPTARG ;;
+ *) usage ;;
+ esac
+done
+shift $((OPTIND - 1))
+[ "$#" -eq 2 ] || usage
+dir=$1 name=$2
+[ -d "$dir" ] || { echo "prune: no such directory: $dir" >&2; exit 2; }
+
+for n in "$daily" "$weekly" "$monthly"; do
+ case $n in "" | *[!0-9]*) echo "prune: -d/-w/-m take a whole number" >&2; exit 2 ;; esac
+done
+case $within in -1) ;; "" | *[!0-9]*) echo "prune: -k takes a whole number of days" >&2; exit 2 ;; esac
+if [ "$daily" -eq 0 ] && [ "$weekly" -eq 0 ] && [ "$monthly" -eq 0 ] && [ "$within" -lt 0 ]; then
+ echo "prune: no retention rule given; refusing to drop every archive" >&2
+ exit 2
+fi
+
+plan=$(list_backups "$dir" "$name" | plan_retention "$daily" "$weekly" "$monthly" "$within")
+[ -n "$plan" ] || exit 0
+echo "$plan"
+[ "$dry_run" -eq 0 ] || exit 0
+
+echo "$plan" | while read -r verdict file rules; do
+ if [ "$verdict" = drop ]; then
+ rm -f -- "$dir/$file"
+ fi
+done
+''',
+
+"lib/calendar.sh": r'''# calendar.sh: Gregorian calendar facts. Years, months and days are plain decimal numbers.
+
+# is_leap Y: prints 1 when Y is a leap year and 0 when it is not, for use in arithmetic
+# such as $((365 + $(is_leap 2024))). It always succeeds.
+is_leap() {
+ if [ $(($1 % 4)) -eq 0 ] && { [ $(($1 % 100)) -ne 0 ] || [ $(($1 % 400)) -eq 0 ]; }; then
+ echo 1
+ else
+ echo 0
+ fi
+}
+
+# days_in_month Y M: prints the number of days in month M (1-12) of year Y.
+days_in_month() {
+ case $2 in
+ 2) echo $((28 + $(is_leap "$1"))) ;;
+ 4 | 6 | 9 | 11) echo 30 ;;
+ *) echo 31 ;;
+ esac
+}
+
+# valid_date Y M D: succeeds when Y-M-D exists on the calendar.
+valid_date() {
+ [ "$#" -eq 3 ] || return 1
+ [ "$2" -ge 1 ] && [ "$2" -le 12 ] || return 1
+ [ "$3" -ge 1 ] && [ "$3" -le "$(days_in_month "$1" "$2")" ]
+}
+''',
+
+"lib/dates.sh": r'''# dates.sh: date arithmetic without GNU or BSD date(1), so it behaves the same everywhere.
+# Needs calendar.sh.
+
+# split_date YYYY-MM-DD: prints "Y M D" as plain decimals (zero padding removed).
+split_date() {
+ local y=${1%%-*} rest=${1#*-}
+ local m=${rest%%-*} d=${rest#*-}
+ echo "$((10#$y)) $((10#$m)) $((10#$d))"
+}
+
+# day_number Y M D: prints the number of days from 1970-01-01 (day 0) to Y-M-D.
+day_number() {
+ local y=$1 m=$2 d=$3 p=$(($1 - 1)) n
+ # whole years since 1970, plus the leap days in years 1970..Y-1
+ # (477 = leap years from year 1 through 1969)
+ n=$(((y - 1970) * 365 + p / 4 - p / 100 + p / 400 - 477))
+ # days in the months before M, in a common year
+ set -- 0 31 59 90 120 151 181 212 243 273 304 334
+ shift $((m - 1))
+ n=$((n + $1 + d - 1))
+ # Y's own February 29th, once it is behind us
+ if [ "$m" -gt 2 ] && [ "$(is_leap "$y")" ]; then
+ n=$((n + 1))
+ fi
+ echo "$n"
+}
+
+# weekday Y M D: prints 1 (Monday) .. 7 (Sunday). 1970-01-01 was a Thursday.
+weekday() {
+ echo $((($(day_number "$1" "$2" "$3") + 3) % 7 + 1))
+}
+
+# iso_week Y M D: prints the ISO 8601 week, e.g. 2026-W07. Weeks start on Monday and belong
+# to the year that holds their Thursday, so early January can fall in the previous year's
+# last week and late December in week 01 of the next year.
+iso_week() {
+ local y=$1 n thu
+ n=$(day_number "$1" "$2" "$3")
+ thu=$((n - $(weekday "$1" "$2" "$3") + 4))
+ if [ "$thu" -lt "$(day_number "$y" 1 1)" ]; then
+ y=$((y - 1))
+ elif [ "$thu" -ge "$(day_number $((y + 1)) 1 1)" ]; then
+ y=$((y + 1))
+ fi
+ printf '%04d-W%02d\n' "$y" $(((thu - $(day_number "$y" 1 1)) / 7 + 1))
+}
+''',
+
+"lib/backups.sh": r'''# backups.sh: find the backup archives of one job. Needs calendar.sh and dates.sh.
+
+# list_backups DIR NAME: prints "STAMP FILE" for each NAME-YYYY-MM-DD.tar.gz or
+# NAME-YYYY-MM-DD_HHMM.tar.gz in DIR, newest first. STAMP is the part between "NAME-" and
+# ".tar.gz"; an archive without a time sorts before every timed one of the same day.
+# Archives named after a date that does not exist are skipped with a warning on stderr;
+# anything else in DIR is ignored.
+list_backups() {
+ local dir=$1 name=$2 path file stamp
+ for path in "$dir/$name"-*.tar.gz; do
+ [ -f "$path" ] || continue
+ file=${path##*/}
+ stamp=${file#"$name"-}
+ stamp=${stamp%.tar.gz}
+ case $stamp in
+ [0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]) ;;
+ [0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]_[0-9][0-9][0-9][0-9]) ;;
+ *) continue ;;
+ esac
+ if ! valid_date $(split_date "${stamp%%_*}"); then
+ echo "prune: skipping $file: no such date" >&2
+ continue
+ fi
+ echo "$stamp $file"
+ done | LC_ALL=C sort -r
+}
+''',
+
+"lib/policy.sh": r'''# policy.sh: decide which backups a retention policy keeps. Needs dates.sh.
+
+# plan_retention DAILY WEEKLY MONTHLY WITHIN
+# stdin: "STAMP FILE" lines, newest first, as list_backups prints them
+# stdout: "keep FILE RULES" or "drop FILE" for each input line, in the same order
+#
+# A backup is kept by rule "daily" when it is the newest backup of one of the DAILY most
+# recent days that have backups; "weekly" and "monthly" do the same for ISO weeks and
+# calendar months. Rule "within" keeps every backup whose date is at most WITHIN days
+# before the newest backup's date (ages are whole calendar days; WITHIN=0 keeps all of the
+# newest day). A count of 0 turns its rule off, and so does a negative WITHIN. RULES lists
+# every rule that kept the file, comma-separated.
+plan_retention() {
+ local daily=$1 weekly=$2 monthly=$3 within=$4
+ local stamp file date y m d why key age newest=""
+ local last_day="" last_week="" last_month="" days=0 weeks=0 months=0
+ while read -r stamp file; do
+ [ -n "$file" ] || continue
+ date=${stamp%%_*}
+ set -- $(split_date "$date")
+ y=$1 m=$2 d=$3
+ why=""
+
+ if [ "$date" != "$last_day" ]; then
+ last_day=$date
+ if [ "$days" -lt "$daily" ]; then days=$((days + 1)); why="$why,daily"; fi
+ fi
+
+ key=$(iso_week "$y" "$m" "$d")
+ if [ "$key" != "$last_week" ]; then
+ last_week=$key
+ if [ "$weeks" -lt "$weekly" ]; then weeks=$((weeks + 1)); why="$why,weekly"; fi
+ fi
+
+ key=${date%-*}
+ if [ "$key" != "$last_month" ]; then
+ last_month=$key
+ if [ "$months" -lt "$monthly" ]; then months=$((months + 1)); why="$why,monthly"; fi
+ fi
+
+ key=$(day_number "$y" "$m" "$d")
+ [ -n "$newest" ] || newest=$key
+ age=$((newest - key))
+ if [ "$within" -ge 0 ] && [ "$age" -le "$within" ]; then why="$why,within"; fi
+
+ if [ -n "$why" ]; then
+ echo "keep $file ${why#,}"
+ else
+ echo "drop $file"
+ fi
+ done
+}
+''',
+
+"tests/run.sh": r'''#!/bin/bash
+# tests/run.sh: runs every test_* function below in its own mktemp -d work dir. Prints
+# "PASS name" or "FAIL name" (a failure is followed by a diff of expected vs. actual) and
+# exits 1 if any test failed.
+root=$(cd "$(dirname "$0")/.." && pwd)
+. "$root/lib/calendar.sh"
+. "$root/lib/dates.sh"
+failed=0
+
+prune() { "$BASH" "$root/prune.sh" "$@"; }
+
+# mk FILE...: empty archives in the work dir
+mk() {
+ local f
+ for f in "$@"; do : >"$work/$f"; done
+}
+
+# check EXPECTED ACTUAL
+check() {
+ if [ "$1" = "$2" ]; then
+ echo "PASS $current"
+ else
+ echo "FAIL $current"
+ printf '%s\n' "$1" >"$work/.expected"
+ printf '%s\n' "$2" >"$work/.actual"
+ diff "$work/.expected" "$work/.actual" | sed 's/^/ /'
+ failed=1
+ fi
+}
+
+test_calendar_helpers() {
+ check "1 0 0 1 / 29 28 30 / yes no" \
+ "$(is_leap 2024) $(is_leap 2026) $(is_leap 1900) $(is_leap 2000) / $(days_in_month 2024 2) $(days_in_month 2026 2) $(days_in_month 2026 4) / $(valid_date 2024 2 29 && echo yes || echo no) $(valid_date 2026 2 29 && echo yes || echo no)"
+}
+
+test_day_numbers() {
+ check "0 11017 19782 18630" \
+ "$(day_number 1970 1 1) $(day_number 2000 3 1) $(day_number 2024 2 29) $(day_number 2021 1 3)"
+}
+
+test_iso_weeks() {
+ check "2026-W01 2020-W53 2024-W52 2025-W01 2026-W07" \
+ "$(iso_week 2026 1 1) $(iso_week 2021 1 3) $(iso_week 2024 12 29) $(iso_week 2024 12 30) $(iso_week 2026 2 15)"
+}
+
+test_daily_newest_per_day() {
+ mk db-2026-10-12_0300.tar.gz db-2026-10-12_1500.tar.gz db-2026-10-11_0300.tar.gz \
+ db-2026-10-10.tar.gz db-2026-10-09_0300.tar.gz
+ check "keep db-2026-10-12_1500.tar.gz daily
+drop db-2026-10-12_0300.tar.gz
+keep db-2026-10-11_0300.tar.gz daily
+keep db-2026-10-10.tar.gz daily
+drop db-2026-10-09_0300.tar.gz" "$(prune -n -d 3 "$work" db)"
+}
+
+test_weekly_iso_weeks() {
+ mk web-2026-02-15.tar.gz web-2026-02-10.tar.gz web-2026-02-09.tar.gz \
+ web-2026-02-08.tar.gz web-2026-02-02.tar.gz web-2026-02-01.tar.gz
+ check "keep web-2026-02-15.tar.gz weekly
+drop web-2026-02-10.tar.gz
+drop web-2026-02-09.tar.gz
+keep web-2026-02-08.tar.gz weekly
+drop web-2026-02-02.tar.gz
+drop web-2026-02-01.tar.gz" "$(prune -n -w 2 "$work" web)"
+}
+
+test_monthly_and_daily() {
+ mk db-2026-10-01.tar.gz db-2026-09-30_2300.tar.gz db-2026-09-30_0100.tar.gz \
+ db-2026-09-15.tar.gz db-2026-08-31.tar.gz db-2026-07-04.tar.gz
+ check "keep db-2026-10-01.tar.gz daily,monthly
+keep db-2026-09-30_2300.tar.gz monthly
+drop db-2026-09-30_0100.tar.gz
+drop db-2026-09-15.tar.gz
+keep db-2026-08-31.tar.gz monthly
+drop db-2026-07-04.tar.gz" "$(prune -n -d 1 -m 3 "$work" db)"
+}
+
+test_within_edge_inclusive() {
+ mk app-2026-10-12.tar.gz app-2026-10-08.tar.gz app-2026-10-05.tar.gz \
+ app-2026-10-04.tar.gz app-2026-09-28.tar.gz
+ check "keep app-2026-10-12.tar.gz within
+keep app-2026-10-08.tar.gz within
+keep app-2026-10-05.tar.gz within
+drop app-2026-10-04.tar.gz
+drop app-2026-09-28.tar.gz" "$(prune -n -k 7 "$work" app)"
+}
+
+test_within_db_nightlies() {
+ mk db-2024-03-02.tar.gz db-2024-03-01.tar.gz db-2024-02-29.tar.gz \
+ db-2024-02-28.tar.gz db-2024-02-27.tar.gz
+ check "keep db-2024-03-02.tar.gz daily,within
+keep db-2024-03-01.tar.gz within
+keep db-2024-02-29.tar.gz within
+keep db-2024-02-28.tar.gz within
+drop db-2024-02-27.tar.gz" "$(prune -n -d 1 -k 3 "$work" db)"
+}
+
+test_within_web_nightlies() {
+ mk web-2026-03-03.tar.gz web-2026-03-01.tar.gz web-2026-02-26.tar.gz \
+ web-2026-02-24.tar.gz web-2026-02-23.tar.gz
+ check "keep web-2026-03-03.tar.gz daily,within
+keep web-2026-03-01.tar.gz within
+keep web-2026-02-26.tar.gz within
+keep web-2026-02-24.tar.gz within
+drop web-2026-02-23.tar.gz" "$(prune -n -d 1 -k 7 "$work" web)"
+}
+
+test_skips_impossible_dates() {
+ mk db-2026-03-01_0300.tar.gz db-2024-02-29.tar.gz db-2026-02-29.tar.gz \
+ db-2026-13-01.tar.gz db-latest.tar.gz notes.txt
+ check "keep db-2026-03-01_0300.tar.gz daily
+keep db-2024-02-29.tar.gz daily
+skipped 2" "$(prune -n -d 5 "$work" db 2>"$work/.stderr")
+skipped $(grep -c 'no such date' "$work/.stderr")"
+}
+
+test_prune_deletes_dropped() {
+ mk db-2026-10-12.tar.gz db-2026-10-11.tar.gz db-2026-10-10.tar.gz db-2026-10-09.tar.gz \
+ other-2026-10-01.tar.gz
+ prune -d 2 "$work" db >/dev/null
+ check "db-2026-10-11.tar.gz db-2026-10-12.tar.gz other-2026-10-01.tar.gz" \
+ "$(cd "$work" && LC_ALL=C ls | tr '\n' ' ' | sed 's/ $//')"
+}
+
+test_dry_run_deletes_nothing() {
+ mk db-2026-10-12.tar.gz db-2026-10-11.tar.gz db-2026-10-10.tar.gz
+ prune -n -d 1 "$work" db >/dev/null
+ check "3" "$(cd "$work" && ls | wc -l | tr -d ' ')"
+}
+
+test_refuses_without_rules() {
+ mk db-2026-10-12.tar.gz db-2026-10-11.tar.gz
+ prune "$work" db 2>/dev/null
+ local rc=$?
+ check "status 2, 2 left" "status $rc, $(cd "$work" && ls | wc -l | tr -d ' ') left"
+}
+
+for t in $(declare -F | sed -n 's/^declare -f test_//p'); do
+ current=$t
+ work=$(mktemp -d "${TMPDIR:-/tmp}/prune-test.XXXXXX") || exit 2
+ "test_$t"
+ rm -f "$work"/* "$work"/.[!.]*
+ rmdir "$work"
+done
+exit "$failed"
+''',
+
+}
+
+
+def _patched(path, *pairs):
+ """{path: PROJECT[path] with each (old, new) pair replaced once}; fails loudly if an `old`
+ is not there exactly once."""
+ src = PROJECT[path]
+ for old, new in pairs:
+ assert src.count(old) == 1, (path, old)
+ src = src.replace(old, new)
+ return {path: src}
+
+
+HIDDEN = ("tests/run.sh",)
+FIX = _patched("lib/dates.sh", ('[ "$(is_leap "$y")" ]', '[ "$(is_leap "$y")" -eq 1 ]'))
+TEST_CMD = ["bash", "tests/run.sh"]
+PASS_RE = r"^PASS (\S+)$"
+TESTS = tuple(re.findall(r"^test_(\w+)\(\) \{", PROJECT["tests/run.sh"], re.M))
+WRONG = [
+ # one more day of slack at the symptom site
+ _patched("lib/policy.sh", ('[ "$age" -le "$within" ]', '[ "$age" -le $((within + 1)) ]')),
+ # is_leap prints nothing for common years, so dates.sh's [ "$(is_leap ...)" ] reads it right
+ _patched("lib/calendar.sh",
+ (" echo 1\n else\n echo 0\n fi\n", " echo 1\n fi\n"),
+ (' 2) echo $((28 + $(is_leap "$1"))) ;;\n',
+ ' 2) if [ "$(is_leap "$1")" ]; then echo 29; else echo 28; fi ;;\n')),
+ # no leap-day adjustment in day_number at all
+ _patched("lib/dates.sh",
+ (' # Y\'s own February 29th, once it is behind us\n'
+ ' if [ "$m" -gt 2 ] && [ "$(is_leap "$y")" ]; then\n'
+ ' n=$((n + 1))\n'
+ ' fi\n', "")),
+]
diff --git a/bench/tasks/fix_hard/sql_backup_rpo.py b/bench/tasks/fix_hard/sql_backup_rpo.py
new file mode 100644
index 0000000..0a9fbaf
--- /dev/null
+++ b/bench/tasks/fix_hard/sql_backup_rpo.py
@@ -0,0 +1,313 @@
+"""SQL (SQLite): a backup-monitoring DB. Views fold job history into an RPO verdict per host and a
+maintenance view expands host/site windows into per-host suppression rows. v_maintenance_now
+selects w.host_id, which is NULL for every row a site window expands to, so rpo_alert's
+`NOT IN (SELECT host_id ...)` sees a NULL and the whole alert comes back empty. Patching the
+alert (NOT EXISTS, or filtering NULLs out of the subquery) un-suppresses the site's hosts; the
+fix is in the view."""
+import re
+
+ITEM_ID = "sql-backup-rpo"
+LANG = "sql"
+TOOL = "python3"
+
+PROJECT = {
+"schema.sql": '''-- Backup monitoring. All timestamps are UTC text 'YYYY-MM-DD HH:MM:SS'.
+PRAGMA foreign_keys = ON;
+
+CREATE TABLE sites (
+ id INTEGER PRIMARY KEY,
+ code TEXT NOT NULL UNIQUE,
+ name TEXT NOT NULL
+);
+
+CREATE TABLE hosts (
+ id INTEGER PRIMARY KEY,
+ hostname TEXT NOT NULL UNIQUE,
+ site_id INTEGER NOT NULL REFERENCES sites(id),
+ tier TEXT NOT NULL CHECK (tier IN ('gold', 'silver', 'bronze')),
+ retired_at TEXT -- NULL while in service; retired hosts drop out of every report
+);
+
+-- Recovery point objective per tier: the newest good backup may be at most this old.
+CREATE TABLE rpo_policy (
+ tier TEXT PRIMARY KEY,
+ max_age_hours INTEGER NOT NULL
+);
+
+-- One row per backup job as reported by the agents. 'warning' means the job completed but
+-- skipped some files (open handles); it still counts as a good backup. 'running' jobs have no
+-- finished_at yet.
+CREATE TABLE backup_jobs (
+ id INTEGER PRIMARY KEY,
+ host_id INTEGER NOT NULL REFERENCES hosts(id),
+ started_at TEXT NOT NULL,
+ finished_at TEXT,
+ status TEXT NOT NULL CHECK (status IN ('running', 'success', 'warning', 'failed')),
+ bytes_written INTEGER
+);
+
+-- Planned work during which backup alerts are suppressed. A window targets exactly one host
+-- (host_id set) or a whole site (site_id set). It is active while starts_at <= now < ends_at.
+CREATE TABLE maintenance_windows (
+ id INTEGER PRIMARY KEY,
+ host_id INTEGER REFERENCES hosts(id),
+ site_id INTEGER REFERENCES sites(id),
+ starts_at TEXT NOT NULL,
+ ends_at TEXT NOT NULL,
+ reason TEXT NOT NULL,
+ CHECK ((host_id IS NULL) <> (site_id IS NULL))
+);
+
+-- The instant every view and report is evaluated at (exactly one row). The nightly job sets it
+-- to the run time; tests pin it.
+CREATE TABLE report_clock (
+ as_of TEXT NOT NULL
+);
+''',
+
+"views/10_job_runs.sql": '''-- v_job_runs: finished jobs, one row per job, outcome folded to good (1) / bad (0).
+CREATE VIEW v_job_runs AS
+SELECT
+ j.id AS job_id,
+ j.host_id,
+ j.started_at,
+ j.finished_at,
+ j.status,
+ j.status IN ('success', 'warning') AS good,
+ COALESCE(j.bytes_written, 0) AS bytes_written
+FROM backup_jobs j
+WHERE j.finished_at IS NOT NULL;
+
+-- v_last_good: one row per in-service host with its newest good job; the job columns are NULL
+-- when the host has never had a good backup. Ties on finished_at go to the higher job id.
+CREATE VIEW v_last_good AS
+SELECT
+ h.id AS host_id,
+ r.job_id,
+ r.finished_at AS last_good_at,
+ r.bytes_written AS last_good_bytes
+FROM hosts h
+LEFT JOIN v_job_runs r
+ ON r.job_id = (
+ SELECT r2.job_id
+ FROM v_job_runs r2
+ WHERE r2.host_id = h.id AND r2.good
+ ORDER BY r2.finished_at DESC, r2.job_id DESC
+ LIMIT 1)
+WHERE h.retired_at IS NULL;
+''',
+
+"views/20_host_state.sql": '''-- v_host_state: RPO verdict per in-service host as of report_clock.as_of.
+-- never no good backup on record
+-- stale newest good backup is older than the tier's max_age_hours
+-- ok otherwise
+-- age_hours is NULL for 'never', otherwise rounded to one decimal.
+CREATE VIEW v_host_state AS
+SELECT
+ h.id AS host_id,
+ h.hostname,
+ h.site_id,
+ s.code AS site,
+ h.tier,
+ lg.last_good_at,
+ lg.last_good_bytes,
+ ROUND((julianday(c.as_of) - julianday(lg.last_good_at)) * 24, 1) AS age_hours,
+ CASE
+ WHEN lg.last_good_at IS NULL THEN 'never'
+ WHEN (julianday(c.as_of) - julianday(lg.last_good_at)) * 24 > p.max_age_hours THEN 'stale'
+ ELSE 'ok'
+ END AS state
+FROM v_last_good lg
+JOIN hosts h ON h.id = lg.host_id
+JOIN sites s ON s.id = h.site_id
+JOIN rpo_policy p ON p.tier = h.tier
+CROSS JOIN report_clock c;
+''',
+
+"views/30_maintenance_now.sql": '''-- v_maintenance_now: alert suppression in effect at report_clock.as_of.
+-- One row per (host, active window): a host window covers that host, a site window covers every
+-- in-service host at the site. Consumers match on host_id.
+CREATE VIEW v_maintenance_now AS
+SELECT
+ w.host_id AS host_id,
+ w.id AS window_id,
+ w.reason,
+ w.ends_at
+FROM maintenance_windows w
+JOIN report_clock c
+ ON w.starts_at <= c.as_of AND c.as_of < w.ends_at
+LEFT JOIN hosts h
+ ON h.site_id = w.site_id AND h.retired_at IS NULL;
+''',
+
+"queries/rpo_alert.sql": '''-- Nightly RPO alert: every in-service host whose state is not 'ok', except hosts under an active
+-- maintenance window. 'never' first, then the oldest backup first, then by hostname.
+SELECT hs.hostname, hs.site, hs.tier, hs.state, hs.age_hours
+FROM v_host_state hs
+WHERE hs.state <> 'ok'
+ AND hs.host_id NOT IN (SELECT host_id FROM v_maintenance_now)
+ORDER BY hs.state = 'never' DESC, hs.age_hours DESC, hs.hostname
+''',
+
+"queries/site_summary.sql": '''-- Weekly rollup per site. protected_gb is the sum of each host's newest good backup size.
+SELECT
+ s.code AS site,
+ COUNT(hs.host_id) AS hosts,
+ COALESCE(SUM(hs.state = 'ok'), 0) AS ok,
+ COALESCE(SUM(hs.state = 'stale'), 0) AS stale,
+ COALESCE(SUM(hs.state = 'never'), 0) AS never,
+ ROUND(COALESCE(SUM(hs.last_good_bytes), 0) / 1e9, 1) AS protected_gb
+FROM sites s
+LEFT JOIN v_host_state hs ON hs.site_id = s.id
+GROUP BY s.id
+ORDER BY s.code
+''',
+
+"queries/maintenance_board.sql": '''-- NOC board: hosts whose backup alerts are suppressed right now, with the reason and when the
+-- window closes. Soonest-closing first.
+SELECT h.hostname, m.reason, m.ends_at
+FROM v_maintenance_now m
+JOIN hosts h ON h.id = m.host_id
+ORDER BY m.ends_at, h.hostname
+''',
+
+"test_reports.py": '''import glob
+import os
+import sqlite3
+import unittest
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+
+FIXTURE = """
+INSERT INTO sites (id, code, name) VALUES
+ (1, 'HQ', 'Head office'), (2, 'BR', 'Eastside branch'), (3, 'COLO', 'Colocation rack');
+INSERT INTO rpo_policy (tier, max_age_hours) VALUES ('gold', 26), ('silver', 50), ('bronze', 170);
+INSERT INTO hosts (id, hostname, site_id, tier, retired_at) VALUES
+ (1, 'dc01', 1, 'gold', NULL),
+ (2, 'fs01', 1, 'silver', NULL),
+ (3, 'sql01', 1, 'gold', NULL),
+ (4, 'db02', 1, 'gold', NULL),
+ (5, 'app03', 1, 'bronze', NULL),
+ (6, 'br-fs01', 2, 'silver', NULL),
+ (7, 'br-pos01', 2, 'bronze', NULL),
+ (8, 'colo-web01', 3, 'silver', NULL),
+ (9, 'colo-nas01', 3, 'bronze', NULL),
+ (10, 'exch01', 1, 'gold', '2026-06-30 17:00:00');
+INSERT INTO backup_jobs (host_id, started_at, finished_at, status, bytes_written) VALUES
+ (1, '2026-10-11 01:00:00', '2026-10-11 01:40:00', 'success', 41000000000),
+ (1, '2026-10-12 01:00:00', '2026-10-12 01:30:00', 'success', 42000000000),
+ (2, '2026-10-09 22:00:00', '2026-10-09 23:00:00', 'warning', 610000000000),
+ (2, '2026-10-10 22:00:00', '2026-10-10 22:20:00', 'failed', NULL),
+ (2, '2026-10-11 22:00:00', NULL, 'running', NULL),
+ (3, '2026-10-10 21:00:00', '2026-10-10 22:00:00', 'success', 150000000000),
+ (3, '2026-10-11 21:00:00', '2026-10-11 22:00:00', 'failed', 3000000000),
+ (4, '2026-10-11 02:00:00', '2026-10-11 02:05:00', 'failed', NULL),
+ (5, '2026-10-06 02:00:00', '2026-10-06 03:00:00', 'success', 8000000000),
+ (6, '2026-10-08 01:00:00', '2026-10-08 02:00:00', 'success', 220000000000),
+ (6, '2026-10-11 01:00:00', '2026-10-11 01:10:00', 'failed', NULL),
+ (7, '2026-10-11 01:00:00', '2026-10-11 01:02:00', 'failed', NULL),
+ (8, '2026-10-11 19:00:00', '2026-10-11 20:00:00', 'success', 12000000000),
+ (9, '2026-09-30 03:00:00', '2026-09-30 04:00:00', 'success', 900000000000),
+ (10, '2026-06-29 01:00:00', '2026-06-29 02:00:00', 'success', 70000000000);
+INSERT INTO maintenance_windows (host_id, site_id, starts_at, ends_at, reason) VALUES
+ (2, NULL, '2026-10-11 18:00:00', '2026-10-13 18:00:00', 'disk replacement'),
+ (NULL, 2, '2026-10-12 00:00:00', '2026-10-12 12:00:00', 'WAN cutover'),
+ (3, NULL, '2026-10-10 00:00:00', '2026-10-11 00:00:00', 'patching'),
+ (8, NULL, '2026-10-14 00:00:00', '2026-10-14 08:00:00', 'switch firmware');
+"""
+
+
+def read(rel):
+ with open(os.path.join(HERE, rel)) as f:
+ return f.read()
+
+
+def open_db(as_of):
+ db = sqlite3.connect(":memory:")
+ db.executescript(read("schema.sql"))
+ for path in sorted(glob.glob(os.path.join(HERE, "views", "*.sql"))):
+ with open(path) as f:
+ db.executescript(f.read())
+ db.executescript(FIXTURE)
+ db.execute("INSERT INTO report_clock (as_of) VALUES (?)", (as_of,))
+ return db
+
+
+def query(db, name):
+ return db.execute(read(os.path.join("queries", name + ".sql"))).fetchall()
+
+
+NIGHTLY = "2026-10-12 06:00:00"
+TWO_DAYS_LATER = "2026-10-14 06:00:00"
+
+
+class BackupReportTest(unittest.TestCase):
+ def test_host_state_verdicts(self):
+ db = open_db(NIGHTLY)
+ got = {r[0]: (r[1], r[2]) for r in
+ db.execute("SELECT hostname, state, age_hours FROM v_host_state")}
+ self.assertEqual(got, {
+ "dc01": ("ok", 4.5), "fs01": ("stale", 55.0), "sql01": ("stale", 32.0),
+ "db02": ("never", None), "app03": ("ok", 147.0), "br-fs01": ("stale", 100.0),
+ "br-pos01": ("never", None), "colo-web01": ("ok", 10.0),
+ "colo-nas01": ("stale", 290.0)})
+
+ def test_site_summary(self):
+ db = open_db(NIGHTLY)
+ self.assertEqual(query(db, "site_summary"), [
+ ("BR", 2, 0, 1, 1, 220.0),
+ ("COLO", 2, 1, 1, 0, 912.0),
+ ("HQ", 5, 2, 2, 1, 810.0)])
+
+ def test_rpo_alert_nightly(self):
+ db = open_db(NIGHTLY)
+ self.assertEqual(query(db, "rpo_alert"), [
+ ("db02", "HQ", "gold", "never", None),
+ ("colo-nas01", "COLO", "bronze", "stale", 290.0),
+ ("sql01", "HQ", "gold", "stale", 32.0)])
+
+ def test_site_window_covers_site_hosts(self):
+ db = open_db(NIGHTLY)
+ alerted = {r[0] for r in query(db, "rpo_alert")}
+ self.assertEqual(alerted & {"br-fs01", "br-pos01"}, set())
+
+ def test_rpo_alert_after_windows_close(self):
+ db = open_db(TWO_DAYS_LATER)
+ self.assertEqual([r[0] for r in query(db, "rpo_alert")], [
+ "br-pos01", "db02", "colo-nas01", "app03", "br-fs01", "fs01", "sql01", "dc01"])
+
+ def test_maintenance_board(self):
+ db = open_db(TWO_DAYS_LATER)
+ self.assertEqual(query(db, "maintenance_board"), [
+ ("colo-web01", "switch firmware", "2026-10-14 08:00:00")])
+
+
+if __name__ == "__main__":
+ unittest.main()
+''',
+}
+
+HIDDEN = ("test_reports.py",)
+_VIEW = "views/30_maintenance_now.sql"
+_ALERT = "queries/rpo_alert.sql"
+FIX = {_VIEW: PROJECT[_VIEW]
+ .replace(" w.host_id AS host_id,", " COALESCE(w.host_id, h.id) AS host_id,")
+ .replace(" ON h.site_id = w.site_id AND h.retired_at IS NULL;",
+ " ON h.site_id = w.site_id AND h.retired_at IS NULL\n"
+ "WHERE COALESCE(w.host_id, h.id) IS NOT NULL;")}
+TEST_CMD = ["python3", "-B", "-m", "unittest", "-v"]
+PASS_RE = r"^(test_\w+) \(.*\) \.\.\. ok$"
+TESTS = tuple(re.findall(r"^ def (test_\w+)\(", PROJECT["test_reports.py"], re.M))
+WRONG = [
+ # NOT IN -> NOT EXISTS at the symptom: the NULL rows stop matching anything, so the alert
+ # comes back, but the site window no longer suppresses br-fs01 / br-pos01.
+ {_ALERT: PROJECT[_ALERT].replace(
+ " AND hs.host_id NOT IN (SELECT host_id FROM v_maintenance_now)",
+ " AND NOT EXISTS (SELECT 1 FROM v_maintenance_now m WHERE m.host_id = hs.host_id)")},
+ # Filter the NULLs out of the subquery: same effect.
+ {_ALERT: PROJECT[_ALERT].replace(
+ "(SELECT host_id FROM v_maintenance_now)",
+ "(SELECT host_id FROM v_maintenance_now WHERE host_id IS NOT NULL)")},
+ # Select the joined host instead: site windows work, host windows now yield NULL.
+ {_VIEW: PROJECT[_VIEW].replace(" w.host_id AS host_id,", " h.id AS host_id,")},
+]
diff --git a/bench/tasks/fix_hard/swift_engine_pin.py b/bench/tasks/fix_hard/swift_engine_pin.py
new file mode 100644
index 0000000..31e3d65
--- /dev/null
+++ b/bench/tasks/fix_hard/swift_engine_pin.py
@@ -0,0 +1,356 @@
+"""Swift: an engine-pin updater (Splashpad-style OTA). SemVer documents that build metadata plays no
+part in precedence or equality, implements `<` accordingly, but declares Comparable without
+writing `==`, so Swift synthesizes `==` over every stored property, `build` included. decide()
+then sees installed 1.4.0 != pinned 1.4.0+20261005 and reinstalls forever. The symptom is in
+EngineUpdater.swift; patching it to "install only when newer" breaks rollbacks, comparing only
+major/minor/patch breaks rc -> release, and stripping build metadata at parse time (SemVer or
+EnginePin) breaks the pin/About checks. The fix is an explicit `==` in SemVer.swift."""
+import re
+
+ITEM_ID = "swift-engine-pin"
+LANG = "swift"
+TOOL = "xcrun"
+MAC_ONLY = True
+
+PROJECT = {
+"Sources/SemVer.swift": r'''/// A Semantic Versioning 2.0.0 version: MAJOR.MINOR.PATCH[-PRERELEASE][+BUILD]. A leading "v" is
+/// accepted on input ("v1.4.0").
+///
+/// Precedence follows semver.org section 11:
+/// - major, minor and patch compare numerically;
+/// - a version with a prerelease ranks below the same version without one;
+/// - prerelease identifiers compare left to right: all-digit ones numerically, others in ASCII
+/// order, all-digit below the rest; if every shared identifier is equal, more identifiers
+/// rank higher.
+/// Build metadata is kept for display (About panel, logs) and has no part in precedence or
+/// equality: 1.4.0 and 1.4.0+20261005 are the same version.
+struct SemVer: Comparable, CustomStringConvertible {
+ let major: Int
+ let minor: Int
+ let patch: Int
+ let prerelease: [String]
+ let build: [String]
+
+ init(_ major: Int, _ minor: Int, _ patch: Int, prerelease: [String] = [], build: [String] = []) {
+ self.major = major
+ self.minor = minor
+ self.patch = patch
+ self.prerelease = prerelease
+ self.build = build
+ }
+
+ /// Parses "1.4.0", "v1.4.0", "1.5.0-rc.2", "1.4.0+20261005.g1a2b3c". Nil when malformed.
+ init?(_ text: String) {
+ var rest = Substring(text)
+ if rest.hasPrefix("v") { rest = rest.dropFirst() }
+ var build: [String] = []
+ if let plus = rest.firstIndex(of: "+") {
+ guard let ids = SemVer.identifiers(rest[rest.index(after: plus)...]) else { return nil }
+ build = ids
+ rest = rest[..<plus]
+ }
+ var prerelease: [String] = []
+ if let dash = rest.firstIndex(of: "-") {
+ guard let ids = SemVer.identifiers(rest[rest.index(after: dash)...]) else { return nil }
+ prerelease = ids
+ rest = rest[..<dash]
+ }
+ let core = rest.split(separator: ".", omittingEmptySubsequences: false)
+ guard core.count == 3,
+ let major = SemVer.number(core[0]),
+ let minor = SemVer.number(core[1]),
+ let patch = SemVer.number(core[2])
+ else { return nil }
+ self.init(major, minor, patch, prerelease: prerelease, build: build)
+ }
+
+ var isPrerelease: Bool { !prerelease.isEmpty }
+
+ /// The version without build metadata, e.g. "1.5.0-rc.2".
+ var versionString: String {
+ let core = "\(major).\(minor).\(patch)"
+ return prerelease.isEmpty ? core : core + "-" + prerelease.joined(separator: ".")
+ }
+
+ /// The version as published, e.g. "1.4.0+20261005".
+ var description: String {
+ build.isEmpty ? versionString : versionString + "+" + build.joined(separator: ".")
+ }
+
+ static func < (lhs: SemVer, rhs: SemVer) -> Bool {
+ if lhs.major != rhs.major { return lhs.major < rhs.major }
+ if lhs.minor != rhs.minor { return lhs.minor < rhs.minor }
+ if lhs.patch != rhs.patch { return lhs.patch < rhs.patch }
+ if lhs.prerelease.isEmpty || rhs.prerelease.isEmpty {
+ return !lhs.prerelease.isEmpty && rhs.prerelease.isEmpty
+ }
+ for (a, b) in zip(lhs.prerelease, rhs.prerelease) where a != b {
+ return identifierPrecedes(a, b)
+ }
+ return lhs.prerelease.count < rhs.prerelease.count
+ }
+
+ private static func identifierPrecedes(_ a: String, _ b: String) -> Bool {
+ switch (allDigits(a), allDigits(b)) {
+ case (true, true): return a.count != b.count ? a.count < b.count : a < b
+ case (true, false): return true
+ case (false, true): return false
+ case (false, false): return a < b
+ }
+ }
+
+ private static func allDigits<S: StringProtocol>(_ s: S) -> Bool {
+ !s.isEmpty && s.allSatisfy { $0.isASCII && $0.isNumber }
+ }
+
+ private static func number(_ text: Substring) -> Int? {
+ guard allDigits(text), text == "0" || !text.hasPrefix("0") else { return nil }
+ return Int(text)
+ }
+
+ private static func identifiers(_ text: Substring) -> [String]? {
+ let parts = text.split(separator: ".", omittingEmptySubsequences: false).map(String.init)
+ let valid = parts.allSatisfy { part in
+ !part.isEmpty && part.allSatisfy { $0.isASCII && ($0.isLetter || $0.isNumber || $0 == "-") }
+ }
+ return valid ? parts : nil
+ }
+}
+''',
+
+"Sources/EnginePin.swift": r'''import Foundation
+
+/// The engine pin the update server publishes: the one engine every client should run.
+///
+/// # comments and blank lines are ignored; unknown keys too, so older apps can read newer pins
+/// engine = 1.4.0+20261005 the exact engine to run (may be older than what is installed)
+/// min_app = 2.3.0 oldest app able to host this engine
+/// sha256 = <64 hex digits> digest of the engine archive, any case
+/// notes = https://... optional release-notes page
+struct EnginePin {
+ let engine: SemVer
+ let minimumApp: SemVer
+ let sha256: String
+ let notesURL: String?
+}
+
+enum PinError: Error, Equatable {
+ case missingKey(String)
+ case badVersion(key: String, value: String)
+ case badDigest(String)
+}
+
+extension EnginePin {
+ static func parse(_ text: String) throws -> EnginePin {
+ var fields: [String: String] = [:]
+ for raw in text.split(whereSeparator: { $0.isNewline }) {
+ let line = raw.trimmingCharacters(in: .whitespaces)
+ if line.isEmpty || line.hasPrefix("#") { continue }
+ guard let eq = line.firstIndex(of: "=") else { continue }
+ let key = line[..<eq].trimmingCharacters(in: .whitespaces)
+ fields[key] = line[line.index(after: eq)...].trimmingCharacters(in: .whitespaces)
+ }
+
+ func version(_ key: String) throws -> SemVer {
+ guard let value = fields[key] else { throw PinError.missingKey(key) }
+ guard let parsed = SemVer(value) else { throw PinError.badVersion(key: key, value: value) }
+ return parsed
+ }
+
+ guard let digest = fields["sha256"] else { throw PinError.missingKey("sha256") }
+ guard digest.count == 64, digest.allSatisfy({ $0.isHexDigit }) else {
+ throw PinError.badDigest(digest)
+ }
+ return EnginePin(engine: try version("engine"),
+ minimumApp: try version("min_app"),
+ sha256: digest.lowercased(),
+ notesURL: fields["notes"])
+ }
+}
+''',
+
+"Sources/EngineUpdater.swift": r'''/// What the engine installer should do after fetching the pin.
+enum UpdateAction: Equatable, CustomStringConvertible {
+ case upToDate
+ case install(SemVer)
+ case needsNewerApp(SemVer)
+
+ var description: String {
+ switch self {
+ case .upToDate: return "upToDate"
+ case .install(let version): return "install \(version)"
+ case .needsNewerApp(let version): return "needsNewerApp \(version)"
+ }
+ }
+}
+
+/// Decides the installer's next step for `pin`. `installed` is the version the engine binary
+/// reports via `splash --version`; nil when no engine is installed yet.
+///
+/// 1. An app older than pin.minimumApp cannot host the pinned engine: ask for an app update.
+/// 2. Otherwise the pin is authoritative. If the installed engine is not the pinned version,
+/// install the pin whether it is newer or older; an older pin is a deliberate rollback.
+func decide(installed: SemVer?, pin: EnginePin, appVersion: SemVer) -> UpdateAction {
+ if appVersion < pin.minimumApp {
+ return .needsNewerApp(pin.minimumApp)
+ }
+ if let installed = installed, installed == pin.engine {
+ return .upToDate
+ }
+ return .install(pin.engine)
+}
+''',
+
+"Sources/ReleaseNotes.swift": r'''/// One entry from the release-notes feed.
+struct ReleaseNote {
+ let version: SemVer
+ let summary: String
+}
+
+/// Notes for the update sheet when moving from `installed` to `target`: every note with
+/// installed < version <= target, oldest first. A rollback has nothing new to show.
+func notesToShow(from installed: SemVer?, to target: SemVer, feed: [ReleaseNote]) -> [ReleaseNote] {
+ feed.filter { note in
+ let newerThanInstalled = installed.map { $0 < note.version } ?? true
+ return newerThanInstalled && note.version <= target
+ }
+ .sorted { $0.version < $1.version }
+}
+''',
+
+"Sources/AboutPanel.swift": r'''/// The engine row of the About panel:
+/// "Engine 1.4.0 (build 20261005)" build metadata shown when the engine carries it
+/// "Engine 1.5.0-rc.2" no build metadata
+/// "Engine not installed"
+func aboutEngineLine(_ installed: SemVer?) -> String {
+ guard let version = installed else { return "Engine not installed" }
+ if version.build.isEmpty {
+ return "Engine \(version.versionString)"
+ }
+ return "Engine \(version.versionString) (build \(version.build.joined(separator: ".")))"
+}
+
+/// The status line under the engine row for a pending update decision.
+func updateStatusLine(_ action: UpdateAction) -> String {
+ switch action {
+ case .upToDate: return "Engine is up to date"
+ case .install(let version): return "Engine \(version.versionString) will be installed"
+ case .needsNewerApp(let version): return "Update the app to \(version.versionString) or later"
+ }
+}
+''',
+
+"Tests/main.swift": r'''import Foundation
+
+func report(_ name: String, _ ok: Bool, _ detail: @autoclosure () -> String) -> Bool {
+ print(ok ? "PASS \(name)" : "FAIL \(name): \(detail())")
+ return ok
+}
+
+func v(_ text: String) -> SemVer {
+ guard let parsed = SemVer(text) else { fatalError("unparseable version literal \(text)") }
+ return parsed
+}
+
+let pinText = """
+# engine pin, published 2026-10-05
+engine = 1.4.0+20261005
+min_app = 2.3.0
+sha256 = 3F0A9C1D5E7B2A4C6D8E0F1A3B5C7D9E1F2A4B6C8D0E2F4A6B8C0D2E4F6A8B0C
+notes = https://updates.example.net/engine/1.4.0.html
+"""
+
+guard let pin = try? EnginePin.parse(pinText) else {
+ print("FAIL parsesPin: parse threw")
+ exit(1)
+}
+
+var results: [Bool] = []
+
+results.append(report("parsesPin",
+ pin.engine.description == "1.4.0+20261005" && pin.minimumApp.description == "2.3.0"
+ && pin.sha256 == "3f0a9c1d5e7b2a4c6d8e0f1a3b5c7d9e1f2a4b6c8d0e2f4a6b8c0d2e4f6a8b0c"
+ && pin.notesURL == "https://updates.example.net/engine/1.4.0.html",
+ "engine \(pin.engine), min_app \(pin.minimumApp), sha256 \(pin.sha256)"))
+
+let shuffled = ["1.5.0", "1.5.0-rc.10", "1.4.9", "1.10.0", "1.5.0-beta", "1.5.0-rc.2",
+ "1.5.0-rc.2.1", "1.5.0-alpha", "v1.5.0-rc.3+20261001"]
+let ordered = shuffled.map(v).sorted().map { $0.description }
+results.append(report("precedenceOrder",
+ ordered == ["1.4.9", "1.5.0-alpha", "1.5.0-beta", "1.5.0-rc.2", "1.5.0-rc.2.1",
+ "1.5.0-rc.3+20261001", "1.5.0-rc.10", "1.5.0", "1.10.0"],
+ "\(ordered)"))
+
+let fresh = decide(installed: nil, pin: pin, appVersion: v("2.3.0"))
+results.append(report("freshInstall", fresh == .install(v("1.4.0+20261005")),
+ "nothing installed -> \(fresh)"))
+
+let oldApp = decide(installed: v("1.3.2"), pin: pin, appVersion: v("2.2.9"))
+results.append(report("appTooOld", oldApp == .needsNewerApp(v("2.3.0")),
+ "app 2.2.9 -> \(oldApp)"))
+
+let rollback = decide(installed: v("1.4.1"), pin: pin, appVersion: v("2.4.0"))
+results.append(report("rollbackToPin", rollback == .install(v("1.4.0+20261005")),
+ "installed 1.4.1, pin \(pin.engine) -> \(rollback)"))
+
+let candidate = decide(installed: v("1.4.0-rc.3"), pin: pin, appVersion: v("2.4.0"))
+results.append(report("releaseReplacesCandidate", candidate == .install(v("1.4.0+20261005")),
+ "installed 1.4.0-rc.3, pin \(pin.engine) -> \(candidate)"))
+
+let current = decide(installed: v("1.4.0"), pin: pin, appVersion: v("2.4.0"))
+results.append(report("matchingEngineIsUpToDate", current == .upToDate,
+ "installed 1.4.0, pin \(pin.engine) -> \(current)"))
+
+let feed = ["1.3.9", "1.4.0", "1.4.1", "1.5.0-rc.10", "1.5.0", "1.5.0-rc.1", "1.5.0-rc.2",
+ "1.5.1-beta.1"].map { ReleaseNote(version: v($0), summary: "notes for " + $0) }
+let shown = notesToShow(from: v("1.4.0+20260930"), to: v("1.5.0+20261005"), feed: feed)
+ .map { $0.version.description }
+let none = notesToShow(from: v("1.4.1"), to: pin.engine, feed: feed)
+results.append(report("releaseNotesWindow",
+ shown == ["1.4.1", "1.5.0-rc.1", "1.5.0-rc.2", "1.5.0-rc.10", "1.5.0"] && none.isEmpty,
+ "upgrade shows \(shown), rollback shows \(none.count)"))
+
+let about = [aboutEngineLine(pin.engine), aboutEngineLine(v("1.5.0-rc.2")), aboutEngineLine(nil),
+ updateStatusLine(.install(pin.engine)), updateStatusLine(.upToDate)]
+results.append(report("aboutPanelLines",
+ about == ["Engine 1.4.0 (build 20261005)", "Engine 1.5.0-rc.2", "Engine not installed",
+ "Engine 1.4.0 will be installed", "Engine is up to date"],
+ "\(about)"))
+
+let failed = results.filter { !$0 }.count
+print("\(results.count - failed) passed, \(failed) failed")
+exit(failed == 0 ? 0 : 1)
+''',
+}
+
+HIDDEN = ("Tests/main.swift",)
+_SEMVER, _UPDATER, _PIN = "Sources/SemVer.swift", "Sources/EngineUpdater.swift", "Sources/EnginePin.swift"
+FIX = {_SEMVER: PROJECT[_SEMVER].replace(
+ " static func < (lhs: SemVer, rhs: SemVer) -> Bool {\n",
+ " static func == (lhs: SemVer, rhs: SemVer) -> Bool {\n"
+ " lhs.major == rhs.major && lhs.minor == rhs.minor && lhs.patch == rhs.patch\n"
+ " && lhs.prerelease == rhs.prerelease\n"
+ " }\n\n"
+ " static func < (lhs: SemVer, rhs: SemVer) -> Bool {\n", 1)}
+TEST_CMD = ["sh", "-c", "xcrun swiftc Sources/*.swift Tests/main.swift -o testbin && ./testbin"]
+PASS_RE = r"^PASS (\S+)$"
+TESTS = tuple(re.findall(r'report\("(\w+)"', PROJECT["Tests/main.swift"]))
+WRONG = [
+ # At the symptom: only move forward. Breaks the rollback rule.
+ {_UPDATER: PROJECT[_UPDATER].replace("installed == pin.engine {", "pin.engine <= installed {")},
+ # At the symptom: compare the numeric core only. 1.4.0-rc.3 then counts as current.
+ {_UPDATER: PROJECT[_UPDATER].replace(
+ "installed == pin.engine {",
+ "installed.major == pin.engine.major && installed.minor == pin.engine.minor\n"
+ " && installed.patch == pin.engine.patch {")},
+ # Drop build metadata when parsing the pin: the pin and About panel lose the build.
+ {_PIN: PROJECT[_PIN].replace(
+ ' return EnginePin(engine: try version("engine"),',
+ ' let pinned = try version("engine")\n'
+ ' return EnginePin(engine: SemVer(pinned.major, pinned.minor, pinned.patch,\n'
+ ' prerelease: pinned.prerelease),')},
+ # Drop build metadata in SemVer's parser: same loss, everywhere.
+ {_SEMVER: PROJECT[_SEMVER].replace(
+ " self.init(major, minor, patch, prerelease: prerelease, build: build)",
+ " self.init(major, minor, patch, prerelease: prerelease)")},
+]
diff --git a/bench/tasks/fix_hard/ts_cidr_allowlist.py b/bench/tasks/fix_hard/ts_cidr_allowlist.py
new file mode 100644
index 0000000..395548a
--- /dev/null
+++ b/bench/tasks/fix_hard/ts_cidr_allowlist.py
@@ -0,0 +1,443 @@
+"""TypeScript (bun): a CIDR allowlist split across addr / cidr / rules / allowlist / report.
+rules.ts expands a FIRST-LAST range by handing parseSpan's half-open `end` (one past the last
+address) to rangeToCidrs, whose `last` is inclusive, so every range also covers the address just
+after it as an extra block. In the VPN fixture that extra block is an `allow 10.8.0.100/32` on a
+later line than the pinned `deny 10.8.0.100`, so the kiosk address flips to allow: the symptom
+reads as a tie-break problem in allowlist.ts. The tempting patches (deny wins ties in
+allowlist.ts, an exclusive `last` in cidr.ts, an inclusive span end in addr.ts) each fix that test
+but break the tie-break, rangeToCidrs or report tests."""
+import re
+
+ITEM_ID = "ts-cidr-allowlist"
+LANG = "ts"
+TOOL = "bun"
+
+PROJECT = {
+"src/addr.ts": r'''// IPv4 addresses as plain numbers (0 .. 2**32 - 1) and spans of them.
+//
+// Arithmetic here sticks to ordinary number math, never the 32-bit bitwise operators, so
+// addresses at or above 128.0.0.0 stay positive.
+
+export const ADDRESS_COUNT = 2 ** 32;
+
+export function parseIp(text: string): number {
+ const parts = text.trim().split(".");
+ if (parts.length !== 4) throw new Error(`not an IPv4 address: ${text}`);
+ let n = 0;
+ for (const p of parts) {
+ if (!/^[0-9]{1,3}$/.test(p) || Number(p) > 255) throw new Error(`not an IPv4 address: ${text}`);
+ n = n * 256 + Number(p);
+ }
+ return n;
+}
+
+export function formatIp(n: number): string {
+ const out: number[] = [];
+ for (let i = 0; i < 4; i++) {
+ out.unshift(n % 256);
+ n = Math.floor(n / 256);
+ }
+ return out.join(".");
+}
+
+/** A run of consecutive addresses, half-open like Array.slice: `start` is the first address
+ * and `end` is one past the last, so the span holds `end - start` addresses. */
+export interface Span {
+ start: number;
+ end: number;
+}
+
+/** Parses "a.b.c.d" (one address), "a.b.c.d/n" (a CIDR block; host bits must be zero) or
+ * "a.b.c.d-e.f.g.h" (both ends included, as rule files write ranges). */
+export function parseSpan(text: string): Span {
+ const t = text.trim();
+ const dash = t.indexOf("-");
+ if (dash >= 0) {
+ const first = parseIp(t.slice(0, dash));
+ const last = parseIp(t.slice(dash + 1));
+ if (last < first) throw new Error(`range ends before it starts: ${text}`);
+ return { start: first, end: last + 1 };
+ }
+ const slash = t.indexOf("/");
+ if (slash < 0) {
+ const a = parseIp(t);
+ return { start: a, end: a + 1 };
+ }
+ const base = parseIp(t.slice(0, slash));
+ const bits = t.slice(slash + 1);
+ if (!/^[0-9]{1,2}$/.test(bits) || Number(bits) > 32) throw new Error(`bad prefix length: ${text}`);
+ const size = 2 ** (32 - Number(bits));
+ if (base % size !== 0) throw new Error(`host bits set: ${text}`);
+ return { start: base, end: base + size };
+}
+
+export function spanSize(s: Span): number {
+ return s.end - s.start;
+}
+
+/** Sorts spans and joins any that overlap or touch, e.g. [10, 20) and [20, 30) -> [10, 30). */
+export function mergeSpans(spans: Span[]): Span[] {
+ const sorted = [...spans].sort((a, b) => a.start - b.start || a.end - b.end);
+ const out: Span[] = [];
+ for (const s of sorted) {
+ const last = out[out.length - 1];
+ if (last && s.start <= last.end) last.end = Math.max(last.end, s.end);
+ else out.push({ start: s.start, end: s.end });
+ }
+ return out;
+}
+''',
+
+"src/cidr.ts": r'''import { formatIp, parseIp } from "./addr";
+
+/** A CIDR block: `base` is its first address (host bits zero), `prefix` is 0..32. */
+export interface Cidr {
+ base: number;
+ prefix: number;
+}
+
+export function blockSize(prefix: number): number {
+ return 2 ** (32 - prefix);
+}
+
+/** Parses "a.b.c.d/n", or a bare "a.b.c.d" as a /32. Host bits must be zero. */
+export function parseCidr(text: string): Cidr {
+ const [ip, bits, extra] = text.trim().split("/");
+ if (extra !== undefined) throw new Error(`bad CIDR: ${text}`);
+ const base = parseIp(ip);
+ if (bits === undefined) return { base, prefix: 32 };
+ if (!/^[0-9]{1,2}$/.test(bits) || Number(bits) > 32) throw new Error(`bad prefix length: ${text}`);
+ const prefix = Number(bits);
+ if (base % blockSize(prefix) !== 0) throw new Error(`host bits set: ${text}`);
+ return { base, prefix };
+}
+
+export function formatCidr(c: Cidr): string {
+ return `${formatIp(c.base)}/${c.prefix}`;
+}
+
+export function contains(c: Cidr, addr: number): boolean {
+ return addr >= c.base && addr < c.base + blockSize(c.prefix);
+}
+
+/** The fewest CIDR blocks that together cover the addresses first..last, both ends included,
+ * in ascending order. rangeToCidrs(a, a) is the single /32 for a. */
+export function rangeToCidrs(first: number, last: number): Cidr[] {
+ const out: Cidr[] = [];
+ let cur = first;
+ while (cur <= last) {
+ let prefix = 32;
+ while (prefix > 0) {
+ const wider = blockSize(prefix - 1);
+ if (cur % wider !== 0 || cur + wider - 1 > last) break;
+ prefix--;
+ }
+ out.push({ base: cur, prefix });
+ cur += blockSize(prefix);
+ }
+ return out;
+}
+''',
+
+"src/rules.ts": r'''// Rule files: one rule per line, `allow|deny TARGET`, with `#` comments and blank lines.
+// TARGET is a CIDR block (10.8.0.0/16), a single address (a /32) or a range written
+// FIRST-LAST with both ends included (10.8.0.10-10.8.0.99).
+import { parseSpan } from "./addr";
+import { type Cidr, parseCidr, rangeToCidrs } from "./cidr";
+
+export type Action = "allow" | "deny";
+
+/** One rule line, before its target is interpreted. `line` is 1-based. */
+export interface RuleLine {
+ line: number;
+ action: Action;
+ target: string;
+}
+
+/** A compiled rule. A range line compiles to several rules that share its line number. */
+export interface Rule {
+ action: Action;
+ cidr: Cidr;
+ line: number;
+}
+
+export function tokenize(text: string): RuleLine[] {
+ const out: RuleLine[] = [];
+ text.split("\n").forEach((raw, i) => {
+ const body = raw.replace(/#.*/, "").trim();
+ if (body === "") return;
+ const words = body.split(/\s+/);
+ if (words.length !== 2 || (words[0] !== "allow" && words[0] !== "deny")) {
+ throw new Error(`line ${i + 1}: expected "allow|deny TARGET", got: ${raw.trim()}`);
+ }
+ out.push({ line: i + 1, action: words[0] as Action, target: words[1] });
+ });
+ return out;
+}
+
+/** Compiles a rule file. CIDR and single-address targets keep the prefix they were written
+ * with (precedence depends on it); a range becomes the fewest CIDR blocks that cover it. */
+export function parseRules(text: string): Rule[] {
+ const rules: Rule[] = [];
+ for (const { line, action, target } of tokenize(text)) {
+ try {
+ if (target.includes("-")) {
+ const { start, end } = parseSpan(target);
+ for (const cidr of rangeToCidrs(start, end)) rules.push({ action, cidr, line });
+ } else {
+ rules.push({ action, cidr: parseCidr(target), line });
+ }
+ } catch (e) {
+ throw new Error(`line ${line}: ${(e as Error).message}`);
+ }
+ }
+ return rules;
+}
+''',
+
+"src/allowlist.ts": r'''import { parseIp } from "./addr";
+import { contains, formatCidr } from "./cidr";
+import { type Action, type Rule, parseRules } from "./rules";
+
+/** A compiled rule file, queried per source address.
+ *
+ * Precedence: among the rules whose block contains the address, the most specific one (the
+ * longest prefix) decides; between equally specific rules the one on the later line decides,
+ * so an appended line can override an older one. An address no rule covers is denied. */
+export class Allowlist {
+ readonly rules: Rule[];
+
+ constructor(text: string) {
+ this.rules = parseRules(text);
+ }
+
+ /** The deciding rule for `ip`, or null when no rule covers it. */
+ match(ip: string | number): Rule | null {
+ const addr = typeof ip === "number" ? ip : parseIp(ip);
+ let best: Rule | null = null;
+ for (const r of this.rules) {
+ if (!contains(r.cidr, addr)) continue;
+ if (
+ best === null ||
+ r.cidr.prefix > best.cidr.prefix ||
+ (r.cidr.prefix === best.cidr.prefix && r.line > best.line)
+ ) {
+ best = r;
+ }
+ }
+ return best;
+ }
+
+ decide(ip: string | number): Action {
+ return this.match(ip)?.action ?? "deny";
+ }
+
+ /** One line for logs, e.g. "deny 172.20.4.9 (line 2: 172.20.0.0/16)". */
+ explain(ip: string): string {
+ const r = this.match(ip);
+ if (r === null) return `deny ${ip} (no rule; default)`;
+ return `${r.action} ${ip} (line ${r.line}: ${formatCidr(r.cidr)})`;
+ }
+}
+''',
+
+"src/report.ts": r'''// A summary of a rule file for change review: how many addresses each line names and how
+// many distinct addresses all allow lines (and all deny lines) cover together.
+import { type Span, mergeSpans, parseSpan, spanSize } from "./addr";
+import { type Action, tokenize } from "./rules";
+
+export interface LineSummary {
+ line: number;
+ action: Action;
+ target: string;
+ addresses: number;
+}
+
+export interface Summary {
+ lines: LineSummary[];
+ allowed: number;
+ denied: number;
+}
+
+function covered(spans: Span[]): number {
+ return mergeSpans(spans).reduce((n, s) => n + spanSize(s), 0);
+}
+
+export function summarize(text: string): Summary {
+ const lines: LineSummary[] = [];
+ const allow: Span[] = [];
+ const deny: Span[] = [];
+ for (const { line, action, target } of tokenize(text)) {
+ const span = parseSpan(target);
+ lines.push({ line, action, target, addresses: spanSize(span) });
+ (action === "allow" ? allow : deny).push(span);
+ }
+ return { lines, allowed: covered(allow), denied: covered(deny) };
+}
+
+/** e.g. "line 4 allow 90 10.8.0.10-10.8.0.99" */
+export function formatSummary(s: Summary): string {
+ const rows = s.lines.map(
+ (l) => `line ${l.line} ${l.action.padEnd(5)} ${String(l.addresses).padStart(4)} ${l.target}`,
+ );
+ rows.push(`allow lines cover ${s.allowed} addresses; deny lines cover ${s.denied}`);
+ return rows.join("\n");
+}
+''',
+
+"tests/allowlist.test.ts": r'''import { describe, expect, test } from "bun:test";
+import { Allowlist } from "../src/allowlist";
+
+const VPN = [
+ "# vpn.rules: client addresses handed out by the VPN concentrator",
+ "deny 10.8.0.0/24 # closed unless opened below",
+ "deny 10.8.0.100 # shared kiosk login",
+ "allow 10.8.0.10-10.8.0.99 # contractor pool",
+ "allow 10.8.0.101-10.8.0.120 # on-call staff",
+ "allow 10.8.0.7 # concentrator health check",
+].join("\n");
+
+describe("allowlist", () => {
+ test("the longest prefix wins whatever the line order", () => {
+ const a = new Allowlist("deny 10.66.6.0/24\nallow 10.0.0.0/8\n");
+ expect(a.decide("10.66.6.6")).toBe("deny");
+ expect(a.decide("10.1.2.3")).toBe("allow");
+ });
+
+ test("the later line wins between equally specific rules", () => {
+ const a = new Allowlist(
+ ["allow 172.16.0.0/12", "deny 172.16.5.0/24", "allow 172.16.5.0/24 # reopened after the move"].join("\n"),
+ );
+ expect(a.decide("172.16.5.9")).toBe("allow");
+ expect(a.explain("172.16.5.9")).toBe("allow 172.16.5.9 (line 3: 172.16.5.0/24)");
+ });
+
+ test("addresses no rule covers are denied", () => {
+ const a = new Allowlist(VPN);
+ expect(a.decide("8.8.8.8")).toBe("deny");
+ expect(a.explain("8.8.8.8")).toBe("deny 8.8.8.8 (no rule; default)");
+ });
+
+ test("vpn: pools admit their first and last address", () => {
+ const a = new Allowlist(VPN);
+ expect(a.decide("10.8.0.9")).toBe("deny");
+ expect(a.decide("10.8.0.10")).toBe("allow");
+ expect(a.decide("10.8.0.99")).toBe("allow");
+ expect(a.decide("10.8.0.101")).toBe("allow");
+ expect(a.decide("10.8.0.120")).toBe("allow");
+ expect(a.decide("10.8.0.7")).toBe("allow");
+ });
+
+ test("vpn: the kiosk address stays closed", () => {
+ const a = new Allowlist(VPN);
+ expect(a.decide("10.8.0.100")).toBe("deny");
+ });
+});
+''',
+
+"tests/cidr.test.ts": r'''import { describe, expect, test } from "bun:test";
+import { formatIp, parseIp } from "../src/addr";
+import { contains, formatCidr, parseCidr, rangeToCidrs } from "../src/cidr";
+
+const cover = (a: string, b: string) => rangeToCidrs(parseIp(a), parseIp(b)).map(formatCidr);
+
+describe("cidr", () => {
+ test("addresses above 128.0.0.0 stay positive", () => {
+ expect(parseIp("203.0.113.7")).toBe(3405803783);
+ expect(formatIp(parseIp("255.255.255.255"))).toBe("255.255.255.255");
+ });
+
+ test("parseCidr reads blocks and bare addresses", () => {
+ expect(parseCidr("10.8.0.0/16")).toEqual({ base: parseIp("10.8.0.0"), prefix: 16 });
+ expect(parseCidr("192.0.2.7")).toEqual({ base: parseIp("192.0.2.7"), prefix: 32 });
+ expect(() => parseCidr("10.8.0.1/16")).toThrow("host bits");
+ });
+
+ test("contains honours both block edges", () => {
+ const c = parseCidr("192.168.4.0/22");
+ expect(contains(c, parseIp("192.168.3.255"))).toBe(false);
+ expect(contains(c, parseIp("192.168.4.0"))).toBe(true);
+ expect(contains(c, parseIp("192.168.7.255"))).toBe(true);
+ expect(contains(c, parseIp("192.168.8.0"))).toBe(false);
+ });
+
+ test("rangeToCidrs covers exactly the given addresses", () => {
+ expect(cover("10.0.0.0", "10.0.0.255")).toEqual(["10.0.0.0/24"]);
+ expect(cover("192.0.2.7", "192.0.2.7")).toEqual(["192.0.2.7/32"]);
+ expect(cover("172.16.0.1", "172.16.0.6")).toEqual([
+ "172.16.0.1/32",
+ "172.16.0.2/31",
+ "172.16.0.4/31",
+ "172.16.0.6/32",
+ ]);
+ expect(cover("198.51.100.255", "198.51.101.0")).toEqual(["198.51.100.255/32", "198.51.101.0/32"]);
+ });
+});
+''',
+
+"tests/report.test.ts": r'''import { describe, expect, test } from "bun:test";
+import { mergeSpans, parseIp, parseSpan } from "../src/addr";
+import { formatSummary, summarize } from "../src/report";
+
+describe("report", () => {
+ test("spans are half-open", () => {
+ expect(parseSpan("192.168.10.0/24")).toEqual({ start: parseIp("192.168.10.0"), end: parseIp("192.168.11.0") });
+ expect(parseSpan("172.16.0.1-172.16.0.254")).toEqual({ start: parseIp("172.16.0.1"), end: parseIp("172.16.0.255") });
+ expect(parseSpan("192.0.2.7")).toEqual({ start: parseIp("192.0.2.7"), end: parseIp("192.0.2.8") });
+ });
+
+ test("mergeSpans joins overlapping and touching spans", () => {
+ expect(mergeSpans([{ start: 30, end: 40 }, { start: 10, end: 20 }, { start: 20, end: 25 }])).toEqual([
+ { start: 10, end: 25 },
+ { start: 30, end: 40 },
+ ]);
+ });
+
+ test("summarize counts each line and the distinct totals", () => {
+ const s = summarize(`
+allow 10.8.0.10-10.8.0.99 # contractor pool
+allow 10.8.0.64/26
+deny 10.8.0.200
+`);
+ expect(s.lines.map((l) => [l.line, l.addresses])).toEqual([[2, 90], [3, 64], [4, 1]]);
+ expect(s.allowed).toBe(118);
+ expect(s.denied).toBe(1);
+ expect(formatSummary(s).split("\n")[0]).toBe("line 2 allow 90 10.8.0.10-10.8.0.99");
+ });
+});
+''',
+
+}
+
+
+def _patched(path, old, new):
+ """{path: PROJECT[path] with `old` replaced once}; fails loudly if `old` is not there."""
+ src = PROJECT[path]
+ assert src.count(old) == 1, (path, old)
+ return {path: src.replace(old, new)}
+
+
+HIDDEN = ("tests/allowlist.test.ts", "tests/cidr.test.ts", "tests/report.test.ts")
+FIX = _patched("src/rules.ts", "rangeToCidrs(start, end))", "rangeToCidrs(start, end - 1))")
+TEST_CMD = ["bun", "test"] # bun hides its (pass) lines under an AI agent; tools.AGENT_ENV strips the markers
+PASS_RE = r"^\(pass\) (.+?)(?: \[[^\]]*\])?$"
+TESTS = tuple(re.search(r'^describe\("([^"]+)"', PROJECT[h], re.M).group(1) + " > " + name
+ for h in HIDDEN for name in re.findall(r'^ test\("([^"]+)"', PROJECT[h], re.M))
+WRONG = [
+ # deny wins ties at the symptom site
+ _patched("src/allowlist.ts",
+ "(r.cidr.prefix === best.cidr.prefix && r.line > best.line)",
+ "(r.cidr.prefix === best.cidr.prefix && r.action === \"deny\")"),
+ # rangeToCidrs takes an exclusive end, matching what rules.ts passes
+ _patched("src/cidr.ts",
+ " while (cur <= last) {\n let prefix = 32;\n while (prefix > 0) {\n"
+ " const wider = blockSize(prefix - 1);\n"
+ " if (cur % wider !== 0 || cur + wider - 1 > last) break;\n",
+ " while (cur < last) {\n let prefix = 32;\n while (prefix > 0) {\n"
+ " const wider = blockSize(prefix - 1);\n"
+ " if (cur % wider !== 0 || cur + wider > last) break;\n"),
+ # ranges parse to an inclusive end
+ _patched("src/addr.ts",
+ " return { start: first, end: last + 1 };\n",
+ " return { start: first, end: last };\n"),
+]
diff --git a/bench/tasks/loop_battery.py b/bench/tasks/loop_battery.py
index 030482a..2d3ec20 100644
--- a/bench/tasks/loop_battery.py
+++ b/bench/tasks/loop_battery.py
@@ -1,31 +1,52 @@
-"""Loop-provoking battery. Prompts engineered to induce over-rethinking / runaway CoT.
-Runs each probe RUNS times at temp 0.6 (the model's recommended sampler for reasoning).
-Captures: finish_reason (length == ran to cap == runaway), completion_tokens, wall time,
-thinking length, re-derivation markers, and an n-gram repetition score (a high max
-repeated-10gram count == a hard loop, the model literally repeating itself).
-
-Thinking is parsed from `reasoning_content` (vLLM / LM Studio separate channel) or
-falling back to inline <think>...</think> tags in the content. Models that expose no
-thinking channel at all have their answer text scanned instead and flagged so a silent
-0-marker report isn't mistaken for clean reasoning.
-
-Usage (via the bench.py CLI):
- python bench.py loop-battery run
-
-Env (via .env): ENDPOINT, MODEL, API_KEY, MAX_TOKENS, TEMPERATURE.
- RUNS number of runs per probe (default 2)
- NUM_PREDICT per-probe generation cap (default 16000; falls back to MAX_TOKENS)
+"""Loop-provoking battery: prompts engineered to induce over-rethinking / runaway CoT.
+
+Five probes, `--samples` draws each (default 8). Everything goes through the lane/client
+(OpenAI-compatible only); the lane owns the sampler and the generation cap. The instrument
+defaults below (temperature 0.6, max_tokens 16000) are only used when a lane does not set them.
+
+Per sample (one row, category "loop/<probe>"):
+ cap_hit finish_reason == "length" (ran to the cap == runaway)
+ max_ngram_rep max repeat count of any 10-word run over reasoning+content (>1 means that exact
+ run recurred; high == a hard loop). Also *_reasoning / *_content variants.
+ markers total + per-marker counts of re-derivation phrases ("wait", "hmm", ...) in the
+ reasoning (or in the content, flagged scanned_content, when the lane exposes no
+ reasoning channel at all)
+ answer_ok acceptable-answer check (below)
+ correct not cap_hit and answer_ok
+
+Acceptable-answer rules. Several probes are false-premise or underdetermined on purpose,
+so for them a *good* answer pushes back; a confident fabricated answer is wrong. Rules are
+deliberately loose keyword checks - they are a floor for "did not just comply", not a grader:
+ self-ref-wordcount satisfiable. OK iff a number stated in the answer (digits or spelled
+ out, 0-99) equals the answer's own word count (whitespace-split or
+ alphanumeric-word count).
+ underdetermined-ages classic product-36 puzzle: the sum is never given. OK iff the answer
+ gives ages 2, 2, 9 (the puzzle's solution, sum 13) OR says the sum / needed
+ information is missing.
+ prove-false false statement (9 = 3*3). OK iff the answer says it is false / gives a
+ counterexample (an odd composite such as 9, 15, 21, 25, 27).
+ conflicting-opt false premise (no language is optimal on every axis). OK iff the answer
+ says no single language / it depends / trade-offs.
+ ambiguous-pronoun-math the first two sentences give apple = orange = 1.40; the last sentence
+ contradicts them (both paid the same). OK iff the answer flags the
+ contradiction/ambiguity OR gives 1.40 for the fruit.
+
+--items takes probe names (with or without the "loop-" item-id prefix).
"""
-import os
+import argparse
+import hashlib
+import json
import re
import sys
from collections import Counter
-from bench.core import client
-from bench.core.reporting import RESULTS_DIR, safe_label
+from bench.core import client, results, stats
-RUNS = int(os.environ.get("RUNS", "2"))
-NUM_PREDICT = int(os.environ.get("NUM_PREDICT", os.environ.get("MAX_TOKENS", "16000")))
+INSTRUMENT = "loop-battery"
+DEFAULT_MAX_TOKENS = 16000
+DEFAULT_TEMPERATURE = 0.6
+DEFAULT_SAMPLES = 8
+NGRAM = 10
PROBES = [
("self-ref-wordcount",
@@ -53,76 +74,166 @@ MARKERS = ["wait", "let me reconsider", "hold on", "actually,", "let me recomput
"scratch that", "on second thought", "let me restart", "let me try again"]
-def split_think(msg, content):
- rc = msg.get("reasoning_content")
- if rc:
- return rc, content
- m = re.search(r"<think>(.*?)</think>(.*)$", content, re.DOTALL)
- if m:
- return m.group(1).strip(), m.group(2).strip()
- return "", content
-
-
-def rep_score(text):
+# ---------------------------------------------------------------- scoring
+def rep_score(text, n=NGRAM):
+ """(max repeat count of any n-word run, unique-word ratio). (0, 1.0) for very short text."""
w = text.split()
- if len(w) < 20:
+ if len(w) < 2 * n:
return 0, 1.0
- grams = Counter(tuple(w[i:i + 10]) for i in range(len(w) - 9))
- maxrep = max(grams.values())
- uniq_ratio = len(set(w)) / len(w)
- return maxrep, round(uniq_ratio, 3)
-
-
-def run():
- model = client.MODEL
- print("### LOOP BATTERY vs %s (temp0.6, num_predict=%d, %d runs each) ###" %
- (model, NUM_PREDICT, RUNS), flush=True)
- safe = safe_label(model)
- for label, prompt in PROBES:
- for n in range(1, RUNS + 1):
- msgs = [{"role": "user", "content": prompt}]
- try:
- resp, dt = client.call_model(
- msgs, max_tokens=NUM_PREDICT, temperature=0.6)
- except Exception as e:
- print("[%s #%d] ERROR %r" % (label, n, e), flush=True)
- continue
- ch = resp.get("choices", [{}])[0]
- msg = ch.get("message", {}) or {}
- content_str = msg.get("content") or ""
- think, ans = split_think(msg, content_str)
- scan = think if think else ans
- fallback = "" if think else " [no-think-channel, scanned=answer]"
- done = ch.get("finish_reason")
- u = client.usage(resp)
- ct = u["completion_tokens"]
- low = scan.lower()
- mk = sum(low.count(m) for m in MARKERS)
- maxrep, uniq = rep_score(scan)
- runaway = "RUNAWAY(cap)" if done == "length" else "ok"
- print("[%-22s #%d] %-12s done=%-7s gen_tok=%-6s wall=%5.1fs "
- "think_words=%-5d markers=%-3d max10gram=%d uniq=%.2f%s" %
- (label, n, runaway, done, ct, dt, len(scan.split()),
- mk, maxrep, uniq, fallback), flush=True)
- path = os.path.join(
- RESULTS_DIR, "loop_%s_%s_%d.txt" % (safe, label, n))
- with open(path, "w") as f:
- f.write("MODEL:%s\nPROMPT:\n%s\n\n=== THINKING ===\n%s\n\n"
- "=== ANSWER ===\n%s\n" %
- (model, prompt, think, ans))
- print("DONE.", flush=True)
-
-
-
-
-def main():
- mode = sys.argv[1] if len(sys.argv) > 1 else "run"
- if mode == "run":
- run()
- else:
- print(f"usage: python bench.py loop-battery [run]")
- sys.exit(1)
+ grams = Counter(tuple(w[i:i + n]) for i in range(len(w) - n + 1))
+ return max(grams.values()), round(len(set(w)) / len(w), 3)
+
+
+def marker_counts(text):
+ low = text.lower()
+ per = {m: low.count(m) for m in MARKERS if m in low}
+ return sum(per.values()), per
+
+
+_ONES = {w: i for i, w in enumerate(
+ "zero one two three four five six seven eight nine ten eleven twelve thirteen fourteen "
+ "fifteen sixteen seventeen eighteen nineteen".split())}
+_TENS = {w: 10 * (i + 2) for i, w in enumerate(
+ "twenty thirty forty fifty sixty seventy eighty ninety".split())}
+
+
+def stated_numbers(text):
+ """Integers written as digits or as English words 0-99 (e.g. 'twenty-one')."""
+ toks = re.findall(r"\d+|[a-z]+", text.lower())
+ out, i = [], 0
+ while i < len(toks):
+ t = toks[i]
+ if t.isdigit():
+ out.append(int(t))
+ elif t in _TENS:
+ v = _TENS[t]
+ if i + 1 < len(toks) and toks[i + 1] in _ONES and 1 <= _ONES[toks[i + 1]] <= 9:
+ v += _ONES[toks[i + 1]]
+ i += 1
+ out.append(v)
+ elif t in _ONES:
+ out.append(_ONES[t])
+ i += 1
+ return out
+
+
+_WORD_RE = re.compile(r"[A-Za-z0-9]+(?:['’-][A-Za-z0-9]+)*")
+
+
+def _ok_wordcount(content):
+ counts = {len(content.split()), len(_WORD_RE.findall(content))}
+ return bool(counts & set(stated_numbers(content)))
+
+
+def _ok_ages(content):
+ nums = stated_numbers(content)
+ if nums.count(2) >= 2 and 9 in nums:
+ return True
+ return bool(re.search(
+ r"(sum|information|detail|data)\b.{0,60}\b(not (been )?(given|provided|stated|specified)|missing|"
+ r"unspecified|unknown|isn't given|wasn't given|was not given|didn't (say|tell|give))"
+ r"|(never|not|n't)\b.{0,20}\b(tell|tell me|told|give|given|provide|provided)\b.{0,30}\bsum", content, re.I | re.S))
+
+
+def _ok_prove_false(content):
+ low = content.lower()
+ flags = re.search(r"\b(false|not true|untrue|incorrect|counter-?example|cannot be proved|can't be proved|"
+ r"cannot be proven|disprove|disproved|no such proof)\b", low)
+ composite = re.search(r"(?<![\d.])(9|15|21|25|27|33|35)(?![\d.])", content)
+ return bool(flags and composite)
+
+
+def _ok_conflicting(content):
+ return bool(re.search(
+ r"\b(no single|there is no|there's no|no one|not possible|impossible|cannot|can't|trade-?offs?|"
+ r"depends|no language (is|that|can)|doesn't exist|does not exist|no perfect|no universal|"
+ r"no silver bullet)\b", content, re.I))
+
+
+def _ok_pronoun(content):
+ flags = re.search(r"\b(contradict\w*|inconsisten\w*|ambigu\w*|unclear|doesn't make sense|"
+ r"does not make sense|impossible|conflict\w*|no solution|can't be|cannot be|"
+ r"paradox|which friend|not consistent)\b", content, re.I)
+ return bool(flags or re.search(r"(?<![\d.])1\.40?(?![\d])", content))
+
+
+CHECKERS = {
+ "self-ref-wordcount": _ok_wordcount,
+ "underdetermined-ages": _ok_ages,
+ "prove-false": _ok_prove_false,
+ "conflicting-opt": _ok_conflicting,
+ "ambiguous-pronoun-math": _ok_pronoun,
+}
+
+
+def answer_ok(probe, content):
+ return bool(CHECKERS[probe](content or ""))
+
+
+def analyze(probe, reasoning, content, finish):
+ """Pure function: the per-sample metrics. Used by run and by the tests."""
+ cap_hit = finish == "length"
+ scanned_content = not reasoning
+ scan = content if scanned_content else reasoning
+ mk, per = marker_counts(scan)
+ both = (reasoning + "\n" + content) if reasoning else content
+ rep_all, uniq = rep_score(both)
+ rep_r, _ = rep_score(reasoning)
+ rep_c, _ = rep_score(content)
+ ok = answer_ok(probe, content)
+ return {"cap_hit": cap_hit, "answer_ok": ok, "correct": (not cap_hit) and ok,
+ "max_ngram_rep": rep_all, "max_ngram_rep_reasoning": rep_r, "max_ngram_rep_content": rep_c,
+ "uniq_ratio": uniq, "markers": mk, "marker_counts": per,
+ "scanned_content": scanned_content}
+
+
+def item_set():
+ h = hashlib.sha256(json.dumps([PROBES, MARKERS], sort_keys=True).encode()).hexdigest()[:12]
+ return "loop5@" + h
+
+
+# ---------------------------------------------------------------- run
+def _attempt(store, lane, probe, k):
+ name, prompt = probe
+ item = "loop-" + name
+
+ def grade(resp):
+ reasoning, content = client.reasoning(resp), client.content(resp)
+ side = store.sidecar("%s-%d" % (item, k), {"prompt": prompt, "reasoning": reasoning,
+ "content": content})
+ return dict(analyze(name, reasoning, content, client.finish_reason(resp)), sidecar=side)
+ results.call_attempt(store, lane, item, k, "loop/" + name,
+ [{"role": "user", "content": prompt}], grade,
+ max_tokens=DEFAULT_MAX_TOKENS, temperature=DEFAULT_TEMPERATURE)
+
+
+SUMMARY = {
+ "cap_hit": lambda rs: sum(bool(r.get("cap_hit")) for r in rs),
+ "max_ngram_rep_max": lambda rs: max((r["max_ngram_rep"] for r in rs
+ if r.get("max_ngram_rep") is not None), default=None),
+ "mean_completion_tokens": lambda rs: stats.mean(r["completion_tokens"] for r in rs
+ if r.get("completion_tokens")),
+}
+
+
+def run(a):
+ ids = ",".join(i if i.startswith("loop-") else "loop-" + i for i in a.items.split(",") if i)
+ plan = lambda _args: (item_set(), [("loop-" + n, (n, p)) for n, p in PROBES]) # noqa: E731
+ _store, summary = results.run_attempts(INSTRUMENT, dict(results.run_args(a), items=ids), plan,
+ _attempt, resume=a.resume, extra=SUMMARY)
+ return 3 if summary["stopped"] else 0
+
+
+def main(argv=None):
+ ap = argparse.ArgumentParser(prog="bench.py loop-battery")
+ sub = ap.add_subparsers(dest="cmd")
+ sub.add_parser("report")
+ results.add_run_args(sub.add_parser("run"), samples=DEFAULT_SAMPLES)
+ args = ap.parse_args(sys.argv[1:] if argv is None else argv)
+ if args.cmd == "report":
+ return results.print_report(INSTRUMENT, SUMMARY)
+ sys.exit(run(args if args.cmd else ap.parse_args(["run"])))
if __name__ == "__main__":
- main()
\ No newline at end of file
+ main()
diff --git a/bench/tasks/multitask/__init__.py b/bench/tasks/multitask/__init__.py
index 9f976f4..755811c 100644
--- a/bench/tasks/multitask/__init__.py
+++ b/bench/tasks/multitask/__init__.py
@@ -1,12 +1,15 @@
"""Multitask task modules — auto-discovered by agentic_multitask.py.
Each .py file (not starting with _) exposes:
- TASK_NAME str
- PLAN str (the task plan the agent executes)
- STARTER dict (starter scaffold files)
- REFERENCE dict (reference solution — used by validate only)
- validate(d) function (materialize REFERENCE, run gates, print result)
- gates(d) function (return dict of gate_name -> bool)
- TOOLS list (optional, defaults to core tools)
- TOOL_IMPLS dict (optional, defaults to core tool impls)
-"""
\ No newline at end of file
+ TASK_NAME str stable item_id
+ CATEGORY str capability bucket: go | rust | ts
+ PLAN str the task plan the agent executes
+ STARTER dict starter scaffold files
+ REFERENCE dict reference solution (`validate` only: gates run on it after VALIDATE_PREP)
+ VALIDATE_PREP tuple optional shell commands run on REFERENCE first (e.g. "go mod tidy")
+ TOOLSET tools.Toolset tool schema + impls (per language: run_build/run_test differ)
+ GATES tuple gate names, in order
+ PORT_TOKEN str|None text in PLAN replaced by the item's free port (e.g. "8080")
+ ENV dict extra env for every tool/gate subprocess (None value = unset)
+ gates(ws, port) -> ({gate: bool}, detail) ws = tools.Workspace of the attempt
+"""
diff --git a/bench/tasks/multitask/go_htmx.py b/bench/tasks/multitask/go_htmx.py
index 2e7356f..cc5a539 100644
--- a/bench/tasks/multitask/go_htmx.py
+++ b/bench/tasks/multitask/go_htmx.py
@@ -1,18 +1,21 @@
-#!/usr/bin/env python3
-"""
-Task: go_htmx — a Go web app with HTMX partials + multi-table SQLite.
-
-Models a real-world Go web tool in miniature: single Go binary, server-rendered
-html/template + HTMX for partial updates, embedded SQLite (modernc.org/sqlite),
-a multi-table schema with a self-referential location tree (recursive CTE
-read), embedded assets via //go:embed. The "real product" = a binary that
-serves a page listing locations in a tree, lets you add a sub-location via an
-HTMX partial swap (no full page reload), and persists to SQLite.
+"""Task go_htmx: a SITU-shape Go web app with HTMX partials and a multi-table SQLite schema.
+
+Single Go binary: server-rendered html/template + HTMX partial swaps, embedded SQLite
+(modernc.org/sqlite), a self-referential location tree read via a recursive CTE, assets via
+//go:embed. Gates: build; test (`go test -v ./...` exits 0 with >= 1 passing test); serves (GET /
+has <div id="tree" and htmx); persists (the POST fragment, a later GET / AND the SQLite file at
+NOTES_DB all show the new location). The item's free port replaces "8080" in the PLAN.
"""
-import os, sys, subprocess, time, shutil, signal, socket, urllib.request, urllib.parse, json
-HERE = os.path.dirname(os.path.abspath(__file__))
+
from bench.core import tools
+CATEGORY = "go"
+GATES = ("build", "test", "serves", "persists")
+PORT_TOKEN = "8080"
+TOOLSET = tools.GO_TOOLSET
+ENV = {}
+VALIDATE_PREP = ("go mod tidy",)
+
TASK_NAME = "go_htmx"
PLAN = """\
@@ -22,10 +25,9 @@ PLAN = """\
`go build ./...` and `go test ./...` run green, and the binary starts on port
8080, serves a locations tree page at `/`, lets you add a sub-location via an
HTMX partial swap (POST returns just the updated tree HTML fragment, not a full
-page), and persists to embedded SQLite. This is a Go web app with HTMX partials
-+ multi-table SQLite: single Go binary, server-rendered html/template + HTMX,
-embedded SQLite, multi-table schema with a self-referential location tree read
-via a recursive CTE.
+page), and persists to embedded SQLite. Mirrors the SITU shape: single Go
+binary, server-rendered html/template + HTMX, embedded SQLite, multi-table
+schema with a self-referential location tree read via a recursive CTE.
## Prerequisites
Starter scaffold in the work dir:
@@ -82,7 +84,7 @@ templates + migrations via `//go:embed`.
4. `POST /` with form fields name+parent_id returns 200 with the tree fragment (contains the new location name); a subsequent `GET /` shows it in the tree; the SQLite file has the row.
## Out of scope
-Auth, sessions, CSRF, styling beyond minimal readable HTML, delete/edit, drag-drop, any JS beyond the HTMX script tag. This is the smallest real Go web app with HTMX partials + multi-table SQLite — a working location-tree one-pager with HTMX partials.
+Auth, sessions, CSRF, styling beyond minimal readable HTML, delete/edit, drag-drop, any JS beyond the HTMX script tag. This is the smallest real SITU-shape — a working location-tree one-pager with HTMX partials.
## Commit
You do not commit; the harness owns the work dir.
@@ -444,124 +446,17 @@ li.location { margin: 0.25rem 0; }
''',
}
-def _materialize(files, dest):
- shutil.rmtree(dest, ignore_errors=True)
- os.makedirs(dest, exist_ok=True)
- for path, content in files.items():
- fp = os.path.join(dest, path)
- os.makedirs(os.path.dirname(fp), exist_ok=True)
- with open(fp, "w") as f: f.write(content)
- return dest
-
-def _run(cmd, cwd, timeout=180):
- try:
- p = subprocess.run(cmd, cwd=cwd, shell=True, capture_output=True, text=True, timeout=timeout)
- except subprocess.TimeoutExpired:
- return "TIMEOUT"
- return f"exit={p.returncode}\n{(p.stdout + p.stderr).strip()}"
-
-def _free_port():
- s = socket.socket(socket.AF_INET, socket.SOCK_STREAM); s.bind(("", 0))
- p = s.getsockname()[1]; s.close(); return p
-
-def _has_real_app(work_dir):
- main_go = os.path.join(work_dir, "cmd", "server", "main.go")
- if not os.path.isfile(main_go): return False
- with open(main_go) as f:
- src = f.read()
- if "ListenAndServe" not in src and "http.Server" not in src: return False
- internal = os.path.join(work_dir, "internal")
- if not os.path.isdir(internal): return False
- pkg_dirs = [d for d in os.listdir(internal) if os.path.isdir(os.path.join(internal, d))]
- return len(pkg_dirs) >= 3
-
-def gates(work_dir):
- """Return a dict of gate_name -> bool."""
- g = {}
- if not _has_real_app(work_dir):
- return {"build": False, "test": False, "serves": False, "persists": False}
- b = _run("go build ./...", work_dir)
- g["build"] = b.startswith("exit=0")
- t = _run("go test ./...", work_dir)
- g["test"] = t.startswith("exit=0")
- # serves + persists
- binpath = os.path.abspath(os.path.join(work_dir, "server"))
- r = _run(f"go build -o {binpath} ./cmd/server", work_dir)
- if not r.startswith("exit=0") or not os.path.isfile(binpath):
- g["serves"] = False; g["persists"] = False; return g
- port = _free_port()
- dbpath = os.path.abspath(os.path.join(work_dir, f"bench_{port}.db"))
- import os as _os
- for ext in ("", "-wal", "-shm"):
- if _os.path.exists(dbpath+ext): _os.remove(dbpath+ext)
- env = dict(_os.environ, NOTES_PORT=str(port), NOTES_DB=dbpath)
- try:
- proc = subprocess.Popen([binpath], cwd=work_dir, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
- except Exception:
- g["serves"] = False; g["persists"] = False; return g
- try:
- for _ in range(40):
- try:
- with socket.create_connection(("127.0.0.1", port), 0.25): break
- except OSError: time.sleep(0.25)
- else:
- g["serves"] = False; g["persists"] = False; return g
- base = f"http://127.0.0.1:{port}"
- try:
- with urllib.request.urlopen(base+"/", timeout=20) as resp:
- if resp.status != 200: g["serves"]=False; g["persists"]=False; return g
- html = resp.read().decode(errors="replace")
- except Exception:
- g["serves"]=False; g["persists"]=False; return g
- g["serves"] = ('<div id="tree"' in html) and ('htmx' in html.lower())
- if not g["serves"]:
- g["persists"]=False; return g
- # POST a location (HTMX-style: expects 200 + fragment, not a redirect)
- data = urllib.parse.urlencode({"name":"BenchLoc","parent_id":""}).encode()
- try:
- req = urllib.request.Request(base+"/", data=data, method="POST")
- with urllib.request.urlopen(req, timeout=20) as resp:
- post_body = resp.read().decode(errors="replace")
- except Exception:
- g["persists"]=False; return g
- g["persists"] = ("BenchLoc" in post_body)
- if g["persists"] and os.path.exists(dbpath):
- try:
- import sqlite3
- conn = sqlite3.connect(dbpath)
- cur = conn.execute("SELECT count(*) FROM locations WHERE name='BenchLoc'")
- g["persists"] = cur.fetchone()[0] > 0
- conn.close()
- except Exception:
- pass
- return g
- finally:
- proc.send_signal(signal.SIGTERM)
- try: proc.wait(timeout=5)
- except subprocess.TimeoutExpired: proc.kill()
- for ext in ("", "-wal", "-shm"):
- p = dbpath+ext
- if os.path.exists(p):
- try: os.remove(p)
- except: pass
-
-def validate(work_dir):
- _materialize(REFERENCE, dest=work_dir)
- r = _run("go mod tidy", work_dir)
- print("go mod tidy:", r[:120])
- b = _run("go build ./...", work_dir)
- print(f"build: {'OK' if b.startswith('exit=0') else 'FAIL'}\n{b[-300:]}")
- t = _run("go test ./...", work_dir)
- print(f"test: {'OK' if t.startswith('exit=0') else 'FAIL'}\n{t[-300:]}")
- g = gates(work_dir)
- print(f"gates: {g}")
- ok = all(g.values())
- print(f"-> {'OK' if ok else 'BAD'}")
- return ok
-
-# Allow `python go_htmx.py` to run validate directly
-if __name__ == "__main__":
- import sys
- _work_root = os.path.join(HERE, "..", "..", "..", "work")
- wd = os.path.join(_work_root, "multitask_validate_go_htmx")
- validate(wd)
\ No newline at end of file
+
+def gates(ws, port=None):
+ """Return ({gate_name: bool}, detail)."""
+ g = {k: False for k in GATES}
+ if not tools.go_has_real_app(ws.dir):
+ return g, {"reason": "no real app present (starter stub or missing internal/ packages)"}
+ bt, d = tools.build_test_gates(ws, TOOLSET, "go test -v ./...", tools.go_tests_passed)
+ g.update(bt)
+ g["serves"], checks, probe = tools.go_web_probe(
+ ws, port, lambda html: '<div id="tree"' in html and "htmx" in html.lower(),
+ {"name": "BenchLoc", "parent_id": ""}, "locations", "name")
+ g["persists"] = bool(checks) and all(checks.values())
+ d.update(probe)
+ return g, d
diff --git a/bench/tasks/multitask/rust_cli.py b/bench/tasks/multitask/rust_cli.py
index e19457a..44f6f5a 100644
--- a/bench/tasks/multitask/rust_cli.py
+++ b/bench/tasks/multitask/rust_cli.py
@@ -1,19 +1,31 @@
-#!/usr/bin/env python3
+"""Task rust_cli: a cctv-tools-shape Rust CLI (tokio + reqwest/rustls + quick-xml) that fetches an
+XML device list behind HTTP Digest auth and prints `id|name|ip` per device.
+
+Gates: build (`cargo build`); test (`cargo test` exits 0 with >= 1 passed test, summed over every
+`test result:` line); fetches (the binary prints both expected lines AND the harness's mock served
+the XML to an authorized request). The mock verifies Digest: username/realm/nonce must match the
+challenge and the response is recomputed from admin/secret (MD5 default, also MD5-sess and
+SHA-256[-sess]; qop=auth with nc+cnonce, or RFC 2069 without qop); HA2 uses the uri the client
+sent, which must name the requested resource (the request-target, or an absolute URL with that
+path). Basic admin:secret is accepted too, because the PLAN tells the model the mock accepts
+Basic; gate_detail.auth_scheme records which scheme worked. ENV unsets CARGO_TARGET_DIR so the
+gate finds target/debug/device-list.
"""
-Task: rust_cli — a Rust CLI with reqwest + quick-xml + async.
-
-Models a Rust CLI with reqwest + quick-xml + async in miniature: a Rust CLI
-that fetches XML from an HTTP endpoint with Digest auth, parses it with
-serde/quick-xml, and prints a structured result. Async (tokio), reqwest
-(rustls), quick-xml for parsing. The "real product" = a binary that hits a
-mock HTTP server the harness spins up (serves a fixed XML doc behind Digest
-auth), fetches it, parses the device list, and prints one device per line.
-"""
-import os, sys, subprocess, time, shutil, signal, socket, urllib.request, urllib.parse, json, http.server, threading, base64
+import base64
+import hashlib
+import os
+import re
+import socket
+import threading
+import urllib.parse
from bench.core import tools
-HERE = os.path.dirname(os.path.abspath(__file__))
+CATEGORY = "rust"
+GATES = ("build", "test", "fetches")
+PORT_TOKEN = None
+TOOLSET = tools.RUST_TOOLSET
+ENV = {"CARGO_TARGET_DIR": None}
TASK_NAME = "rust_cli"
@@ -23,9 +35,9 @@ PLAN = """\
## Goal
`cargo build` and `cargo test` run green, and the resulting binary fetches an
XML device list from a URL (with HTTP Digest auth), parses it with serde +
-quick-xml, and prints one device per line as `id|name|ip`. A Rust CLI with
-reqwest + quick-xml + async: Rust + reqwest (rustls) + quick-XML + async
-(tokio) + a native binary that talks to an HTTP endpoint.
+quick-xml, and prints one device per line as `id|name|ip`. Mirrors the
+cctv-tools shape: Rust + reqwest (rustls) + quick-XML + async (tokio) + a
+native binary that talks to an HTTP endpoint.
## Prerequisites
Starter scaffold in the work dir:
@@ -83,7 +95,7 @@ default features); XML via quick-xml + serde.
3. The binary, pointed at the harness's mock HTTP server (serves the XML above behind Digest auth at a URL the harness provides), fetches it and prints `1|Camera-Front|10.0.0.50` and `2|Camera-Back|10.0.0.51` on separate lines.
## Out of scope
-Tauri (no GUI), keyring (no OS keychain), ONVIF, ISAPI-specific endpoints, batch operations, config files. This is the smallest real Rust CLI with reqwest + quick-xml + async — a working fetch+parse CLI.
+Tauri (no GUI), keyring (no OS keychain), ONVIF, ISAPI-specific endpoints, batch operations, config files. This is the smallest real cctv-tools-shape — a working fetch+parse CLI.
## Commit
You do not commit; the harness owns the work dir.
@@ -222,22 +234,6 @@ async fn main() {
''',
}
-def _materialize(files, dest):
- shutil.rmtree(dest, ignore_errors=True)
- os.makedirs(dest, exist_ok=True)
- for path, content in files.items():
- fp = os.path.join(dest, path)
- os.makedirs(os.path.dirname(fp), exist_ok=True)
- with open(fp, "w") as f: f.write(content)
- return dest
-
-def _run(cmd, cwd, timeout=300):
- try:
- p = subprocess.run(cmd, cwd=cwd, shell=True, capture_output=True, text=True, timeout=timeout)
- except subprocess.TimeoutExpired:
- return "TIMEOUT"
- return f"exit={p.returncode}\n{(p.stdout + p.stderr).strip()}"
-
def _has_real_app(work_dir):
main_rs = os.path.join(work_dir, "src", "main.rs")
if not os.path.isfile(main_rs): return False
@@ -245,8 +241,82 @@ def _has_real_app(work_dir):
src = f.read()
return "tokio" in src and "reqwest" in src and "parse_devices" in src
+
+_DIGEST_PARAM = re.compile(r'([A-Za-z0-9_-]+)\s*=\s*(?:"((?:[^"\\]|\\.)*)"|([^\s,]*))')
+_HASHES = {"MD5": hashlib.md5, "SHA-256": hashlib.sha256}
+
+
+def parse_digest(header_value):
+ """Parse `Digest k=v, k="v", ...` into a lower-cased-key dict (None if not Digest)."""
+ if not header_value or not header_value.strip().lower().startswith("digest "):
+ return None
+ rest = header_value.strip()[len("digest "):]
+ out = {}
+ for m in _DIGEST_PARAM.finditer(rest):
+ v = m.group(2) if m.group(2) is not None else m.group(3)
+ out[m.group(1).lower()] = v.replace('\\"', '"') if v is not None else ""
+ return out
+
+
+def check_authorization(method, target, header, *, user, password, realm, nonce):
+ """(ok, scheme, why) for one request's Authorization header."""
+ if not header:
+ return False, None, "no Authorization header"
+ h = header.strip()
+ if h.lower().startswith("basic "):
+ try:
+ cred = base64.b64decode(h[6:].strip()).decode("utf-8", "replace")
+ except Exception:
+ return False, "basic", "undecodable Basic credentials"
+ if cred == f"{user}:{password}":
+ return True, "basic", "basic credentials ok"
+ return False, "basic", "wrong Basic credentials"
+ p = parse_digest(h)
+ if p is None:
+ return False, "other", "unsupported auth scheme"
+ missing = [k for k in ("username", "realm", "nonce", "uri", "response") if not p.get(k)]
+ if missing:
+ return False, "digest", "Digest header missing " + ",".join(missing)
+ if p["username"] != user:
+ return False, "digest", "wrong username"
+ if p["realm"] != realm:
+ return False, "digest", "realm mismatch"
+ if p["nonce"] != nonce:
+ return False, "digest", "nonce mismatch"
+ uri = p["uri"]
+ up = urllib.parse.urlsplit(uri)
+ uri_path = (up.path or "/") + ("?" + up.query if up.query else "") if up.scheme else uri
+ if uri_path != target:
+ return False, "digest", f"uri {uri!r} does not name {target!r}"
+ alg = (p.get("algorithm") or "MD5").upper()
+ sess = alg.endswith("-SESS")
+ hfn = _HASHES.get(alg[:-5] if sess else alg)
+ if hfn is None:
+ return False, "digest", f"unsupported algorithm {alg}"
+ H = lambda s: hfn(s.encode()).hexdigest() # noqa: E731
+ ha1 = H(f"{user}:{realm}:{password}")
+ qop = p.get("qop")
+ if sess:
+ if not p.get("cnonce"):
+ return False, "digest", "-sess without cnonce"
+ ha1 = H(f"{ha1}:{nonce}:{p['cnonce']}")
+ ha2 = H(f"{method}:{uri}")
+ if qop:
+ if qop.lower() != "auth":
+ return False, "digest", f"unsupported qop {qop}"
+ if not p.get("nc") or not p.get("cnonce"):
+ return False, "digest", "qop=auth without nc/cnonce"
+ expected = H(f"{ha1}:{nonce}:{p['nc']}:{p['cnonce']}:{qop}:{ha2}")
+ else:
+ expected = H(f"{ha1}:{nonce}:{ha2}")
+ if p["response"].lower() != expected:
+ return False, "digest", "wrong Digest response hash"
+ return True, "digest", "digest response ok"
+
+
class _DigestMockServer:
- """A tiny HTTP server that serves the XML behind Digest auth."""
+ """A tiny HTTP server that serves the XML behind Digest auth (credentials verified;
+ Basic admin:secret also accepted, as the PLAN promises)."""
XML_BODY = (
'<?xml version="1.0" encoding="UTF-8"?>\n'
'<DeviceList>\n'
@@ -254,29 +324,69 @@ class _DigestMockServer:
' <Device><ID>2</ID><Name>Camera-Back</Name><IP>10.0.0.51</IP></Device>\n'
'</DeviceList>'
)
- def __init__(self):
+ REALM = "test"
+ NONCE = "abc123"
+ CHALLENGE = 'Digest realm="test", qop="auth", nonce="abc123", opaque=""'
+
+ def __init__(self, user="admin", password="secret"):
+ self.user, self.password = user, password
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.bind(("127.0.0.1", 0))
self.port = self.sock.getsockname()[1]
self.sock.listen(4)
+ self.sock.settimeout(0.2)
self.thread = threading.Thread(target=self._serve, daemon=True)
self.running = True
+ self.auth_log = []
+ self.served_xml = 0
+
def start(self): self.thread.start()
- def stop(self): self.running = False; self.sock.close()
+
+ def stop(self):
+ self.running = False
+ self.thread.join(timeout=5)
+ try: self.sock.close()
+ except OSError: pass
+
+ @staticmethod
+ def _read_head(conn):
+ data = b""
+ while b"\r\n\r\n" not in data and len(data) < 65536:
+ chunk = conn.recv(4096)
+ if not chunk:
+ break
+ data += chunk
+ return data.split(b"\r\n\r\n", 1)[0].decode("iso-8859-1")
+
def _serve(self):
while self.running:
try:
conn, _ = self.sock.accept()
+ except socket.timeout:
+ continue
except OSError:
break
try:
- data = conn.recv(4096).decode(errors="replace")
- # If no Authorization header → 401 with Digest challenge.
- if "Authorization:" not in data and "authorization:" not in data:
+ conn.settimeout(5)
+ lines = self._read_head(conn).split("\r\n")
+ parts = lines[0].split(" ") if lines else []
+ method = parts[0] if parts else ""
+ target = parts[1] if len(parts) > 1 else ""
+ headers = {}
+ for ln in lines[1:]:
+ if ":" in ln:
+ k, v = ln.split(":", 1)
+ headers[k.strip().lower()] = v.strip()
+ ok, scheme, why = check_authorization(
+ method, target, headers.get("authorization"), user=self.user,
+ password=self.password, realm=self.REALM, nonce=self.NONCE)
+ self.auth_log.append({"scheme": scheme, "ok": ok, "why": why})
+ if not ok:
resp = (
"HTTP/1.1 401 Unauthorized\r\n"
- 'WWW-Authenticate: Digest realm="test", qop="auth", nonce="abc123", opaque=""\r\n'
+ f"WWW-Authenticate: {self.CHALLENGE}\r\n"
"Content-Length: 0\r\n"
+ "Connection: close\r\n"
"\r\n"
)
conn.sendall(resp.encode())
@@ -286,58 +396,44 @@ class _DigestMockServer:
"HTTP/1.1 200 OK\r\n"
"Content-Type: application/xml\r\n"
f"Content-Length: {len(body)}\r\n"
+ "Connection: close\r\n"
"\r\n"
)
conn.sendall(resp.encode() + body)
+ self.served_xml += 1
except Exception:
pass
finally:
conn.close()
-def gates(work_dir):
- g = {}
- if not _has_real_app(work_dir):
- return {"build": False, "test": False, "fetches": False}
- b = _run("cargo build", work_dir, timeout=600)
- g["build"] = b.startswith("exit=0")
- t = _run("cargo test", work_dir, timeout=600)
- g["test"] = t.startswith("exit=0")
+
+def gates(ws, port=None):
+ """Return ({gate_name: bool}, detail)."""
+ g = {k: False for k in GATES}
+ if not _has_real_app(ws.dir):
+ return g, {"reason": "no real app present (src/main.rs lacks tokio/reqwest/parse_devices)"}
+ bt, d = tools.build_test_gates(ws, TOOLSET, "cargo test", tools.cargo_tests_passed)
+ g.update(bt)
# fetches gate: run the binary against the mock server
- binpath = os.path.join(work_dir, "target", "debug", "device-list")
+ binpath = os.path.join(ws.dir, "target", "debug", "device-list")
if not os.path.isfile(binpath):
- g["fetches"] = False; return g
+ d["fetches"] = "no target/debug/device-list"
+ return g, d
srv = _DigestMockServer(); srv.start()
try:
url = f"http://127.0.0.1:{srv.port}/"
- try:
- p = subprocess.run([binpath, "--url", url, "--user", "admin", "--pass", "secret"],
- capture_output=True, text=True, timeout=30)
- out = p.stdout.strip()
- g["fetches"] = ("1|Camera-Front|10.0.0.50" in out and
- "2|Camera-Back|10.0.0.51" in out)
- if not g["fetches"]:
- g["_fetch_detail"] = f"exit={p.returncode} stdout={out[:200]} stderr={p.stderr[:200]}"
- except Exception as e:
- g["fetches"] = False
- g["_fetch_detail"] = repr(e)
+ r = ws.run([binpath, "--url", url, "--user", srv.user, "--pass", srv.password], 30)
+ out = r.out.strip()
+ lines_ok = ("1|Camera-Front|10.0.0.50" in out and
+ "2|Camera-Back|10.0.0.51" in out)
+ g["fetches"] = lines_ok and srv.served_xml > 0
+ oks = [a for a in srv.auth_log if a["ok"]]
+ d["auth_scheme"] = oks[-1]["scheme"] if oks else None
+ d["auth_log"] = srv.auth_log[-4:]
+ if not g["fetches"]:
+ d["fetch_detail"] = (f"exit={r.rc} timeout={r.timed_out} served_xml={srv.served_xml} "
+ f"stdout={out[:200]} stderr={r.err[:200]}")
finally:
srv.stop()
- return g
-
-def validate(work_dir):
- _materialize(REFERENCE, dest=work_dir)
- print("cargo build...")
- b = _run("cargo build", work_dir, timeout=600)
- print(f"build: {'OK' if b.startswith('exit=0') else 'FAIL'}\n{b[-400:]}")
- print("cargo test...")
- t = _run("cargo test", work_dir, timeout=600)
- print(f"test: {'OK' if t.startswith('exit=0') else 'FAIL'}\n{t[-400:]}")
- g = gates(work_dir)
- print(f"gates: {g}")
- ok = all(v for k, v in g.items() if not k.startswith("_"))
- print(f"-> {'OK' if ok else 'BAD'}")
- return ok
-
-if __name__ == "__main__":
- wd = os.path.join(HERE, "..", "..", "work", "v2hard_validate_rust_cli")
- validate(wd)
\ No newline at end of file
+ return g, d
+
diff --git a/bench/tasks/multitask/ts_next.py b/bench/tasks/multitask/ts_next.py
index 97ce635..7b99746 100644
--- a/bench/tasks/multitask/ts_next.py
+++ b/bench/tasks/multitask/ts_next.py
@@ -1,21 +1,27 @@
-#!/usr/bin/env python3
+"""Task ts_next: a NexTask-shape Next.js App Router app with Prisma (SQLite), a Zod-validated API
+route and a server-rendered page.
+
+Gates: install (`npm install`); typecheck (`npx tsc --noEmit`); test (`npm test`; `vitest run`
+exits non-zero when no test runs); serves (dev server: GET / 200, POST /api/items valid -> 201,
+invalid -> 400, GET /api/items lists the new item). Every npm/npx call of the item (tools AND
+gates) runs with npm_config_before=NPM_BEFORE, so "latest" and ^ranges resolve to the same
+versions on every run. REFERENCE pins the newest release inside each major the PLAN asks for,
+not the overall latest: Prisma 7+ drops `url` in the datasource block the PLAN specifies.
"""
-Task: ts_next — a Next.js app with Prisma + API route + Zod validation.
-
-Models a Next.js app with Prisma + API route + Zod validation in miniature:
-a Next.js App Router app with a Prisma schema (2 models), an API route that
-does a CRUD operation with Zod input validation, and a server-rendered page.
-Uses SQLite as the Prisma datasource (so no external Postgres is needed —
-`@prisma/adapter-better-sqlite3` or Prisma's built-in sqlite provider). The
-"real product" = a dev server that responds on `/` (the page) and
-`/api/items` (the API route: GET lists, POST creates with Zod validation,
-invalid input returns 400).
-"""
-import os, sys, subprocess, time, shutil, signal, socket, urllib.request, urllib.parse, json
+import json
+import os
+import time
+import urllib.error
+import urllib.request
from bench.core import tools
-HERE = os.path.dirname(os.path.abspath(__file__))
+CATEGORY = "ts"
+GATES = ("install", "typecheck", "test", "serves")
+PORT_TOKEN = None
+TOOLSET = tools.TS_TOOLSET
+NPM_BEFORE = "2026-10-01T00:00:00.000Z"
+ENV = {"npm_config_before": NPM_BEFORE}
TASK_NAME = "ts_next"
@@ -27,8 +33,8 @@ PLAN = """\
passes (a Vitest unit test of the Zod schema), and the dev server responds:
`GET /` returns the HTML page, `POST /api/items` with valid JSON creates an
item (201), `POST /api/items` with invalid JSON returns 400, `GET /api/items`
-returns the list. Mirrors a Next.js app with Prisma + Zod validation: Next.js
-App Router + Prisma + Zod-validated API routes + server-rendered page.
+returns the list. Mirrors the NexTask shape: Next.js App Router + Prisma +
+Zod-validated API routes + server-rendered page.
## Prerequisites
Starter scaffold in the work dir:
@@ -67,7 +73,7 @@ DB needed).
### Constraints
- Use Prisma with the **sqlite** provider (file-based `dev.db` — no external Postgres needed for this bench).
- - Use `zod` for API input validation — this is the security boundary (the standard pattern for a Next.js app with Prisma + API route + Zod validation).
+ - Use `zod` for API input validation — this is the security boundary (same pattern as NexTask).
- The API route must return **400** with the Zod errors on invalid input, **201** + the created item on success.
- The page (`/`) must server-render the item list (read from Prisma in the server component).
- Use Next.js App Router (`src/app/` layout). NOT the pages router.
@@ -90,7 +96,7 @@ DB needed).
4. Dev server starts; `GET /` returns 200 + HTML containing an item list or a form; `POST /api/items` with valid JSON (`{"name":"Test","description":"desc"}`) returns 201; `POST /api/items` with invalid JSON (`{"name":"","description":""}`) returns 400; `GET /api/items` returns 200 + a JSON array.
## Out of scope
-Auth/Auth.js, sessions, CSRF, Postgres, Docker, Tailwind, RBAC, middleware, themes. This is the smallest real Next.js app with Prisma + API route + Zod validation — a working CRUD app with Zod-validated API + server-rendered page.
+Auth/Auth.js, sessions, CSRF, Postgres, Docker, Tailwind, RBAC, middleware, themes. This is the smallest real NexTask-shape — a working CRUD app with Zod-validated API + server-rendered page.
## Commit
You do not commit; the harness owns the work dir.
@@ -130,20 +136,20 @@ REFERENCE = {
"private": True,
"scripts": {"dev": "next dev", "build": "next build", "start": "next start", "test": "vitest run", "typecheck": "tsc --noEmit"},
"dependencies": {
- "next": "^15",
- "react": "^19",
- "react-dom": "^19",
- "@prisma/client": "^6",
- "zod": "^3",
+ "next": "15.5.27",
+ "react": "19.3.0",
+ "react-dom": "19.3.0",
+ "@prisma/client": "6.19.3",
+ "zod": "3.25.76",
},
"devDependencies": {
- "typescript": "^5",
- "@types/react": "^19",
- "@types/node": "^22",
- "prisma": "^6",
- "vitest": "^2",
- "@vitejs/plugin-react": "^4",
- "jsdom": "^25",
+ "typescript": "5.9.3",
+ "@types/react": "19.3.0",
+ "@types/node": "22.20.4",
+ "prisma": "6.19.3",
+ "vitest": "2.1.9",
+ "@vitejs/plugin-react": "4.7.0",
+ "jsdom": "25.0.1",
}
}, indent=2),
"tsconfig.json": STARTER["tsconfig.json"],
@@ -264,55 +270,48 @@ export async function POST(request: NextRequest) {
".gitignore": "node_modules\ndev.db*\n.next\n",
}
-def _materialize(files, dest):
- shutil.rmtree(dest, ignore_errors=True)
- os.makedirs(dest, exist_ok=True)
- for path, content in files.items():
- fp = os.path.join(dest, path)
- os.makedirs(os.path.dirname(fp), exist_ok=True)
- with open(fp, "w") as f: f.write(content)
- return dest
-
-def _run(cmd, cwd, timeout=600, env=None):
- try:
- p = subprocess.run(cmd, cwd=cwd, shell=True, capture_output=True, text=True, timeout=timeout, env=env)
- except subprocess.TimeoutExpired:
- return "TIMEOUT"
- return f"exit={p.returncode}\n{(p.stdout + p.stderr).strip()}"
-
-def _free_port():
- s = socket.socket(socket.AF_INET, socket.SOCK_STREAM); s.bind(("", 0))
- p = s.getsockname()[1]; s.close(); return p
-
def _has_real_app(work_dir):
if not os.path.isfile(os.path.join(work_dir, "src", "app", "page.tsx")): return False
if not os.path.isfile(os.path.join(work_dir, "src", "app", "api", "items", "route.ts")): return False
if not os.path.isfile(os.path.join(work_dir, "prisma", "schema.prisma")): return False
return True
-def gates(work_dir):
- g = {}
- if not _has_real_app(work_dir):
- return {"install": False, "typecheck": False, "test": False, "serves": False}
+
+def gates(ws, port=None):
+ """Return ({gate_name: bool}, detail)."""
+ g = {k: False for k in GATES}
+ d = {}
+ if not _has_real_app(ws.dir):
+ d["reason"] = "no real app present (page.tsx / api/items/route.ts / schema.prisma missing)"
+ return g, d
# install
- g["install"] = _run("npm install", work_dir, timeout=300).startswith("exit=0")
+ inst = ws.run("npm install", 300)
+ g["install"] = inst.ok
if not g["install"]:
- g["typecheck"] = False; g["test"] = False; g["serves"] = False; return g
+ d["install_tail"] = inst.text()[-400:]
+ return g, d
# prisma generate + db push
- _run("npx prisma generate", work_dir, timeout=120)
- _run("npx prisma db push", work_dir, timeout=120)
+ d["prisma_generate_ok"] = ws.run("npx prisma generate", 120).ok
+ d["prisma_db_push_ok"] = ws.run("npx prisma db push", 120).ok
# typecheck
- g["typecheck"] = _run("npx tsc --noEmit", work_dir, timeout=120).startswith("exit=0")
+ tc = ws.run("npx tsc --noEmit", 120)
+ g["typecheck"] = tc.ok
+ if not tc.ok:
+ d["typecheck_tail"] = tc.text()[-400:]
# test
- g["test"] = _run("npm test", work_dir, timeout=120).startswith("exit=0")
+ te = ws.run("npm test", 120)
+ g["test"] = te.ok
+ if not te.ok:
+ d["test_tail"] = te.text()[-400:]
# serves: start dev server, test the API + page
- port = _free_port()
- env = dict(os.environ, PORT=str(port))
+ if port is None or not tools.port_is_free(port):
+ port = ws.allocate_port()
+ d["port"] = port
try:
- proc = subprocess.Popen(["npx", "next", "dev", "-p", str(port)], cwd=work_dir,
- env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
- except Exception:
- g["serves"] = False; return g
+ proc = ws.popen(["npx", "next", "dev", "-p", str(port)], env={"PORT": str(port)})
+ except Exception as e:
+ d["serves"] = f"failed to start dev server: {e!r}"
+ return g, d
try:
# wait for the dev server to be ready (can take 10-30s on first compile)
for _ in range(60):
@@ -324,7 +323,8 @@ def gates(work_dir):
except Exception:
time.sleep(1)
else:
- g["serves"] = False; return g
+ d["serves"] = "dev server never returned 200 on / : " + ws.proc_output(proc, 400)
+ return g, d
page_ok = "<h1>Items</h1>" in page_html or "Items" in page_html
# POST valid
base = f"http://127.0.0.1:{port}"
@@ -335,7 +335,7 @@ def gates(work_dir):
try:
with urllib.request.urlopen(req, timeout=15) as r:
post_ok = r.status == 201
- except urllib.error.HTTPError as e:
+ except Exception:
post_ok = False
# POST invalid (should 400)
invalid_data = json.dumps({"name": "", "description": ""}).encode()
@@ -347,34 +347,20 @@ def gates(work_dir):
reject_ok = False # should have been 400
except urllib.error.HTTPError as e:
reject_ok = e.code == 400
+ except Exception:
+ reject_ok = False
# GET list
get_ok = False
try:
with urllib.request.urlopen(f"{base}/api/items", timeout=15) as r:
items = json.loads(r.read().decode())
- get_ok = isinstance(items, list) and any(i.get("name") == "BenchItem" for i in items)
+ get_ok = isinstance(items, list) and any(isinstance(i, dict) and i.get("name") == "BenchItem" for i in items)
except Exception:
pass
g["serves"] = page_ok and post_ok and reject_ok and get_ok
if not g["serves"]:
- g["_serves_detail"] = f"page={page_ok} post={post_ok} reject400={reject_ok} get={get_ok}"
+ d["serves_detail"] = f"page={page_ok} post={post_ok} reject400={reject_ok} get={get_ok}"
finally:
- proc.send_signal(signal.SIGTERM)
- try: proc.wait(timeout=10)
- except subprocess.TimeoutExpired: proc.kill()
- return g
-
-def validate(work_dir):
- _materialize(REFERENCE, dest=work_dir)
- print("npm install...")
- g = gates(work_dir)
- print(f"gates: { {k:v for k,v in g.items() if not k.startswith('_')} }")
- if not g.get("serves") and "_serves_detail" in g:
- print(f" serves detail: {g['_serves_detail']}")
- ok = all(v for k, v in g.items() if not k.startswith("_"))
- print(f"-> {'OK' if ok else 'BAD'}")
- return ok
+ ws.stop(proc, grace=10)
+ return g, d
-if __name__ == "__main__":
- wd = os.path.join(HERE, "..", "..", "..", "work", "validate_ts_next")
- validate(wd)
\ No newline at end of file
diff --git a/bench/tasks/needle.py b/bench/tasks/needle.py
index 8ee5636..2843837 100644
--- a/bench/tasks/needle.py
+++ b/bench/tasks/needle.py
@@ -1,256 +1,308 @@
-#!/usr/bin/env python3
-"""
-needle.py — repeatable needle-in-a-haystack battery for quant/lever A/Bs.
-
-Replaces the ad-hoc one-off probes (EMERALD-7742 @66.5k etc.) with a committed
-instrument. Measures retrieval quality at depth AND speed telemetry per depth,
-so a candidate quant can be compared against the incumbent on one run.
-
-Method (mirrors halogen-flash's published battery + our 2026-09-03 probes):
- - Filler text is neutral prose paragraphs (seeded, deterministic per depth).
- - A needle is a single sentence with a random code token: "The maintenance
- code for the {place} is {CODE}-{NNNN}." Spliced into filler at a target
- depth, the document continues, then asks for the code. Exact string match
- on the retrieved code. Temp 0 (greedy) — quant differences only, no
- sampling noise.
- - Speed: prefill tok/s (prompt_eval from usage), decode tok/s (eval), wall.
- - Multiple needles per depth, different insertion positions -> a distribution,
- not a single anecdote. Also: one NEAR-MISS needle per depth (a second code
- exists elsewhere in the doc; the model must return the RIGHT one) to catch
- confabulation.
-
-Usage:
- python bench.py needle run # full battery
- python bench.py needle run --depths 1000,16000 # quick subset
- python bench.py needle run --needles 3 --repeats 2 # smoke config
-
-Env (via .env / bench.core.client): ENDPOINT, MODEL, API_KEY, MAX_TOKENS,
-TEMPERATURE, HTTP_TIMEOUT. Plus:
- LABEL tag for the JSON/report (default MODEL)
- N_PREDICT max answer tokens (default 512; reasoning models think first)
-
-Output: results/needle-<label>.json + printed table. Exit 0 if every needle
-retrieved exact (any miss -> exit 1, so CI-style gating can catch it).
+"""Needle-in-a-haystack instrument, built to rank quants.
+
+ * Items are (depth, position, seed, variant); item_id = "ndl-" + sha1 of those four, so ids are
+ stable across --depths order, --positions subsets and lanes, and independent of --cpt.
+ Positions come from the fixed POSITION_GRID.
+ * Variants
+ plain one needle: "the access code for the <place> is CODE".
+ decoy an OLD code for the SAME place, stated as rotated out, plus the CURRENT code
+ elsewhere (decoy before or after the current one, order varied by seed).
+ The question asks for the current code.
+ multikey K=5 places with codes at the five grid positions; ask for the one at `position`.
+ * Scoring: take every `[A-Z]+-\\d+` token in the answer *content* (never the reasoning).
+ correct iff the gold code is present and no decoy / other-key code is present.
+ * Depth: --depths in tokens, built with a chars-per-token estimate (--cpt, default 4.4); the
+ server-reported prompt_tokens is recorded next to the estimate, so a lane with a different
+ tokenizer is visible instead of silently mislabeled.
+ * Speed: llama-server lanes send override={"cache_prompt": False} and the row records
+ cached_tokens; prefill speed is averaged over uncached rows only.
"""
+import argparse
+import hashlib
import json
-import os
import random
+import re
import sys
-import time
-from bench.core import client
-from bench.core.reporting import write_json, RESULTS_DIR
+from bench.core import client, results, stats
-LABEL = os.environ.get("LABEL", client.MODEL)
-N_PREDICT = int(os.environ.get("N_PREDICT", "512"))
+INSTRUMENT = "needle"
+GEN_VERSION = "2"
+DEFAULT_MAX_TOKENS = 8192 # instrument default; the lane's max_tokens wins
+DEFAULT_TEMPERATURE = 0.0 # likewise (lane wins)
+DEFAULT_CPT = 4.4
DEPTH_GRID = [1000, 4000, 16000, 32000, 64000]
+POSITION_GRID = [0.1, 0.3, 0.5, 0.7, 0.9]
+DEFAULT_POSITIONS = [0.1, 0.5, 0.9]
+VARIANTS = ["plain", "decoy", "multikey"]
+MULTIKEY_K = len(POSITION_GRID)
-# Deterministic per-depth filler. Neutral office-log prose, no code tokens.
-FILLER_SENTENCES = [
- "The quarterly inventory review proceeded without any material discrepancies noted by the floor staff.",
- "Facilities confirmed the heating schedule for the west corridor will revert to the winter profile next week.",
- "The procurement team circulated updated vendor terms for the spring contract cycle.",
- "Attendance at the all-hands was recorded at eighty-four percent, which is typical for this month.",
- "The backup generator passed its monthly load test and the transfer switch responded within specification.",
- "Reception logged three courier deliveries before noon and routed each to the appropriate department.",
- "The finance office reminded everyone that expense submissions close on the fifteenth of the month.",
- "A scheduled patch window for the document management system was announced for Thursday evening.",
- "The landscaping crew completed the seasonal pruning along the south entrance without incident.",
- "Warehouse slotting for the new product line was finalized and communicated to the picking team.",
- "The safety committee published minutes from its monthly walkthrough of the loading dock area.",
- "IT reported that the printer fleet firmware update completed on all but two devices.",
-]
+CODE_RE = re.compile(r"[A-Z]+-\d+")
PLACES = ["north stairwell", "server room", "loading dock", "rooftop hatch", "maintenance office",
- "freight elevator", "parking garage level two", "electrical closet", "boiler room", "west fire exit"]
+ "freight elevator", "parking garage level two", "electrical closet", "boiler room",
+ "west fire exit", "records archive", "cold storage vault"]
+CODE_WORDS = ["EMERALD", "COPPER", "GRANITE", "LANTERN", "HARBOR", "MERIDIAN", "SAPPHIRE",
+ "THISTLE", "OBSIDIAN", "FALCON", "JUNIPER", "QUARTZ", "ZEPHYR", "BASALT"]
+
+# Filler: neutral office-log prose built from templates x slots (more varied than a fixed
+# sentence pool, so the haystack is not trivially self-similar). No digit-bearing uppercase
+# tokens may appear here — the scorer would read them as codes (checked by `validate`).
+_DEPTS = ["facilities", "procurement", "the finance office", "reception", "the warehouse team",
+ "the safety committee", "IT support", "the landscaping crew", "human resources",
+ "the print room", "the mailroom", "the records team"]
+_THINGS = ["the heating schedule", "the vendor terms", "the expense policy", "the courier log",
+ "the generator test", "the patch window", "the seasonal pruning", "the slotting plan",
+ "the visitor badges", "the printer fleet", "the supply order", "the walkthrough minutes"]
+_WHEN = ["on Monday", "before noon", "late on Thursday", "earlier this week", "at the start of the month",
+ "during the afternoon shift", "ahead of the audit", "after the all-hands"]
+_NUMS = ["three", "four", "six", "eight", "eleven", "twelve", "fifteen", "twenty"]
+_TEMPLATES = [
+ "{d} confirmed {t} {w} without any material discrepancies.",
+ "{d} circulated an update on {t} {w}, and the floor staff acknowledged it.",
+ "A reminder from {d}: {t} will be reviewed {w}.",
+ "{d} logged {n} items related to {t} {w} and routed each to the right department.",
+ "Attendance at the briefing on {t} was recorded by {d} {w}, which is typical for this month.",
+ "{d} reported that {t} passed its routine check {w} and no follow-up is needed.",
+ "{d} asked everyone to read {t} {w}; {n} questions were collected for the next meeting.",
+ "Following {w}, {d} closed {n} open tickets about {t}.",
+]
-CODE_WORDS = ["EMERALD", "COPPER", "GRANITE", "LANTERN", "HARBOR", "MERIDIAN", "SAPPHIRE", "THISTLE"]
+def _rng(*parts):
+ return random.Random("|".join(str(p) for p in parts))
-def _para(rng):
- return " ".join(rng.choice(FILLER_SENTENCES) for _ in range(4)) + "\n\n"
+def item_id(depth, position, seed, variant):
+ h = hashlib.sha1(("%d|%.3f|%d|%s" % (depth, position, seed, variant)).encode()).hexdigest()
+ return "ndl-" + h[:10]
-def build_doc(target_tokens, needle, needle_at_frac, rng):
- """Filler document with `needle` spliced at needle_at_frac of target size."""
- parts, approx = [], 0
- while approx < target_tokens:
- parts.append(_para(rng))
- approx += 64 # ~64 tok/paragraph (3 sentences avg)
- doc_parts_before = []
- tok_before = int(target_tokens * needle_at_frac)
- idx = max(1, tok_before // 64)
- head = "".join(parts[:idx])
- tail = "".join(parts[idx:])
- return head + needle + "\n\n" + tail
+def depth_bucket(depth):
+ return ("%gk" % (depth / 1000.0)) if depth >= 1000 else str(depth)
-def make_needle(rng):
- place = rng.choice(PLACES)
- word = rng.choice(CODE_WORDS)
- num = rng.randint(1000, 9999)
- code = f"{word}-{num}"
- sentence = f"Maintenance note: the access code for the {place} is {code} until the end of the quarter."
- return sentence, code, place
+
+def category(depth, variant):
+ return "needle/%s/%s" % (depth_bucket(depth), variant)
+
+
+def _paragraph(rng):
+ sents = []
+ for _ in range(4):
+ sents.append(rng.choice(_TEMPLATES).format(
+ d=rng.choice(_DEPTS), t=rng.choice(_THINGS), w=rng.choice(_WHEN), n=rng.choice(_NUMS)))
+ p = " ".join(sents)
+ return p[0].upper() + p[1:] + "\n\n"
+
+
+def _cap(s):
+ return s[0].upper() + s[1:]
+
+
+def filler_paragraphs(target_chars, rng):
+ paras, total = [], 0
+ while total < target_chars:
+ p = _paragraph(rng)
+ # sentences starting with a department name in lower case get capitalised per sentence
+ p = ". ".join(_cap(x) if x else x for x in p.split(". "))
+ paras.append(p)
+ total += len(p)
+ return paras
+
+
+def _codes(rng, n):
+ words = rng.sample(CODE_WORDS, n)
+ nums = rng.sample(range(1000, 10000), n)
+ return ["%s-%d" % (w, k) for w, k in zip(words, nums)]
+
+
+def _splice(paras, inserts):
+ """inserts: list of (fraction, text). Insert by paragraph index on the ORIGINAL list."""
+ n = len(paras)
+ out = list(paras)
+ placed = sorted(((min(n, max(0, int(round(f * n)))), i, t) for i, (f, t) in enumerate(inserts)),
+ key=lambda x: (x[0], x[1]), reverse=True)
+ for idx, _i, text in placed:
+ out.insert(idx, text + "\n\n")
+ return "".join(out)
+
+
+def _current_sentence(place, code):
+ return ("Maintenance note: the access code for the %s is %s until the end of the quarter."
+ % (place, code))
+
+
+def _old_sentence(place, code):
+ return ("Maintenance note: the access code for the %s was %s until it was rotated out "
+ "last month." % (place, code))
+
+
+def _key_sentence(place, code):
+ return "Maintenance note: the access code for the %s is %s." % (place, code)
-def make_decoy(rng):
+def build_item(depth, position, seed, variant, cpt=DEFAULT_CPT):
+ """Deterministic item. Returns dict(prompt, gold, others, place, decoy_order, ...)."""
+ rng = _rng("needle", GEN_VERSION, depth, "%.3f" % position, seed, variant)
+ needle_chars = 0
place = rng.choice(PLACES)
- word = rng.choice(CODE_WORDS)
- num = rng.randint(1000, 9999)
- sentence = (f"Maintenance note: the access code for the {place} was {word}-{num} "
- f"until it was rotated last month.")
- return sentence
-
-
-def call_model(prompt, n_predict=N_PREDICT, max_retries=1):
- """Delegate to bench.core.client.call_model and extract needle-relevant telemetry.
-
- needle_bench needs the `timings` field from llama-server responses for
- prefill/decode tok/s, so we keep the local parsing of resp.get("timings")
- and resp.get("usage") on top of the shared client.
- """
- last_err = None
- for attempt in range(max_retries + 1):
- try:
- resp, wall = client.call_model(
- [{"role": "user", "content": prompt}],
- max_tokens=n_predict,
- temperature=0.0,
- http_timeout=1800,
- )
- usage = resp.get("usage", {})
- timings = resp.get("timings", {})
- ctok = usage.get("completion_tokens", 0)
- ptok = usage.get("prompt_tokens", 0)
- # llama-server reports rates top-level in `timings` (prompt_per_second /
- # predicted_per_second); OpenAI-style usage has no rate fields.
- pd = timings.get("prompt_per_second")
- ev = timings.get("predicted_per_second")
- msg = resp.get("choices", [{}])[0].get("message", {})
- content = msg.get("content") or ""
- reasoning = msg.get("reasoning_content") or ""
- return {"content": content, "reasoning": reasoning, "ptok": ptok, "ctok": ctok,
- "prefill_ps": pd, "decode_ps": ev, "wall": wall,
- "finish": resp.get("choices", [{}])[0].get("finish_reason", "")}
- except Exception as e:
- last_err = str(e)[:300]
- time.sleep(2)
- return {"error": last_err}
-
-
-def run_battery(needles, depths, repeats, decoy_probe=True):
- results = []
- for depth in depths:
- for rep in range(repeats):
- # ---- normal needles at varying positions
- for n in range(needles):
- rng = random.Random(f"{depth}-{rep}-{n}")
- sentence, code, place = make_needle(rng)
- pos_frac = (n + 0.5) / needles # spread across the doc
- doc = build_doc(depth, sentence, pos_frac, rng)
- prompt = (doc + "\n\nQUESTION: According to the maintenance notes above, "
- "what is the access code for the " + place +
- "? Answer with the code exactly as written, nothing else.")
- r = call_model(prompt)
- ok = code in r.get("content", "")
- results.append({"depth": depth, "rep": rep, "needle_idx": n,
- "code": code, "exact": ok, **{k: r.get(k) for k in
- ("ptok", "ctok", "prefill_ps", "decode_ps", "wall", "error")}})
- _print_row(results[-1])
- # ---- decoy probe: right needle + rotated-out old code in the same doc
- if decoy_probe:
- rng = random.Random(f"{depth}-{rep}-decoy")
- sentence, code, place = make_needle(rng)
- decoy_sent = make_decoy(rng)
- rng2 = random.Random(f"{depth}-{rep}-decoy-tail")
- head = build_doc(int(depth * 0.4), sentence, 0.5, rng)
- tail = build_doc(int(depth * 0.6), decoy_sent, 0.5, rng2)
- prompt = (head + tail + "\n\nQUESTION: According to the maintenance notes above, "
- "what is the CURRENT access code for the " + place +
- "? Answer with the code exactly as written, nothing else.")
- r = call_model(prompt)
- ok = code in r.get("content", "")
- results.append({"depth": depth, "rep": rep, "needle_idx": "decoy",
- "code": code, "exact": ok, **{k: r.get(k) for k in
- ("ptok", "ctok", "prefill_ps", "decode_ps", "wall", "error")}})
- _print_row(results[-1])
- return results
-
-
-def _print_row(r):
- if r.get("error"):
- print(f" depth={r['depth']:>6} rep={r['rep']} needle={r['needle_idx']!s:>5} ERROR: {r['error']}")
- return
- print(f" depth={r['depth']:>6} rep={r['rep']} needle={r['needle_idx']!s:>5} "
- f"{'PASS' if r['exact'] else 'MISS'} ptok={r.get('ptok', 0):>6} prefill={r.get('prefill_ps') or 0:>7.1f} "
- f"decode={r.get('decode_ps') or 0:>5.1f} wall={r.get('wall', 0):>6.1f}s")
-
-
-def summarize(results):
- by_depth = {}
- for r in results:
- d = by_depth.setdefault(r["depth"], {"pass": 0, "total": 0, "walls": [], "prefills": [], "decodes": []})
- d["total"] += 1
- if r.get("exact"):
- d["pass"] += 1
- if not r.get("error"):
- if r.get("wall") is not None:
- d["walls"].append(r["wall"])
- if r.get("prefill_ps"):
- d["prefills"].append(r["prefill_ps"])
- if r.get("decode_ps"):
- d["decodes"].append(r["decode_ps"])
- print("\n== Summary ==")
- print(f"{'depth':>8} {'retrieved':>10} {'wall mean':>10} {'prefill t/s':>12} {'decode t/s':>11}")
- for depth in sorted(by_depth):
- d = by_depth[depth]
- walls = d["walls"]
- prefills = [p for p in d["prefills"] if p]
- decodes = d["decodes"]
-
- def mean(xs):
- return sum(xs) / len(xs) if xs else 0.0
- print(f"{depth:>8} {d['pass']:>4}/{d['total']:<4} {mean(walls):>9.1f}s {mean(prefills):>11.1f} {mean(decodes):>10.1f}")
- total_pass = sum(1 for r in results if r.get("exact"))
- print(f"\nTOTAL: {total_pass}/{len(results)} exact")
- return total_pass == len(results)
-
-
-def run():
- args = sys.argv[1:]
- if not args or args[0] not in ("run",):
- print(__doc__)
- sys.exit(2)
- needles = 3
- repeats = 1
- depths = list(DEPTH_GRID)
- rest = args[1:]
- if "--needles" in rest:
- needles = int(rest[rest.index("--needles") + 1])
- if "--repeats" in rest:
- repeats = int(rest[rest.index("--repeats") + 1])
- if "--depths" in rest:
- depths = [int(x) for x in rest[rest.index("--depths") + 1].split(",")]
- print(f"needle_bench: model={client.MODEL} endpoint={client.ENDPOINT} label={LABEL}")
- print(f"depths={depths} needles/depth={needles} repeats={repeats} decoy=on")
- t0 = time.time()
- results = run_battery(needles, depths, repeats)
- all_ok = summarize(results)
- payload = {"label": LABEL, "model": client.MODEL, "endpoint": client.ENDPOINT,
- "ts": time.strftime("%Y-%m-%d %H:%M:%S"),
- "needles_per_depth": needles, "repeats": repeats, "depths": depths, "results": results}
- out_path = write_json(payload, LABEL, prefix="needle")
- print(f"wrote {out_path} ({time.time() - t0:.0f}s total)")
- sys.exit(0 if all_ok else 1)
-
-
-
-
-def main():
- run()
+ inserts, others, decoy_order = [], [], None
+ if variant == "plain":
+ (gold,) = _codes(rng, 1)
+ inserts.append((position, _current_sentence(place, gold)))
+ elif variant == "decoy":
+ gold, old = _codes(rng, 2)
+ decoy_order = rng.choice(["old_first", "old_last"])
+ dpos = max(0.02, position - 0.2) if decoy_order == "old_first" else min(0.98, position + 0.2)
+ inserts.append((position, _current_sentence(place, gold)))
+ inserts.append((dpos, _old_sentence(place, old)))
+ others = [old]
+ elif variant == "multikey":
+ places = rng.sample(PLACES, MULTIKEY_K)
+ codes = _codes(rng, MULTIKEY_K)
+ # the asked key sits at `position`; the other four fill the remaining grid slots
+ slots = list(POSITION_GRID)
+ if position not in slots:
+ slots = sorted(set(slots[:-1] + [position]))[:MULTIKEY_K]
+ order = sorted(range(MULTIKEY_K), key=lambda i: slots[i])
+ gold_slot = slots.index(position)
+ place, gold = places[gold_slot], codes[gold_slot]
+ for i in order:
+ inserts.append((slots[i], _key_sentence(places[i], codes[i])))
+ others = [c for i, c in enumerate(codes) if i != gold_slot]
+ else:
+ raise ValueError("unknown variant %r" % variant)
+ needle_chars = sum(len(t) + 2 for _f, t in inserts)
+ question = ("QUESTION: According to the maintenance notes above, what is the %saccess code for the %s? "
+ "Answer with the code exactly as written, nothing else."
+ % ("CURRENT " if variant == "decoy" else "", place))
+ target_chars = max(200, int(depth * cpt) - needle_chars - len(question) - 8)
+ paras = filler_paragraphs(target_chars, rng)
+ doc = _splice(paras, inserts)
+ prompt = doc + "\n" + question
+ return {"item_id": item_id(depth, position, seed, variant), "depth": depth,
+ "position": position, "seed": seed, "variant": variant, "place": place,
+ "gold": gold, "others": others, "decoy_order": decoy_order,
+ "prompt": prompt, "est_tokens": int(len(prompt) / cpt)}
+
+
+def score_answer(content, gold, others):
+ toks = CODE_RE.findall(content or "")
+ has_gold = gold in toks
+ bad = sorted({t for t in toks if t in set(others)})
+ return {"correct": bool(has_gold and not bad), "has_gold": has_gold,
+ "answer_tokens": toks[:8], "wrong_codes": bad}
+
+
+def item_set(cpt=DEFAULT_CPT):
+ defs = {"v": GEN_VERSION, "cpt": cpt, "templates": _TEMPLATES, "depts": _DEPTS, "things": _THINGS,
+ "when": _WHEN, "nums": _NUMS, "places": PLACES, "words": CODE_WORDS,
+ "positions": POSITION_GRID, "variants": VARIANTS}
+ return "needle@" + hashlib.sha256(json.dumps(defs, sort_keys=True).encode()).hexdigest()[:12]
+
+
+def grid(depths, positions, variants, seeds):
+ return [(d, p, s, v) for d in depths for v in variants for p in positions for s in range(seeds)]
+
+
+# ---------------------------------------------------------------- run
+def _attempt(store, lane, key, k):
+ it = build_item(*key, cpt=store.run["args"]["cpt"])
+ override = {"cache_prompt": False} if lane.snapshot_kind == "llama-server" else None
+
+ def grade(resp):
+ content, u = client.content(resp), client.usage(resp)
+ sc = score_answer(content, it["gold"], it["others"])
+ pt = u["prompt_tokens"]
+ return {"correct": sc["correct"], "answer_tokens": sc["answer_tokens"],
+ "wrong_codes": sc["wrong_codes"], "has_gold": sc["has_gold"],
+ "content_head": content[:200],
+ "chars_per_token": round(len(it["prompt"]) / pt, 3) if pt else None,
+ "cached_prefill": bool(u["cached_tokens"])}
+ fields = {"depth": it["depth"], "position": it["position"], "seed": it["seed"],
+ "variant": it["variant"], "gold": it["gold"], "est_tokens": it["est_tokens"],
+ "decoy_order": it["decoy_order"], "cache_prompt_off": bool(override)}
+ results.call_attempt(store, lane, it["item_id"], k, category(it["depth"], it["variant"]),
+ [{"role": "user", "content": it["prompt"]}], grade, fields,
+ max_tokens=DEFAULT_MAX_TOKENS, temperature=DEFAULT_TEMPERATURE,
+ override=override)
+
+
+def _uncached(rows):
+ return [r["prefill_ps"] for r in rows if r.get("prefill_ps") and not r.get("cached_prefill")]
+
+
+SUMMARY = {"mean_prompt_tokens": lambda rs: stats.mean(r["prompt_tokens"] for r in rs
+ if r.get("prompt_tokens")),
+ "mean_prefill_ps_uncached": lambda rs: stats.mean(_uncached(rs)),
+ "n_uncached_speed_rows": lambda rs: len(_uncached(rs))}
+
+
+def validate(cpt=DEFAULT_CPT):
+ ok = True
+ for d, p, s, v in grid([1000, 4000], POSITION_GRID, VARIANTS, 2):
+ a, b = build_item(d, p, s, v, cpt), build_item(d, p, s, v, cpt)
+ problems = []
+ if a != b:
+ problems.append("not deterministic")
+ codes = CODE_RE.findall(a["prompt"])
+ expect = 1 + len(a["others"])
+ if sorted(codes) != sorted([a["gold"]] + a["others"]) or len(codes) != expect:
+ problems.append("stray or missing codes %s" % codes)
+ if a["prompt"].count(a["gold"]) != 1:
+ problems.append("gold not unique")
+ if v == "decoy" and not all(a["place"] in x for x in re.findall(r"[^.\n]*rotated out[^.\n]*", a["prompt"])):
+ problems.append("decoy not about the same place")
+ if problems:
+ ok = False
+ print("[BAD] %s %s: %s" % (a["item_id"], (d, p, s, v), "; ".join(problems)))
+ ids = {item_id(*k) for k in grid(DEPTH_GRID, POSITION_GRID, VARIANTS, 3)}
+ if len(ids) != len(DEPTH_GRID) * len(POSITION_GRID) * len(VARIANTS) * 3:
+ ok = False
+ print("[BAD] item id collision")
+ print("item_set %s: %s" % (item_set(cpt), "OK" if ok else "FAILED"))
+ return ok
+
+
+def run(a):
+ args = results.run_args(a, depths=[int(x) for x in a.depths.split(",")],
+ positions=[float(x) for x in a.positions.split(",")],
+ variants=a.variants.split(","), seeds=a.seeds, cpt=a.cpt)
+ if not (set(args["positions"]) <= set(POSITION_GRID) and set(args["variants"]) <= set(VARIANTS)):
+ print("ERROR: --positions must come from %s and --variants from %s."
+ % (POSITION_GRID, VARIANTS))
+ return 2
+
+ def plan(g):
+ keys = grid(g["depths"], g["positions"], g["variants"], g["seeds"])
+ return item_set(g["cpt"]), [(item_id(*key), key) for key in keys]
+ _store, summary = results.run_attempts(INSTRUMENT, args, plan, _attempt, resume=a.resume,
+ extra=SUMMARY)
+ return 3 if summary["stopped"] else 0
+
+
+def main(argv=None):
+ ap = argparse.ArgumentParser(prog="bench.py needle")
+ sub = ap.add_subparsers(dest="cmd")
+ v = sub.add_parser("validate")
+ v.add_argument("--cpt", type=float, default=DEFAULT_CPT)
+ sub.add_parser("report")
+ r = sub.add_parser("run")
+ r.add_argument("--depths", default=",".join(str(d) for d in DEPTH_GRID))
+ r.add_argument("--positions", default=",".join(str(p) for p in DEFAULT_POSITIONS))
+ r.add_argument("--variants", default=",".join(VARIANTS))
+ r.add_argument("--seeds", type=int, default=1)
+ r.add_argument("--cpt", type=float, default=DEFAULT_CPT)
+ results.add_run_args(r)
+ args = ap.parse_args(sys.argv[1:] if argv is None else argv)
+ if args.cmd == "run":
+ sys.exit(run(args))
+ elif args.cmd == "report":
+ results.print_report(INSTRUMENT, SUMMARY)
+ else:
+ sys.exit(0 if validate(getattr(args, "cpt", DEFAULT_CPT)) else 1)
if __name__ == "__main__":
- main()
\ No newline at end of file
+ main()
diff --git a/bench/tasks/no_think.py b/bench/tasks/no_think.py
deleted file mode 100644
index 444ef73..0000000
--- a/bench/tasks/no_think.py
+++ /dev/null
@@ -1,87 +0,0 @@
-"""No-think latency instrument — measures the latency win of suppressing reasoning.
-
-Runs each probe in THINK vs NO_THINK mode against the endpoint and compares
-wall time, completion tokens, and thinking length. The NO_THINK mode uses
-the `chat_template_kwargs.enable_thinking` field (for backends that support
-it) and/or the empty-think assistant prefill trick.
-
-Usage (via the bench.py CLI):
- python bench.py no-think run
-
-Env (via .env): ENDPOINT, MODEL, API_KEY.
-"""
-import json
-import os
-import re
-import sys
-import time
-
-from bench.core import client
-
-PROBES = [
- ("triage-classify",
- "You are a security triage assistant. Classify this finding as one of "
- "{FALSE_POSITIVE, LOW, MEDIUM, HIGH, CRITICAL} and give a one-sentence reason. "
- "Finding: CVE in a dev-only test dependency (pytest plugin) not shipped in the "
- "production image; CVSS 9.8 RCE. Answer with 'SEVERITY: <x>' then the reason."),
- ("mail-triage",
- "Extract sender, intent, urgency (low/med/high) from this email as strict JSON with "
- "keys sender,intent,urgency and nothing else: 'From: billing@acme.com — Subject: "
- "Invoice #4471 overdue, service suspension in 48h.'"),
- ("classify-short",
- "Classify the sentiment of this ticket as POSITIVE/NEUTRAL/NEGATIVE and nothing else: "
- "'Your update broke our export and support hasn't replied in three days.'"),
- ("arithmetic",
- "A backup runs every 15 minutes. How many backups happen in one day? Give just the number."),
-]
-
-
-def _split_think(msg, content):
- rc = msg.get("reasoning_content")
- if rc:
- return rc, content
- m = re.search(chr(60) + "think" + chr(62) + "(.*?)" + chr(60) + "/think" + chr(62) + "(.*)$", content, re.DOTALL)
- if m:
- return m.group(1).strip(), m.group(2).strip()
- return "", content
-
-
-def run():
- print("### no-think latency bench vs %s ###" % client.MODEL, flush=True)
- print("%-16s %-9s %8s %8s %8s %s" % ("probe", "mode", "wall_s", "comp_tok", "think_w", "answer"), flush=True)
- for name, base in PROBES:
- for mode in ("think", "no_think"):
- no_think = (mode == "no_think")
- msgs = [{"role": "user", "content": base}]
- if no_think and not client.NOTHINK:
- msgs = msgs + [{"role": "assistant", "content": chr(60) + "think" + chr(62) + chr(60) + "/think" + chr(62)}]
- try:
- resp, dt = client.call_model(
- msgs, max_tokens=4000,
- temperature=0.3,
- )
- ch = resp["choices"][0]
- msg = ch.get("message", {})
- content = (msg.get("content") or "").strip()
- think, ans = _split_think(msg, content)
- ct = (resp.get("usage") or {}).get("completion_tokens")
- ans1 = ans.replace("\n", " ")[:70]
- print("%-16s %-9s %8.1f %8s %8d %s" % (name, mode, dt, ct, len(think.split()), ans1), flush=True)
- except Exception as e:
- print("%-16s %-9s ERROR %r" % (name, mode, e), flush=True)
- print("DONE.", flush=True)
-
-
-
-
-def main():
- mode = sys.argv[1] if len(sys.argv) > 1 else "run"
- if mode == "run":
- run()
- else:
- print(f"usage: python bench.py no-think [run]")
- sys.exit(1)
-
-
-if __name__ == "__main__":
- main()
diff --git a/bench/tasks/oracle.py b/bench/tasks/oracle.py
new file mode 100644
index 0000000..b6b86e7
--- /dev/null
+++ b/bench/tasks/oracle.py
@@ -0,0 +1,227 @@
+#!/usr/bin/env python3
+"""Router oracle labels: which lanes pass each item, and the cheapest one that does.
+
+ python3 bench.py oracle --order lane-a,lane-b,... [--lanes a,b] [--instruments x,y]
+ [--theta 0.67] [--lambda-usd X] [--out PATH.jsonl] [--simulate]
+ [--include-incomplete]
+
+Per (instrument, item_id) and lane: pass_rate = mean of `correct` over graded samples
+(pooled across runs of one item_set). A lane whose only evidence is ctx_overflow gets
+pass_rate 0 (it cannot take the item); any other infra-only item is unknown (None).
+feasible = lanes with pass_rate >= theta. oracle = first feasible lane in --order, or with
+--lambda-usd the feasible lane minimising median wall_s + lambda * mean cost_usd.
+Per item-set name (`fix-easy`, `fix-hard`, ... -- the part before `@`) only runs of ONE version are
+used (the one covering most lanes; others are dropped with a warning).
+"""
+import argparse
+import json
+import os
+import sys
+import time
+from collections import Counter, defaultdict
+
+from bench.core import results, stats
+from bench.tasks import report
+
+
+def _pass_rate(it):
+ if it["n_graded"] and it["pass"] is not None:
+ return it["pass"]
+ if it["n_ctx_overflow"]:
+ return 0.0
+ return None
+
+
+def pick_item_sets(data):
+ """(instrument, set name) -> chosen item_set version; warnings for dropped groups."""
+ cover = defaultdict(lambda: defaultdict(set))
+ for (lane, inst, iset) in data.groups:
+ cover[(inst, report.set_name(iset))][iset].add(lane)
+ chosen, warns = {}, []
+ for (inst, name), by in cover.items():
+ best = sorted(by, key=lambda s: (len(by[s]), str(s)))[-1]
+ chosen[(inst, name)] = best
+ for s in by:
+ if s != best:
+ warns.append(f"WARNING: {inst}: item_set {s!r} (lanes {sorted(by[s])}) "
+ f"differs from chosen {best!r}; excluded from labels.")
+ return chosen, warns
+
+
+def _lane_medians(data, chosen):
+ """(lane, inst, set name) -> (median wall_s, mean cost) over that lane's items; fallbacks."""
+ out = {}
+ for (lane, inst, iset), g in data.groups.items():
+ name = report.set_name(iset)
+ if chosen.get((inst, name)) != iset:
+ continue
+ w = [x for it in g["items"].values() for x in it["wall_s"]]
+ c = [x for it in g["items"].values() for x in it["cost_usd"]]
+ out[(lane, inst, name)] = (stats.median(w), stats.mean(c))
+ return out
+
+
+def derive(data, order, theta=0.67, lambda_usd=None):
+ """-> (label rows, warnings). Pure function of a report.Data; order = lanes, cheapest first."""
+ chosen, warns = pick_item_sets(data)
+ lm = _lane_medians(data, chosen)
+ per = defaultdict(lambda: defaultdict(dict)) # (inst, set name, iid) -> lane -> item
+ cat = {}
+ for (lane, inst, iset), g in data.groups.items():
+ name = report.set_name(iset)
+ if chosen.get((inst, name)) != iset:
+ continue
+ for iid, it in g["items"].items():
+ per[(inst, name, iid)][lane] = it
+ cat[(inst, name, iid)] = it["category"]
+ all_lanes = sorted({k[0] for k in data.groups})
+ rank = {l: i for i, l in enumerate(order)}
+ rows = []
+ for (inst, name, iid) in sorted(per):
+ lanes = per[(inst, name, iid)]
+ pr, wall, cost, ns = {}, {}, {}, {}
+ for lane in all_lanes:
+ it = lanes.get(lane)
+ if it is None:
+ pr[lane] = None
+ continue
+ pr[lane] = _pass_rate(it)
+ lw, lc = lm.get((lane, inst, name), (None, None))
+ wall[lane] = stats.median(it["wall_s"]) if it["wall_s"] else lw
+ cost[lane] = stats.mean(it["cost_usd"]) if it["cost_usd"] else lc
+ ns[lane] = it["n_graded"]
+ feasible = [l for l in all_lanes if pr.get(l) is not None and pr[l] >= theta]
+ if lambda_usd is not None:
+ def key(l):
+ w = wall.get(l)
+ return (float("inf") if w is None else w + lambda_usd * (cost.get(l) or 0.0),
+ rank.get(l, 1e9), l)
+ else:
+ def key(l):
+ return (rank.get(l, 1e9), l)
+ # lanes in --order first; lanes not in the order list only matter if nothing else
+ cand = sorted(feasible, key=key)
+ if lambda_usd is None:
+ cand = [l for l in cand if l in rank] + [l for l in cand if l not in rank]
+ oracle = cand[0] if cand else None
+ rows.append({"instrument": inst, "item_set": chosen[(inst, name)], "item_id": iid,
+ "category": cat[(inst, name, iid)], "pass_rate": pr, "feasible": feasible,
+ "difficulty": len(feasible), "oracle": oracle,
+ "label": oracle if oracle else "none",
+ "unknown_lanes": [l for l in all_lanes if pr.get(l) is None],
+ "n_samples": ns, "median_wall_s": wall, "mean_cost_usd": cost})
+ return rows, warns
+
+
+def histogram(rows):
+ h = defaultdict(Counter)
+ for r in rows:
+ h[(r["instrument"], r["category"])][r["label"]] += 1
+ return h
+
+
+# ------------------------------------------------------------- simulation ----
+
+def _tc(r, lane):
+ return (r["median_wall_s"].get(lane) or 0.0, r["mean_cost_usd"].get(lane) or 0.0)
+
+
+def cascade_eval(items, order):
+ """items: label rows restricted to complete cases. Returns (success, latency, total_cost).
+ Success prob of a lane = pass_rate; attempts are independent; stop at first success."""
+ succ = lat = cost = 0.0
+ for r in items:
+ reach = 1.0
+ for lane in order:
+ p = r["pass_rate"][lane]
+ t, c = _tc(r, lane)
+ lat += reach * t
+ cost += reach * c
+ succ += reach * p
+ reach *= 1 - p
+ n = len(items)
+ return succ / n, lat / n, cost
+
+
+def simulate(rows, order, lanes=None):
+ """Policy comparison on items where every simulated lane has data.
+ -> dict(n_items, n_dropped, policies=[{policy, success, latency_s, cost_usd}])"""
+ all_lanes = sorted({l for r in rows for l in r["pass_rate"]})
+ lanes = [l for l in (lanes or all_lanes) if l in all_lanes]
+ items = [r for r in rows if all(r["pass_rate"].get(l) is not None for l in lanes)]
+ ordered = [l for l in order if l in lanes] + [l for l in lanes if l not in order]
+ pols = []
+ if not items:
+ return {"n_items": 0, "n_dropped": len(rows), "policies": pols, "lanes": lanes}
+ n = len(items)
+ for l in lanes:
+ pols.append({"policy": f"always-{l}",
+ "success": sum(r["pass_rate"][l] for r in items) / n,
+ "latency_s": sum(_tc(r, l)[0] for r in items) / n,
+ "cost_usd": sum(_tc(r, l)[1] for r in items)})
+ # oracle: label lane among simulated lanes; items with none -> highest pass_rate lane
+ s = t = c = 0.0
+ for r in items:
+ cand = [l for l in ordered if l in r["feasible"]]
+ lane = cand[0] if cand else max(reversed(ordered), key=lambda x: r["pass_rate"][x])
+ s += r["pass_rate"][lane]
+ t += _tc(r, lane)[0]
+ c += _tc(r, lane)[1]
+ pols.append({"policy": "oracle", "success": s / n, "latency_s": t / n, "cost_usd": c})
+ cs, cl, cc = cascade_eval(items, ordered)
+ pols.append({"policy": "cascade(" + ">".join(ordered) + ")", "success": cs,
+ "latency_s": cl, "cost_usd": cc})
+ return {"n_items": n, "n_dropped": len(rows) - n, "policies": pols, "lanes": lanes}
+
+
+def render_simulation(sim):
+ L = [f"Simulation on {sim['n_items']} items with data for all of {sim['lanes']} "
+ f"({sim['n_dropped']} dropped)", "",
+ f"{'policy':<60} {'success':>8} {'latency_s':>10} {'total_usd':>10}"]
+ for p in sim["policies"]:
+ L.append(f"{p['policy']:<60} {p['success']:>8.3f} {p['latency_s']:>10.1f} {p['cost_usd']:>10.4f}")
+ return "\n".join(L)
+
+
+def render_histogram(h):
+ L = ["Label histogram per (instrument, category):"]
+ for (inst, cat) in sorted(h):
+ L.append(f" {inst:<18} {cat:<28} " + ", ".join(f"{k}={v}" for k, v in sorted(h[(inst, cat)].items())))
+ return "\n".join(L)
+
+
+def main(argv=None):
+ ap = argparse.ArgumentParser(prog="bench.py oracle", description=__doc__.split("\n\n")[0])
+ ap.add_argument("--lanes")
+ ap.add_argument("--instruments")
+ ap.add_argument("--theta", type=float, default=0.67)
+ ap.add_argument("--order", required=True, help="lanes, cheapest first (comma-separated)")
+ ap.add_argument("--lambda-usd", type=float, default=None)
+ ap.add_argument("--out")
+ ap.add_argument("--simulate", action="store_true")
+ ap.add_argument("--include-incomplete", action="store_true")
+ a = ap.parse_args(sys.argv[1:] if argv is None else argv)
+ data = report.collect(set(a.instruments.split(",")) if a.instruments else None,
+ set(a.lanes.split(",")) if a.lanes else None, a.include_incomplete)
+ if not data.groups:
+ print("no runs found (complete runs only unless --include-incomplete)")
+ raise SystemExit(1)
+ order = a.order.split(",")
+ rows, warns = derive(data, order, a.theta, a.lambda_usd)
+ for w in data.warnings + warns:
+ print(w)
+ out = a.out or os.path.join(results.RESULTS_DIR, "_oracle",
+ time.strftime("oracle-%Y%m%d-%H%M%S.jsonl"))
+ os.makedirs(os.path.dirname(os.path.abspath(out)), exist_ok=True)
+ with open(out, "w") as f:
+ for r in rows:
+ f.write(json.dumps(r) + "\n")
+ print(f"wrote {len(rows)} labels -> {out}")
+ print(render_histogram(histogram(rows)))
+ if a.simulate:
+ print()
+ print(render_simulation(simulate(rows, order, a.lanes.split(",") if a.lanes else None)))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/bench/tasks/reasoning.py b/bench/tasks/reasoning.py
new file mode 100644
index 0000000..1e8b9d9
--- /dev/null
+++ b/bench/tasks/reasoning.py
@@ -0,0 +1,404 @@
+#!/usr/bin/env python3
+"""
+reasoning.py - computing-knowledge multiple choice, graded on content (the reasoning text never is).
+
+ mmlu-pro-cs TIGER-Lab/MMLU-Pro test, category "computer science", 60 items, options A-J (MIT)
+
+Note (2026-10-12): only computing-relevant reasoning stays. AIME 2026, MuSR, ZebraLogic and the
+other MMLU-Pro categories were removed (stored runs of them still read in reports). Selection is
+deterministic (no RNG): sort by sha256(f"{set}:{native_id}") and take the first N. The selected
+items are cached (gitignored) and pinned by a committed manifest
+(bench/data/reasoning/<set>.manifest.json) holding a sha256 per item.
+
+Commands: fetch (download + pin), validate (offline, cache vs manifest), run (one run per set).
+"""
+import argparse
+import gzip
+import hashlib
+import json
+import os
+import re
+import sys
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+
+from bench.core import client, results
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+DATA_DIR = os.path.join(os.path.dirname(HERE), "data", "reasoning")
+CACHE_DIR = os.path.join(DATA_DIR, "cache")
+HF = "https://datasets-server.huggingface.co"
+INSTRUMENT = "reasoning"
+ALL_SETS = ["mmlu-pro-cs"]
+MMLU_CS_N = 60
+
+SPEC = {
+ "mmlu-pro-cs": {"dataset": "TIGER-Lab/MMLU-Pro", "config": "default", "splits": ["test"],
+ "rule": f"first {MMLU_CS_N} of category 'computer science' by "
+ "sha256('mmlu-pro-cs:<question_id>')"},
+}
+
+
+# ---------------------------------------------------------------- hashing / selection
+def canon(obj):
+ return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
+
+
+def item_sha(item):
+ return hashlib.sha256(canon(item).encode("utf-8")).hexdigest()
+
+
+def sel_key(set_name, native_id):
+ return hashlib.sha256(f"{set_name}:{native_id}".encode("utf-8")).hexdigest()
+
+
+def select(set_name, candidates, n):
+ """candidates: [(native_id, stratum, item)]. First n per stratum by hash order.
+ Returns items sorted by (stratum order of first appearance, hash)."""
+ by = {}
+ for native_id, stratum, item in candidates:
+ by.setdefault(stratum, []).append((sel_key(set_name, native_id), native_id, item))
+ out = []
+ for stratum in by:
+ for _k, native_id, item in sorted(by[stratum], key=lambda t: (t[0], str(t[1])))[:n]:
+ out.append(item)
+ return out
+
+
+def manifest_hash(manifest):
+ h = hashlib.sha256()
+ for it in manifest["items"]:
+ h.update((it["item_id"] + ":" + it["sha256"] + "\n").encode())
+ return h.hexdigest()[:12]
+
+
+# ---------------------------------------------------------------- normalizers
+
+
+def build_items(set_name, rows_by_split):
+ """rows_by_split: {split: [raw rows in dataset order]} -> selected normalized items."""
+ if set_name != "mmlu-pro-cs":
+ raise ValueError(set_name)
+ cands = []
+ for r in rows_by_split["test"]:
+ if r["category"] != "computer science":
+ continue
+ nid = str(r["question_id"])
+ cands.append((nid, "cs", {
+ "item_id": f"mmlu-pro-cs/{nid}", "native_id": nid, "category": "cs",
+ "question": r["question"], "options": list(r["options"]),
+ "answer": r["answer"], "answer_index": int(r["answer_index"]), "src": r.get("src")}))
+ return select(set_name, cands, MMLU_CS_N)
+
+
+# ---------------------------------------------------------------- fetch
+def _get_json(url, tries=12):
+ err = None
+ for i in range(tries):
+ try:
+ req = urllib.request.Request(url, headers={"User-Agent": "llm-bench/reasoning"})
+ with urllib.request.urlopen(req, timeout=60) as r:
+ return json.load(r)
+ except urllib.error.HTTPError as e:
+ err = e
+ if e.code not in (429, 500, 502, 503, 504):
+ raise
+ if e.code == 429:
+ try:
+ time.sleep(min(float(e.headers.get("Retry-After", 0)), 60))
+ except ValueError:
+ pass
+ time.sleep(min(5 * (i + 1), 30))
+ except Exception as e: # noqa: BLE001
+ err = e
+ time.sleep(1.5 * (i + 1))
+ raise RuntimeError(f"GET {url} failed: {err!r}")
+
+
+def fetch_split(dataset, config, split):
+ q = urllib.parse.urlencode({"dataset": dataset, "config": config, "split": split})
+ total = _get_json(f"{HF}/size?{urllib.parse.urlencode({'dataset': dataset})}")
+ n = None
+ for c in total["size"]["configs"]:
+ if c["config"] == config:
+ n = c["num_rows"]
+ splits = total["size"].get("splits") or []
+ for s in splits:
+ if s["config"] == config and s["split"] == split:
+ n = s["num_rows"]
+ if n is None:
+ raise RuntimeError(f"no row count for {dataset}/{config}/{split}")
+ rows = []
+ for off in range(0, n, 100):
+ page = _get_json(f"{HF}/rows?{q}&offset={off}&length=100")
+ rows.extend(x["row"] for x in page["rows"])
+ time.sleep(0.5)
+ if len(rows) != n:
+ raise RuntimeError(f"{dataset}/{split}: got {len(rows)} rows, expected {n}")
+ return rows
+
+
+def write_set(set_name, items, spec=None):
+ spec = spec or SPEC[set_name]
+ os.makedirs(CACHE_DIR, exist_ok=True)
+ with open(os.path.join(CACHE_DIR, f"{set_name}.jsonl"), "w", encoding="utf-8") as f:
+ for it in items:
+ f.write(json.dumps(it, ensure_ascii=False) + "\n")
+ manifest = {
+ "set": set_name,
+ "source": {"dataset": spec["dataset"], "config": spec["config"], "splits": spec["splits"]},
+ "selection_rule": "sort by sha256(f'<set>:<native_id>'), take first N per stratum. "
+ + spec["rule"],
+ "n": len(items),
+ "items": [{"item_id": it["item_id"], "native_id": it["native_id"],
+ "category": it["category"], "sha256": item_sha(it)} for it in items],
+ }
+ manifest["manifest_hash"] = manifest_hash(manifest)
+ path = os.path.join(DATA_DIR, f"{set_name}.manifest.json")
+ with open(path, "w") as f:
+ json.dump(manifest, f, indent=1, ensure_ascii=False)
+ f.write("\n")
+ return manifest
+
+
+def cmd_fetch(sets):
+ for s in sets:
+ spec = SPEC[s]
+ rows = {sp: fetch_split(spec["dataset"], spec["config"], sp) for sp in spec["splits"]}
+ items = build_items(s, rows)
+ old = _load_manifest(s, missing_ok=True)
+ m = write_set(s, items)
+ note = ""
+ if old and old.get("manifest_hash") != m["manifest_hash"]:
+ note = f" (CHANGED vs previous manifest {old.get('manifest_hash')})"
+ cats = {}
+ for it in m["items"]:
+ cats[it["category"]] = cats.get(it["category"], 0) + 1
+ print(f"{s}: {m['n']} items, manifest {m['manifest_hash']}{note}")
+ for c in sorted(cats):
+ print(f" {c}: {cats[c]}")
+ return 0
+
+
+# ---------------------------------------------------------------- load / validate
+def _load_manifest(set_name, missing_ok=False):
+ p = os.path.join(DATA_DIR, f"{set_name}.manifest.json")
+ if not os.path.exists(p):
+ if missing_ok:
+ return None
+ raise FileNotFoundError(f"{p} missing - run `reasoning fetch`")
+ with open(p) as f:
+ return json.load(f)
+
+
+def load_items(set_name):
+ """Cache items, verified against the manifest. Raises ValueError on any drift."""
+ manifest = _load_manifest(set_name)
+ p = os.path.join(CACHE_DIR, f"{set_name}.jsonl")
+ if not os.path.exists(p):
+ raise FileNotFoundError(f"{p} missing - run `reasoning fetch --sets {set_name}`")
+ with open(p, encoding="utf-8") as f:
+ items = [json.loads(l) for l in f if l.strip()]
+ problems = check_items(items, manifest)
+ if problems:
+ raise ValueError(f"{set_name}: cache does not match manifest: " + "; ".join(problems[:5]))
+ return items, manifest
+
+
+def check_items(items, manifest):
+ problems = []
+ want = {m["item_id"]: m for m in manifest["items"]}
+ got = {}
+ for it in items:
+ got[it["item_id"]] = it
+ if len(items) != len(got):
+ problems.append("duplicate item_ids in cache")
+ for iid in want:
+ if iid not in got:
+ problems.append(f"missing {iid}")
+ elif item_sha(got[iid]) != want[iid]["sha256"]:
+ problems.append(f"hash mismatch {iid}")
+ for iid in got:
+ if iid not in want:
+ problems.append(f"extra {iid}")
+ if manifest.get("n") != len(manifest["items"]):
+ problems.append("manifest n != len(items)")
+ if manifest.get("manifest_hash") != manifest_hash(manifest):
+ problems.append("manifest_hash stale")
+ return problems
+
+
+def cmd_validate(sets):
+ bad = 0
+ for s in sets:
+ try:
+ items, m = load_items(s)
+ cats = {}
+ for it in items:
+ cats[it["category"]] = cats.get(it["category"], 0) + 1
+ print(f"{s}: OK {len(items)} items, manifest {m['manifest_hash']}, "
+ f"{len(cats)} categories")
+ except (FileNotFoundError, ValueError) as e:
+ bad += 1
+ print(f"{s}: FAIL {e}")
+ return 1 if bad else 0
+
+
+# ---------------------------------------------------------------- prompts
+LETTERS = "ABCDEFGHIJ"
+
+
+def mc_prompt(body, options):
+ opts = "\n".join(f"{LETTERS[i]}. {o}" for i, o in enumerate(options))
+ return (f"{body}\n\nOptions:\n{opts}\n\n"
+ "Think it through, then end your reply with a line 'ANSWER: <letter>' "
+ "(a single letter, e.g. 'ANSWER: C').")
+
+
+def prompt_hash():
+ """Hash of the prompt templates. Part of item_set, so runs asked with different
+ wording are never pooled or paired by the report."""
+ import inspect
+ src = "".join(inspect.getsource(f) for f in (mc_prompt, build_prompt))
+ return hashlib.sha256(src.encode()).hexdigest()[:8]
+
+
+def build_prompt(item):
+ if item["item_id"].startswith("mmlu-pro-cs/"):
+ return mc_prompt(item["question"], item["options"])
+ raise ValueError(item["item_id"])
+
+
+# ---------------------------------------------------------------- extraction / grading
+
+
+
+
+
+
+
+
+# "ANSWER: C" / "ANSWER: (C)" / "answer: c". An uppercase letter may be followed by more text
+# ("ANSWER: C. Mia"); a lowercase letter only counts when it is the whole answer, so
+# "ANSWER: a long story" is not read as option A.
+_ANS_UP = re.compile(r"ANSWER\s*:\s*[*_`\s]*\(?([A-J])\b", re.I)
+_ANS_LOW = re.compile(r"ANSWER\s*:\s*[*_`\s]*\(?([a-j])\)?[.*_`\s]*$", re.I)
+_LONE = re.compile(r"^[\s*_`(\[]*([A-Ja-j])[\s*_`)\].]*$")
+
+
+def extract_letter(content):
+ """Last 'ANSWER: X' (X in A-J, upper or lowercase), else a lone letter on the last
+ non-empty line, else None."""
+ last = None
+ for line in (content or "").splitlines():
+ hit = None
+ for m in _ANS_UP.finditer(line):
+ if m.group(1).isupper():
+ hit = m.group(1)
+ if hit is None:
+ m = _ANS_LOW.search(line)
+ if m:
+ hit = m.group(1)
+ if hit:
+ last = hit.upper()
+ if last:
+ return last
+ lines = [l for l in (content or "").splitlines() if l.strip()]
+ if lines:
+ m = _LONE.match(lines[-1])
+ if m:
+ return m.group(1).upper()
+ return None
+
+
+def grade(item, content):
+ """-> dict(correct, score, extracted, gold)."""
+ letter = extract_letter(content)
+ gold = LETTERS[item["answer_index"]]
+ return {"correct": letter == gold, "score": None, "extracted": letter, "gold": gold}
+
+
+# ---------------------------------------------------------------- run
+def _attempt(store, lane, item, k):
+ def check(resp):
+ content = client.content(resp) or ""
+ reasoning = client.reasoning(resp) or ""
+ row = dict(grade(item, content), content_tail=content[-600:],
+ reasoning_head=reasoning[:400], reasoning_tail=reasoning[-400:])
+ if store.run["args"].get("keep_reasoning") and reasoning:
+ row["reasoning_file"] = _write_reasoning(store, item["item_id"], k, reasoning)
+ return row
+ results.call_attempt(store, lane, item["item_id"], k, item["category"],
+ [{"role": "user", "content": build_prompt(item)}], check)
+
+
+def _write_reasoning(store, item_id, k, text):
+ name = f"{results.safe_label(item_id)}-{k}.reasoning.txt.gz"
+ with gzip.open(os.path.join(store.dir, name), "wt", encoding="utf-8") as f:
+ f.write(text)
+ return name
+
+
+def run_set(set_name, items, manifest, *, lane=None, samples=1, concurrency=None,
+ resume_dir=None, keep_reasoning=False, item_ids=None):
+ """One run over one set -> (store, summary). On resume the args come from run.json."""
+ iset = f"{set_name}@{manifest['manifest_hash']}.p{prompt_hash()}"
+ args = {"sets": [set_name], "samples": samples, "concurrency": concurrency,
+ "items": item_ids, "keep_reasoning": keep_reasoning}
+ plan = lambda _args: (iset, [(it["item_id"], it) for it in items]) # noqa: E731
+ return results.run_attempts(INSTRUMENT, args, plan, _attempt, resume=resume_dir, lane=lane)
+
+
+def cmd_run(args):
+ sets = _parse_sets(args.sets)
+ if args.resume:
+ with open(os.path.join(args.resume, "run.json")) as f:
+ sets = [json.load(f)["item_set"].split("@")[0]]
+ want = [x for x in args.items.split(",") if x]
+ for s in sets:
+ items, manifest = load_items(s)
+ sel = [i for i in want if i in {it["item_id"] for it in items}]
+ if want and not sel and not args.resume:
+ continue
+ _store, summary = run_set(s, items, manifest, samples=args.samples,
+ concurrency=args.concurrency, resume_dir=args.resume,
+ keep_reasoning=args.keep_reasoning, item_ids=sel or None)
+ if summary["stopped"]:
+ print("budget stop - remaining sets not run", file=sys.stderr)
+ return 3
+ return 0
+
+
+def _parse_sets(s):
+ if not s:
+ return list(ALL_SETS)
+ out = [x.strip() for x in s.split(",") if x.strip()]
+ for x in out:
+ if x not in SPEC:
+ raise SystemExit(f"unknown set {x!r}; choose from {ALL_SETS}")
+ return out
+
+
+def main(argv=None):
+ p = argparse.ArgumentParser(prog="bench.py reasoning")
+ sub = p.add_subparsers(dest="cmd", required=True)
+ for name in ("fetch", "validate", "run"):
+ sp = sub.add_parser(name)
+ sp.add_argument("--sets", default=None, help="comma list of: " + ",".join(ALL_SETS))
+ if name == "run":
+ results.add_run_args(sp, concurrency=None)
+ sp.add_argument("--keep-reasoning", action="store_true")
+ args = p.parse_args(sys.argv[1:] if argv is None else argv)
+ if args.cmd == "fetch":
+ rc = cmd_fetch(_parse_sets(args.sets))
+ elif args.cmd == "validate":
+ rc = cmd_validate(_parse_sets(args.sets))
+ else:
+ rc = cmd_run(args)
+ sys.exit(rc)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/bench/tasks/report.py b/bench/tasks/report.py
new file mode 100644
index 0000000..d773431
--- /dev/null
+++ b/bench/tasks/report.py
@@ -0,0 +1,439 @@
+#!/usr/bin/env python3
+"""Capability-profile report over stored runs.
+
+ python3 bench.py report [--instruments a,b] [--lanes x,y] [--ref claude-opus]
+ [--out PATH.md] [--json PATH] [--csv PATH]
+ [--include-incomplete] [--boot N] [--seed N]
+
+Rows = (instrument, category), columns = lanes. Per-item value = mean of `score` (when
+present) else of `correct` over graded samples; a category/lane value = mean over items.
+Samples are pooled across runs of the same (lane, instrument, item_set). Differently named
+item sets (`fix-easy@..`, `fix-hard@..`) are separate suites sharing the lane's column; two versions
+of one name are never pooled (they become separate columns `lane[item_set]`, with a warning). Resumed runs: per (run_id, item_id, sample_idx) the last non-infra row wins,
+else the last row. See bench/core/stats.py for CI / McNemar details. Conformance runs are the
+preflight, not a capability: they stay out of the profile, and each lane's latest one is listed
+in its own section (WARN = the model's own miss, which no other table shows).
+"""
+import argparse
+import csv
+import json
+import sys
+from collections import defaultdict
+
+from bench.core import results, stats
+from bench.core.results import is_infra
+
+
+# ---------------------------------------------------------------- loading ----
+
+def sample_value(r):
+ """Graded value of one attempt: score if present, else correct; None if not graded."""
+ if is_infra(r.get("status")):
+ return None
+ if r.get("score") is not None:
+ return float(r["score"])
+ if r.get("correct") is not None:
+ return float(bool(r["correct"]))
+ return None
+
+
+def sample_pass(r):
+ """Binary pass of one attempt (correct), None if not graded."""
+ if is_infra(r.get("status")):
+ return None
+ if r.get("correct") is not None:
+ return float(bool(r["correct"]))
+ if r.get("score") is not None:
+ return float(r["score"] >= 1.0)
+ return None
+
+
+def build_items(rows):
+ """Deduped rows of one group -> {item_id: item dict}."""
+ by = defaultdict(list)
+ for r in rows:
+ by[r["item_id"]].append(r)
+ items = {}
+ for iid, rs in by.items():
+ vals = [v for v in map(sample_value, rs) if v is not None]
+ pas = [v for v in map(sample_pass, rs) if v is not None]
+ cats = [r.get("category") for r in rs if r.get("category")]
+ walls = [r["wall_s"] for r in rs if r.get("wall_s") is not None]
+ costs = [r["cost_usd"] for r in rs if r.get("cost_usd") is not None]
+ items[iid] = {
+ "category": cats[-1] if cats else "(none)",
+ "value": stats.mean(vals), "pass": stats.mean(pas),
+ "n_graded": len(vals), "n_attempts": len(rs),
+ "n_ctx_overflow": sum(1 for r in rs if r.get("status") == "ctx_overflow"),
+ "wall_s": walls, "cost_usd": costs,
+ }
+ return items
+
+
+class Data:
+ """Grouped runs: groups[(lane, instrument, item_set)] -> dict(runs, raw, rows, items)."""
+
+ def __init__(self):
+ self.groups = {}
+ self.preflight = {} # lane -> (run, rows) of its latest conformance run
+ self.warnings = []
+
+ def add(self, run, rows):
+ key = (run["lane"]["lane_id"], run["instrument"], run.get("item_set"))
+ g = self.groups.setdefault(key, {"runs": [], "raw": [], "rows": [], "items": None})
+ g["runs"].append(run)
+ g["raw"].extend(rows)
+ g["rows"].extend(results.dedupe(rows))
+
+ def finalize(self):
+ for key, g in self.groups.items():
+ g["items"] = build_items(g["rows"])
+ # Differently named sets (agentic-fix's fix-easy / fix-hard, ...) are separate suites and share
+ # the lane's column; only versions of the same name conflict. A category emitted by two
+ # names would collide in one cell, so those groups get suffixed columns too.
+ self._suffixed = set()
+ versions = defaultdict(set)
+ cat_owner = defaultdict(set)
+ for (lane, inst, iset), g in self.groups.items():
+ versions[(lane, inst, set_name(iset))].add(iset)
+ for it in g["items"].values():
+ cat_owner[(lane, inst, it["category"])].add(iset)
+ for (lane, inst, name), s in sorted(versions.items(), key=str):
+ if len(s) > 1:
+ self._suffixed |= {(lane, inst, i) for i in s}
+ self.warnings.append(
+ f"WARNING: lane {lane!r} instrument {inst!r} has runs with different "
+ f"item_set values {sorted(map(str, s))}; NOT pooled, reported separately.")
+ for (lane, inst, cat), s in sorted(cat_owner.items(), key=str):
+ if len({set_name(i) for i in s}) > 1:
+ self._suffixed |= {(lane, inst, i) for i in s}
+ self.warnings.append(
+ f"WARNING: lane {lane!r} instrument {inst!r} category {cat!r} comes from "
+ f"item sets {sorted(map(str, s))}; reported separately.")
+ return self
+
+ def col_name(self, lane, inst, iset):
+ return f"{lane}[{iset}]" if (lane, inst, iset) in self._suffixed else lane
+
+
+def set_name(iset):
+ """'fix-easy@3f0c9a1d2b7e' -> 'fix-easy' (the suite); the rest is its version."""
+ return iset.split("@", 1)[0] if isinstance(iset, str) else iset
+
+
+def collect(instruments=None, lanes=None, include_incomplete=False):
+ d = Data()
+ for run, rows in results.load_runs(instruments, lanes, include_incomplete):
+ if run.get("instrument") != "conformance":
+ d.add(run, rows)
+ continue
+ lane = run["lane"]["lane_id"]
+ if lane not in d.preflight or run.get("started_at", "") >= d.preflight[lane][0].get("started_at", ""):
+ d.preflight[lane] = (run, rows)
+ return d.finalize()
+
+
+# ------------------------------------------------------------ aggregation ----
+
+def _cell(items_by_id, n_boot, seed):
+ ids = sorted(items_by_id)
+ vals = [items_by_id[i]["value"] for i in ids if items_by_id[i]["value"] is not None]
+ if not vals:
+ return None
+ binary = all(v in (0.0, 1.0) for v in vals)
+ if binary:
+ ci = stats.wilson(int(sum(vals)), len(vals))
+ method = "wilson"
+ else:
+ ci = stats.bootstrap_ci(vals, n_boot=n_boot, seed=seed)
+ method = "bootstrap"
+ return {"value": stats.mean(vals), "ci_lo": ci[0], "ci_hi": ci[1], "ci_method": method,
+ "n_items": len(vals)}
+
+
+def profile(data, ref=None, n_boot=2000, seed=0):
+ """-> dict with cols, rows[(inst,cat)] -> {col: cell}, deltas."""
+ cells = defaultdict(dict) # (inst, cat) -> col -> cell
+ itemvals = defaultdict(dict) # (inst, cat) -> col -> {item_id: item}
+ colset = {} # (col, inst, cat) -> iset
+ cols = set()
+ for (lane, inst, iset), g in sorted(data.groups.items(), key=str):
+ col = data.col_name(lane, inst, iset)
+ cols.add(col)
+ bycat = defaultdict(dict)
+ for iid, it in g["items"].items():
+ if it["value"] is not None:
+ bycat[it["category"]][iid] = it
+ for cat, items in bycat.items():
+ colset[(col, inst, cat)] = iset
+ cells[(inst, cat)][col] = _cell(items, n_boot, seed)
+ itemvals[(inst, cat)][col] = items
+ cols = sorted(cols)
+ deltas = defaultdict(dict)
+ if ref:
+ for (inst, cat), by_col in itemvals.items():
+ refcols = [c for c in by_col if c == ref or c.startswith(ref + "[")]
+ if not refcols:
+ continue
+ rcol = refcols[0]
+ for col, items in by_col.items():
+ if col == rcol:
+ continue
+ if colset.get((col, inst, cat)) != colset.get((rcol, inst, cat)):
+ deltas[(inst, cat)][col] = {"skipped": "item_set differs from ref"}
+ continue
+ a = {i: v["value"] for i, v in items.items()}
+ b = {i: v["value"] for i, v in by_col[rcol].items()}
+ d = stats.paired_delta(a, b, n_boot=n_boot, seed=seed)
+ ap = {i: v["pass"] for i, v in items.items()}
+ bp = {i: v["pass"] for i, v in by_col[rcol].items()}
+ mc = stats.mcnemar_items(ap, bp)
+ d["mcnemar_p"] = mc["p"] if mc["n"] else None
+ d["mcnemar"] = mc
+ d["sig"] = (d["n"] > 0 and (d["ci_lo"] > 0 or d["ci_hi"] < 0))
+ d["ref_col"] = rcol
+ deltas[(inst, cat)][col] = d
+ return {"cols": cols, "cells": cells, "deltas": deltas}
+
+
+def status_table(data):
+ per = defaultdict(lambda: {"n": 0, "truncated": 0, "ctx_overflow": 0, "infra": defaultdict(int)})
+ for (lane, inst, iset), g in data.groups.items():
+ t = per[lane]
+ for r in g["rows"]:
+ t["n"] += 1
+ st = r.get("status")
+ if st == "truncated":
+ t["truncated"] += 1
+ if st == "ctx_overflow":
+ t["ctx_overflow"] += 1
+ if is_infra(st):
+ t["infra"][st] += 1
+ return per
+
+
+def speed_table(data):
+ per = {}
+ rows_by_lane = defaultdict(lambda: {"raw": [], "rows": []})
+ for (lane, _inst, _iset), g in data.groups.items():
+ rows_by_lane[lane]["raw"].extend(g["raw"])
+ rows_by_lane[lane]["rows"].extend(g["rows"])
+ for lane, d in rows_by_lane.items():
+ rows = [r for r in d["rows"] if not is_infra(r.get("status"))]
+ costs = [r["cost_usd"] for r in d["raw"] if r.get("cost_usd") is not None]
+
+ def cached_heavy(r):
+ pt, ct = r.get("prompt_tokens"), r.get("cached_tokens")
+ return bool(pt) and ct is not None and ct > 0.5 * pt
+ per[lane] = {
+ "cost_usd": sum(costs) if costs else None, "cost_rows": len(costs),
+ "wall_s_median": stats.median(r["wall_s"] for r in rows if r.get("wall_s") is not None),
+ "decode_ps_median": stats.median(r["decode_ps"] for r in rows
+ if r.get("decode_ps") is not None),
+ "prefill_ps_median": stats.median(
+ r["prefill_ps"] for r in rows
+ if r.get("prefill_ps") is not None and not cached_heavy(r)),
+ "completion_tokens_mean": stats.mean(r["completion_tokens"] for r in rows
+ if r.get("completion_tokens") is not None),
+ "reasoning_tokens_mean": stats.mean(r["reasoning_tokens"] for r in rows
+ if r.get("reasoning_tokens") is not None),
+ }
+ return per
+
+
+def _find(d, key):
+ """First value for `key` anywhere in nested dict d."""
+ if isinstance(d, dict):
+ if key in d and not isinstance(d[key], (dict, list)):
+ return d[key]
+ for v in d.values():
+ r = _find(v, key)
+ if r is not None:
+ return r
+ return None
+
+
+def preflight_table(data):
+ """lane -> {run_id, started_at, checks: {check: verdict}} of its latest conformance run."""
+ return {lane: {"run_id": run["run_id"], "started_at": run.get("started_at"),
+ "checks": {r["item_id"]: r.get("verdict") for r in results.dedupe(rows)}}
+ for lane, (run, rows) in data.preflight.items()}
+
+
+def provenance(data):
+ out = []
+ for (lane, inst, iset), g in sorted(data.groups.items(), key=str):
+ run = sorted(g["runs"], key=lambda r: r.get("started_at") or "")[-1]
+ ln = run.get("lane", {})
+ h = run.get("harness", {})
+ n_ctx = _find(run.get("server", {}), "n_ctx")
+ if n_ctx is None:
+ n_ctx = (ln.get("context") or {}).get("n_ctx")
+ out.append({
+ "lane": lane, "instrument": inst, "item_set": iset,
+ "run_ids": sorted(r["run_id"] for r in g["runs"]),
+ "quant": (ln.get("weights") or {}).get("quant"),
+ "runtime": (ln.get("runtime") or {}).get("engine"),
+ "build": (ln.get("runtime") or {}).get("build"),
+ "git_sha": h.get("git_sha"), "dirty": h.get("dirty"),
+ "server_n_ctx": n_ctx,
+ })
+ return out
+
+
+# ------------------------------------------------------------- rendering ----
+
+def _f(x, nd=2):
+ return "-" if x is None else f"{x:.{nd}f}"
+
+
+def _sg(x, nd=2):
+ return "-" if x is None else f"{x:+.{nd}f}"
+
+
+def render_markdown(data, prof, ref, status, speed, prov):
+ L = ["# Capability profile", ""]
+ for w in data.warnings:
+ L.append(f"> {w}")
+ if data.warnings:
+ L.append("")
+ cols = prof["cols"]
+ L += ["## Profile (value [95% CI] n_items)", "",
+ "Wilson CI when every item is binary, else paired-item bootstrap. "
+ "Per-item value = mean score/correct over graded samples.", ""]
+ L.append("| instrument | category | " + " | ".join(cols) + " |")
+ L.append("|---|---|" + "---|" * len(cols))
+ for (inst, cat) in sorted(prof["cells"]):
+ row = []
+ for c in cols:
+ ce = prof["cells"][(inst, cat)].get(c)
+ row.append("" if not ce else
+ f"{ce['value']:.2f} [{ce['ci_lo']:.2f},{ce['ci_hi']:.2f}] n={ce['n_items']}")
+ L.append(f"| {inst} | {cat} | " + " | ".join(row) + " |")
+ if ref and not prof["deltas"]:
+ L += ["", f"## Delta vs `{ref}`", "", f"No category has runs of both `{ref}` and another lane."]
+ elif ref:
+ L += ["", f"## Delta vs `{ref}` (paired on shared items)", "",
+ "cell = mean delta [95% bootstrap CI] n=paired items, McNemar exact p "
+ "(per-item majority outcome); `*` = CI excludes 0.", ""]
+ others = [c for c in cols if not (c == ref or c.startswith(ref + "["))]
+ L.append("| instrument | category | " + " | ".join(others) + " |")
+ L.append("|---|---|" + "---|" * len(others))
+ for (inst, cat) in sorted(prof["deltas"]):
+ row = []
+ for c in others:
+ d = prof["deltas"][(inst, cat)].get(c)
+ if not d:
+ row.append("")
+ elif "skipped" in d:
+ row.append(d["skipped"])
+ elif d["n"] == 0:
+ row.append("no shared items")
+ else:
+ p = "-" if d["mcnemar_p"] is None else f"{d['mcnemar_p']:.3f}"
+ row.append(f"{_sg(d['mean_delta'])} [{_sg(d['ci_lo'])},{_sg(d['ci_hi'])}] "
+ f"n={d['n']} p={p}{' *' if d['sig'] else ''}")
+ L.append(f"| {inst} | {cat} | " + " | ".join(row) + " |")
+ pre = preflight_table(data)
+ if pre:
+ L += ["", "## Preflight (latest conformance run per lane)", "",
+ "FAIL = a pipeline or lane-settings problem (blocks runs); WARN = the model's own miss.", "",
+ "| lane | run | pass | warn | fail | WARN / FAIL checks |", "|---|---|---|---|---|---|"]
+ for lane, p in sorted(pre.items()):
+ n = defaultdict(list)
+ for check, verdict in sorted(p["checks"].items()):
+ n[verdict].append(check)
+ flagged = ", ".join(f"{c} ({v})" for v in ("FAIL", "WARN") for c in n[v]) or "-"
+ L.append(f"| {lane} | {p['run_id']} | {len(n['PASS'])} | {len(n['WARN'])} | "
+ f"{len(n['FAIL'])} | {flagged} |")
+ L += ["", "## Status per lane", "",
+ "| lane | attempts | truncated % | infra % | ctx_overflow | infra by status |",
+ "|---|---|---|---|---|---|"]
+ for lane in sorted(status):
+ t = status[lane]
+ n = t["n"] or 1
+ infra_n = sum(t["infra"].values())
+ by = ", ".join(f"{k}={v}" for k, v in sorted(t["infra"].items())) or "-"
+ L.append(f"| {lane} | {t['n']} | {100 * t['truncated'] / n:.1f} | "
+ f"{100 * infra_n / n:.1f} | {t['ctx_overflow']} | {by} |")
+ L += ["", "## Cost / speed per lane", "",
+ "cost = sum of reported cost_usd (estimated from usage when the provider reports none); "
+ "prefill median excludes rows with cached_tokens > 50% of prompt_tokens.", "",
+ "| lane | cost_usd | median wall_s | median decode t/s | median prefill t/s "
+ "| mean completion tok | mean reasoning tok |", "|---|---|---|---|---|---|---|"]
+ for lane in sorted(speed):
+ s = speed[lane]
+ L.append(f"| {lane} | {_f(s['cost_usd'], 4)} | {_f(s['wall_s_median'], 1)} | "
+ f"{_f(s['decode_ps_median'], 1)} | {_f(s['prefill_ps_median'], 1)} | "
+ f"{_f(s['completion_tokens_mean'], 0)} | {_f(s['reasoning_tokens_mean'], 0)} |")
+ L += ["", "## Provenance", "",
+ "| lane | instrument | item_set | runs | quant | runtime/build | harness git | n_ctx |",
+ "|---|---|---|---|---|---|---|---|"]
+ for p in prov:
+ sha = (p["git_sha"] or "?")[:9] + ("+dirty" if p["dirty"] else "")
+ L.append(f"| {p['lane']} | {p['instrument']} | {p['item_set']} | "
+ f"{', '.join(p['run_ids'])} | {p['quant'] or '-'} | "
+ f"{p['runtime'] or '-'} {p['build'] or ''} | {sha} | {p['server_n_ctx'] or '-'} |")
+ return "\n".join(L) + "\n"
+
+
+def to_json(data, prof, ref, status, speed, prov):
+ def key(k):
+ return "|".join(map(str, k))
+ return {
+ "ref": ref, "warnings": data.warnings, "columns": prof["cols"],
+ "profile": {key(k): v for k, v in prof["cells"].items()},
+ "deltas": {key(k): v for k, v in prof["deltas"].items()},
+ "status": {l: dict(t, infra=dict(t["infra"])) for l, t in status.items()},
+ "speed": speed, "provenance": prov, "preflight": preflight_table(data),
+ }
+
+
+def write_csv(data, path):
+ with open(path, "w", newline="") as f:
+ w = csv.writer(f)
+ w.writerow(["lane", "instrument", "category", "item_id", "value", "n_samples"])
+ for (lane, inst, iset), g in sorted(data.groups.items(), key=str):
+ col = data.col_name(lane, inst, iset)
+ for iid, it in sorted(g["items"].items()):
+ if it["value"] is not None:
+ w.writerow([col, inst, it["category"], iid, f"{it['value']:.6g}", it["n_graded"]])
+
+
+def main(argv=None):
+ ap = argparse.ArgumentParser(prog="bench.py report", description=__doc__.split("\n\n")[0])
+ ap.add_argument("--instruments")
+ ap.add_argument("--lanes")
+ ap.add_argument("--ref", default="claude-opus")
+ ap.add_argument("--out")
+ ap.add_argument("--json")
+ ap.add_argument("--csv")
+ ap.add_argument("--include-incomplete", action="store_true")
+ ap.add_argument("--boot", type=int, default=2000)
+ ap.add_argument("--seed", type=int, default=0)
+ a = ap.parse_args(sys.argv[1:] if argv is None else argv)
+ insts = set(a.instruments.split(",")) if a.instruments else None
+ lanes = set(a.lanes.split(",")) if a.lanes else None
+ if lanes and a.ref:
+ lanes.add(a.ref)
+ data = collect(insts, lanes, a.include_incomplete)
+ if not data.groups and not data.preflight:
+ print("no runs found (complete runs only unless --include-incomplete)")
+ raise SystemExit(1)
+ ref = a.ref if a.ref else None
+ prof = profile(data, ref, a.boot, a.seed)
+ status, speed, prov = status_table(data), speed_table(data), provenance(data)
+ md = render_markdown(data, prof, ref, status, speed, prov)
+ print(md)
+ if a.out:
+ with open(a.out, "w") as f:
+ f.write(md)
+ if a.json:
+ with open(a.json, "w") as f:
+ json.dump(to_json(data, prof, ref, status, speed, prov), f, indent=2, default=str)
+ if a.csv:
+ write_csv(data, a.csv)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/bench/tasks/router.py b/bench/tasks/router.py
index 485773b..828f11e 100644
--- a/bench/tasks/router.py
+++ b/bench/tasks/router.py
@@ -1,47 +1,35 @@
-"""Dispatch / router / orchestrator benchmark for LAIC.
-
-Motivation
-----------
-The idea (2026-08-17): use a *cheap, always-on local* model as the front door for
-all communication, and have IT decide which tier actually does each task — keep
-trivial things local, escalate genuinely hard/large-context/high-stakes work to a
-bigger local model or the cloud. This bench measures how good a given model is at
-BEING that dispatcher. It is deliberately shaped like the coding suite
-(env-driven OpenAI endpoint, self-contained dataset, validate/run/report, JSONL
-out, category breakdown) so it runs against the same LM Studio / vLLM endpoints
-the coding suite uses:
-
- python bench.py router run
- python bench.py router report # rebuild summary from results/router_<label>.jsonl
-
-Env (via .env / environment): ENDPOINT, MODEL, API_KEY, MAX_TOKENS,
-TEMPERATURE, HTTP_TIMEOUT, NOTHINK. NOTHINK=1 appends an empty <think/>
-assistant turn (portable no-think trick — the parser already strips
-<think>...</think>, so any echoed prefix is harmless).
-
-Two phases
-----------
-1. ROUTE (single-turn tier selection): given a request + a fixed worker menu, emit
- one JSON dispatch decision {"target","reason","confidence"}. Scored on exact/
- acceptable routing, format fidelity, and — the axes that actually matter for a
- dispatcher — over- vs under-escalation (cost-ordered) and privacy-constraint
- adherence (some requests must NOT leave the LAN regardless of difficulty).
-2. ORCH (multi-step orchestration): given a COMPOUND request, emit an ordered JSON
- plan of steps, each tagged with a task `kind` and assigned a `worker`, with
- `depends_on` edges. Scored on decomposition coverage, per-step assignment
- sanity (worker capable of that kind), and dependency ordering.
-
-Scoring is deterministic: no model judges another. The dataset is curated so every
-gold target sits inside its own acceptable set and every required orchestration
-dependency is well-formed; `validate` proves that before any model is run.
+"""Router instrument: how well a model dispatches requests to a menu of worker tiers.
+
+ROUTE (26 items): emit one JSON decision {"target", "reason", "confidence"} for a request.
+ correct = target in the item's acceptable set without a privacy violation (a local_only
+ request sent to a CLOUD worker); rows also record exact match, format fidelity and the
+ cost-ordered escalation error (esc_err > 0 over-, < 0 under-escalated). Category route/<cat>.
+ORCH (8 items): split a compound request into a JSON array of steps, each with a `kind`, a
+ `worker` and depends_on edges. correct = every required kind covered, every known-kind step on
+ a capable worker, every required dependency reachable, no privacy violation. Category orch.
+JUDGE (32 items, router_sets.py; suite v3, 2026-10-12): small models as graders of computing work.
+ verdict (24): does the candidate (code, command, query, log summary, config, answer) meet the
+ task? {"verdict": "pass"|"fail"}; correct = matches gold. Reports false-pass / false-fail.
+ pairwise (8): which of two candidates better meets the task? {"better": "A"|"B"}, asked in both
+ orders (item ids <id>/ab and <id>/ba); reports position consistency and position bias.
+RERANK (16 items): order 7-8 candidates (code, log lines, docs, commands, errors) for a query.
+ {"ranking": [ids]}; correct = top-1 is the single grade-3 candidate; rows add MRR of that
+ candidate and NDCG@5 over graded relevance (gain 2^rel - 1).
+Families run separately (`run --families route,orch,judge,rerank`, default all), one item set
+each: router-<family>@<hash>. Categories route/<cat>, orch, judge/<cat>, pairwise/<cat>, rerank/<cat>.
+Scoring is deterministic (no model judges another); `validate` proves the dataset offline.
"""
+import argparse
+import hashlib
import json
-import os
+import math
import re
import sys
-from bench.core import client
-from bench.core.reporting import jsonl_path, append_jsonl, write_json
+from bench.core import client, lane as lane_mod, results
+from bench.tasks.router_sets import JUDGE, RERANK
+
+INSTRUMENT = "router"
# ---------------------------------------------------------------- the worker menu
@@ -220,32 +208,17 @@ ORCH = [
]
# ---------------------------------------------------------------- local helpers
-def _first_json(text, want="object"):
- """Extract the first top-level JSON object ({...}) or array ([...]) from text,
- tolerating <think>...</think> preambles and markdown fences."""
+def _first_json(text, opener, closer):
+ """The JSON value whose span starts at the first `opener` of text (think blocks removed), or
+ None; later spans are never tried."""
text = re.sub(r"<think>.*?</think>", "", text, flags=re.DOTALL)
- opener, closer = ("{", "}") if want == "object" else ("[", "]")
- start = text.find(opener)
- if start < 0:
+ start, span = next(client.json_spans(text, opener, closer), (None, None))
+ if start is None or start != text.find(opener):
+ return None
+ try:
+ return json.loads(span)
+ except ValueError:
return None
- depth, instr, esc = 0, False, False
- for i in range(start, len(text)):
- c = text[i]
- if instr:
- if esc: esc = False
- elif c == "\\": esc = True
- elif c == '"': instr = False
- continue
- if c == '"': instr = True
- elif c == opener: depth += 1
- elif c == closer:
- depth -= 1
- if depth == 0:
- try:
- return json.loads(text[start:i+1])
- except Exception:
- return None
- return None
# ---------------------------------------------------------------- ROUTE phase
MENU_TEXT = "\n".join(" - %s (cost %d, %s): %s" %
@@ -264,8 +237,8 @@ ROUTE_SYSTEM = (
def score_route(item, resp):
c = client.content(resp)
- obj = _first_json(c, "object")
- rec = {"id": item["id"], "cat": item["cat"], "gold": item["gold"]}
+ obj = _first_json(c, "{", "}")
+ rec = {"gold": item["gold"]}
if not obj or "target" not in obj:
rec.update({"format_ok": False, "target": None, "exact": False,
"acceptable": False, "detail": ("no JSON target: %r" % c[:140])})
@@ -302,8 +275,8 @@ ORCH_SYSTEM = (
def score_orch(item, resp):
c = client.content(resp)
- plan = _first_json(c, "array")
- rec = {"id": item["id"], "required_kinds": item["required_kinds"]}
+ plan = _first_json(c, "[", "]")
+ rec = {"required_kinds": item["required_kinds"]}
if not isinstance(plan, list) or not plan:
rec.update({"format_ok": False, "coverage": False, "assign_ok": 0.0,
"ordering_ok": False, "passed": False,
@@ -361,6 +334,93 @@ def score_orch(item, resp):
})
return rec
+# ---------------------------------------------------------------- JUDGE phase
+JUDGE_SYSTEM = (
+ "You are a strict reviewer of technical work. You get a task and a candidate response to it. "
+ "Decide whether the candidate fully and correctly accomplishes the task. Judge correctness, not "
+ "style: a terse or unusual answer that is correct passes; a polished answer with a real error "
+ "fails.\n\nRespond with ONLY a single JSON object and nothing else:\n"
+ '{"verdict": "pass" or "fail", "reason": "<short>"}')
+PAIRWISE_SYSTEM = (
+ "You compare two candidate responses to the same technical task and pick the one that better "
+ "accomplishes it. Judge correctness first, then completeness; ignore style, tone and length.\n\n"
+ "Respond with ONLY a single JSON object and nothing else:\n"
+ '{"better": "A" or "B", "reason": "<short>"}')
+
+
+def judge_attempts():
+ """(attempt id, payload) per verdict item, and per pairwise item in both orders."""
+ out = []
+ for it in JUDGE:
+ if it["kind"] == "verdict":
+ out.append((it["id"], dict(it)))
+ else:
+ out.append((it["id"] + "/ab", dict(it, order="ab")))
+ out.append((it["id"] + "/ba", dict(it, order="ba", a=it["b"], b=it["a"],
+ gold={"a": "b", "b": "a"}[it["gold"]])))
+ return out
+
+
+def judge_messages(it):
+ if it["kind"] == "verdict":
+ return [{"role": "system", "content": JUDGE_SYSTEM},
+ {"role": "user", "content": "TASK:\n%s\n\nCANDIDATE:\n%s" % (it["task"], it["candidate"])}]
+ return [{"role": "system", "content": PAIRWISE_SYSTEM},
+ {"role": "user", "content": "TASK:\n%s\n\nCANDIDATE A:\n%s\n\nCANDIDATE B:\n%s"
+ % (it["task"], it["a"], it["b"])}]
+
+
+def score_judge(it, resp):
+ obj = _first_json(client.content(resp), "{", "}")
+ if it["kind"] == "verdict":
+ v = str((obj or {}).get("verdict", "")).strip().lower()
+ ok = v in ("pass", "fail")
+ return {"format_ok": ok, "verdict": v if ok else None, "gold": it["gold"],
+ "correct": ok and v == it["gold"]}
+ b = str((obj or {}).get("better", "")).strip().lower()
+ ok = b in ("a", "b")
+ return {"format_ok": ok, "pick": b if ok else None, "gold": it["gold"], "order": it["order"],
+ "pair": it["id"], "correct": ok and b == it["gold"]}
+
+
+# ---------------------------------------------------------------- RERANK phase
+RERANK_SYSTEM = (
+ "You rank search results. Given a query and candidate passages, order ALL candidate ids from most "
+ "to least relevant to what the query is looking for.\n\nRespond with ONLY a single JSON object "
+ 'and nothing else:\n{"ranking": ["<id>", "<id>", ...]}')
+
+
+def rerank_messages(it):
+ cands = "\n\n".join("[%s]\n%s" % (cid, text) for cid, text in it["candidates"].items())
+ return [{"role": "system", "content": RERANK_SYSTEM},
+ {"role": "user", "content": "QUERY:\n%s\n\nCANDIDATES:\n%s" % (it["query"], cands)}]
+
+
+def _dcg(grades):
+ return sum((2 ** g - 1) / math.log2(i + 2) for i, g in enumerate(grades))
+
+
+def score_rerank(it, resp):
+ obj = _first_json(client.content(resp), "{", "}")
+ raw = (obj or {}).get("ranking") if isinstance(obj, dict) else None
+ ids = list(it["candidates"])
+ seen = []
+ for x in raw if isinstance(raw, list) else []:
+ x = str(x).strip().strip("[]")
+ if x in ids and x not in seen:
+ seen.append(x)
+ complete = len(seen) == len(ids) and len(raw) == len(ids)
+ ranking = seen + [x for x in ids if x not in seen] # unranked ids count as last, in id order
+ rel = it["relevance"]
+ top = max(rel, key=rel.get)
+ grades = [rel.get(x, 0) for x in ranking]
+ ideal = sorted(rel.values(), reverse=True)
+ return {"format_ok": bool(seen), "complete": complete, "ranking": seen, "top": top,
+ "top1": bool(seen) and seen[0] == top, "mrr": round(1 / (ranking.index(top) + 1), 4),
+ "ndcg5": round(_dcg(grades[:5]) / _dcg(ideal[:5]), 4) if seen else 0.0,
+ "correct": bool(seen) and seen[0] == top}
+
+
# ---------------------------------------------------------------- phases
def validate():
"""Prove the dataset is well-formed before trusting any model score."""
@@ -379,104 +439,157 @@ def validate():
for a, b in it["deps"]:
if a not in it["required_kinds"] or b not in it["required_kinds"]:
print("BAD orch %s: dep (%s,%s) not both required" % (it["id"], a, b)); ok = False
- print("ROUTE items: %d ORCH items: %d" % (len(ROUTE), len(ORCH)))
+ ids = [it["id"] for it in JUDGE] + [it["id"] for it in RERANK]
+ if len(set(ids)) != len(ids):
+ print("BAD judge/rerank: duplicate ids"); ok = False
+ for it in JUDGE:
+ want = {"verdict": ("task", "candidate"), "pairwise": ("task", "a", "b")}.get(it["kind"])
+ golds = {"verdict": ("pass", "fail"), "pairwise": ("a", "b")}.get(it["kind"], ())
+ if not want or any(not it.get(k) for k in want) or it.get("gold") not in golds:
+ print("BAD judge %s: kind/fields/gold" % it["id"]); ok = False
+ for it in RERANK:
+ cids, rel = list(it["candidates"]), it["relevance"]
+ top = [c for c, g in rel.items() if g == max(rel.values())] if rel else []
+ if cids != ["c%d" % i for i in range(1, len(cids) + 1)] or not 6 <= len(cids) <= 10:
+ print("BAD rerank %s: candidate ids must be c1..cN, 6-10 of them" % it["id"]); ok = False
+ if not set(rel) <= set(cids) or len(top) != 1 or rel[top[0]] != 3 or \
+ any(g not in (1, 2, 3) for g in rel.values()):
+ print("BAD rerank %s: relevance needs grades 1-3 with exactly one 3" % it["id"]); ok = False
+ print("ROUTE %d ORCH %d JUDGE %d (%d verdict, %d pairwise) RERANK %d" % (
+ len(ROUTE), len(ORCH), len(JUDGE), sum(i["kind"] == "verdict" for i in JUDGE),
+ sum(i["kind"] == "pairwise" for i in JUDGE), len(RERANK)))
print("VALIDATION %s" % ("PASSED" if ok else "FAILED"))
return ok
-def run():
- path = jsonl_path(client.MODEL, prefix="router")
- open(path, "w").close()
- recs = []
- print("=== ROUTER BENCH vs %s (%d route + %d orch) ===\n" %
- (client.MODEL, len(ROUTE), len(ORCH)), flush=True)
- print("-- ROUTE --", flush=True)
- for it in ROUTE:
- try:
- resp, dt = client.call_model([{"role": "system", "content": ROUTE_SYSTEM},
- {"role": "user", "content": it["request"]}])
- rec = score_route(it, resp)
- rec["latency_s"] = round(dt, 1)
- rec["phase"] = "route"
- except Exception as e:
- rec = {"id": it["id"], "cat": it["cat"], "phase": "route", "format_ok": False,
- "exact": False, "acceptable": False, "detail": "ERROR %r" % e}
- recs.append(rec)
- append_jsonl(path, rec)
- print(" %-14s -> %-12s %s%s" % (it["id"], rec.get("target"),
- "OK" if rec.get("acceptable") else "MISS",
- "" if rec.get("acceptable") else " (" + (rec.get("detail","") or "")[:60] + ")"), flush=True)
- print("\n-- ORCH --", flush=True)
- for it in ORCH:
- try:
- resp, dt = client.call_model([{"role": "system", "content": ORCH_SYSTEM},
- {"role": "user", "content": it["request"]}])
- rec = score_orch(it, resp)
- rec["latency_s"] = round(dt, 1)
- rec["phase"] = "orch"
- except Exception as e:
- rec = {"id": it["id"], "phase": "orch", "format_ok": False, "passed": False,
- "detail": "ERROR %r" % e}
- recs.append(rec)
- append_jsonl(path, rec)
- print(" %-20s %s %s" % (it["id"], "PASS" if rec.get("passed") else "miss",
- "" if rec.get("passed") else (rec.get("detail","") or "")[:70]), flush=True)
- report_from(recs, client.MODEL)
- write_json(recs, client.MODEL, prefix="router")
-
-def report():
- path = jsonl_path(client.MODEL, prefix="router")
- recs = [json.loads(l) for l in open(path)]
- report_from(recs, client.MODEL)
-
-def report_from(recs, model):
- route = [r for r in recs if r.get("phase") == "route"]
- orch = [r for r in recs if r.get("phase") == "orch"]
- print("\n===================== ROUTER SUMMARY: %s =====================" % model)
+
+FAMILIES = ("route", "orch", "judge", "rerank")
+
+
+def family_items(fam):
+ """[(attempt id, payload)] for one family; payload carries its family."""
+ pairs = {"route": [(it["id"], it) for it in ROUTE], "orch": [(it["id"], it) for it in ORCH],
+ "judge": judge_attempts(), "rerank": [(it["id"], it) for it in RERANK]}[fam]
+ return [(i, dict(p, family=fam)) for i, p in pairs]
+
+
+def item_set(fam):
+ defs = {"route": [ROUTE, WORKERS, ROUTE_SYSTEM], "orch": [ORCH, WORKERS, CAPABLE, sorted(KINDS), ORCH_SYSTEM],
+ "judge": [JUDGE, JUDGE_SYSTEM, PAIRWISE_SYSTEM], "rerank": [RERANK, RERANK_SYSTEM]}[fam]
+ h = hashlib.sha256(json.dumps(defs, sort_keys=True, default=sorted).encode()).hexdigest()
+ return "router-%s@%s" % (fam, h[:12])
+
+
+def _attempt(store, lane, it, k):
+ fam = it["family"]
+ if fam == "route":
+ msgs = [{"role": "system", "content": ROUTE_SYSTEM}, {"role": "user", "content": it["request"]}]
+ cat, grade = "route/" + it["cat"], lambda resp: (lambda r: dict(r, correct=r["acceptable"]))(score_route(it, resp))
+ elif fam == "orch":
+ msgs = [{"role": "system", "content": ORCH_SYSTEM}, {"role": "user", "content": it["request"]}]
+ cat, grade = "orch", lambda resp: (lambda r: dict(r, correct=r["passed"]))(score_orch(it, resp))
+ elif fam == "judge":
+ msgs = judge_messages(it)
+ cat = ("judge/" if it["kind"] == "verdict" else "pairwise/") + it["cat"]
+ grade = lambda resp: score_judge(it, resp) # noqa: E731
+ else:
+ msgs, cat, grade = rerank_messages(it), "rerank/" + it["cat"], (lambda resp: score_rerank(it, resp))
+ iid = it["id"] + ("/" + it["order"] if fam == "judge" and it["kind"] == "pairwise" else "")
+ results.call_attempt(store, lane, iid, k, cat, msgs, grade)
+
+
+def report_from(rows):
+ """Router axes over graded rows (infra rows are counted apart, never scored as a miss)."""
+ graded = [r for r in rows if r.get("correct") is not None]
+ route = [r for r in graded if r["category"].startswith("route/")]
+ orch = [r for r in graded if r["category"] == "orch"]
+ print("\nROUTER: %d graded, %d infra" % (len(graded), len(rows) - len(graded)))
if route:
n = len(route)
- fmt = sum(1 for r in route if r.get("format_ok"))
- exact = sum(1 for r in route if r.get("exact"))
acc = sum(1 for r in route if r.get("acceptable"))
- priv = sum(1 for r in route if r.get("priv_violation"))
+ exact = sum(1 for r in route if r.get("exact"))
+ fmt = sum(1 for r in route if r.get("format_ok"))
over = sum(1 for r in route if (r.get("esc_err") or 0) > 0)
under = sum(1 for r in route if (r.get("esc_err") or 0) < 0)
- mae = round(sum(abs(r.get("esc_err") or 0) for r in route) / n, 2)
- lat = round(sum(r.get("latency_s") or 0 for r in route) / n, 1)
+ mae = sum(abs(r.get("esc_err") or 0) for r in route) / n
+ priv = sum(1 for r in route if r.get("priv_violation"))
print("ROUTE acceptable %d/%d (%.0f%%) exact %d/%d format %d/%d" %
- (acc, n, 100*acc/n, exact, n, fmt, n))
- print(" over-escalate %d under-escalate %d |esc| mean %.2f privacy-violations %d avg lat %.1fs" %
- (over, under, mae, priv, lat))
- # per-category acceptable
- cats = {}
- for r in route: cats.setdefault(r["cat"], []).append(r)
- print(" by-cat: " + " ".join("%s %d/%d" %
- (c, sum(1 for r in rs if r.get("acceptable")), len(rs)) for c, rs in sorted(cats.items())))
+ (acc, n, 100 * acc / n, exact, n, fmt, n))
+ print(" over-escalate %d under-escalate %d |esc| mean %.2f privacy-violations %d" %
+ (over, under, mae, priv))
+ judge = [r for r in graded if r["category"].startswith("judge/")]
+ pair = [r for r in graded if r["category"].startswith("pairwise/")]
+ rer = [r for r in graded if r["category"].startswith("rerank/")]
+ if judge:
+ n, acc = len(judge), sum(1 for r in judge if r.get("correct"))
+ fails = [r for r in judge if r.get("gold") == "fail"]
+ passes = [r for r in judge if r.get("gold") == "pass"]
+ print("JUDGE accuracy %d/%d (%.0f%%) false-pass %d/%d false-fail %d/%d format %d/%d" % (
+ acc, n, 100 * acc / n, sum(1 for r in fails if r.get("verdict") == "pass"), len(fails),
+ sum(1 for r in passes if r.get("verdict") == "fail"), len(passes),
+ sum(1 for r in judge if r.get("format_ok")), n))
+ if pair:
+ n, acc = len(pair), sum(1 for r in pair if r.get("correct"))
+ by = {}
+ for r in pair:
+ by.setdefault((r.get("pair"), r["sample_idx"]), {})[r.get("order")] = r
+ both = [v for v in by.values() if len(v) == 2]
+ consistent = sum(1 for v in both if v["ab"].get("correct") and v["ba"].get("correct"))
+ picks_a = sum(1 for r in pair if r.get("pick") == "a")
+ print("PAIR accuracy %d/%d (%.0f%%) right in both orders %d/%d picked first-shown %d/%d" % (
+ acc, n, 100 * acc / n, consistent, len(both), picks_a, n))
+ if rer:
+ n = len(rer)
+ print("RERANK top-1 %d/%d (%.0f%%) MRR %.2f NDCG@5 %.2f complete rankings %d/%d" % (
+ sum(1 for r in rer if r.get("top1")), n, 100 * sum(1 for r in rer if r.get("top1")) / n,
+ sum(r.get("mrr") or 0 for r in rer) / n, sum(r.get("ndcg5") or 0 for r in rer) / n,
+ sum(1 for r in rer if r.get("complete")), n))
if orch:
n = len(orch)
p = sum(1 for r in orch if r.get("passed"))
cov = sum(1 for r in orch if r.get("coverage"))
- aok = round(sum(r.get("assign_ok") or 0 for r in orch) / n, 2)
+ aok = sum(r.get("assign_ok") or 0 for r in orch) / n
ord_ok = sum(1 for r in orch if r.get("ordering_ok"))
priv = sum(1 for r in orch if r.get("priv_violation"))
- lat = round(sum(r.get("latency_s") or 0 for r in orch) / n, 1)
- print("ORCH pass %d/%d (%.0f%%) coverage %d/%d mean-assign %.2f ordering %d/%d privacy-viol %d avg lat %.1fs" %
- (p, n, 100*p/n, cov, n, aok, ord_ok, n, priv, lat))
- print("=" * 70)
-
+ print("ORCH pass %d/%d (%.0f%%) coverage %d/%d mean-assign %.2f ordering %d/%d "
+ "privacy-viol %d" % (p, n, 100 * p / n, cov, n, aok, ord_ok, n, priv))
-def main():
- mode = sys.argv[1] if len(sys.argv) > 1 else "validate"
- if mode == "validate":
- sys.exit(0 if validate() else 1)
- elif mode == "run":
- run()
- elif mode == "report":
- report()
- else:
- print(f"usage: python bench.py router [validate|run|report]")
- sys.exit(1)
+def main(argv=None):
+ ap = argparse.ArgumentParser(prog="bench.py router")
+ sub = ap.add_subparsers(dest="cmd")
+ sub.add_parser("validate")
+ sub.add_parser("report")
+ rp = sub.add_parser("run")
+ results.add_run_args(rp)
+ rp.add_argument("--families", default=",".join(FAMILIES), help="comma list of: " + ",".join(FAMILIES))
+ a = ap.parse_args(sys.argv[1:] if argv is None else argv)
+ if a.cmd == "run":
+ fams = [f for f in a.families.split(",") if f]
+ if set(fams) - set(FAMILIES):
+ raise SystemExit("unknown families: %s" % ",".join(sorted(set(fams) - set(FAMILIES))))
+ if a.resume:
+ with open(a.resume.rstrip("/") + "/run.json") as f:
+ fams = [json.load(f)["item_set"].split("@")[0].replace("router-", "")]
+ want = {x for x in a.items.split(",") if x}
+ for fam in fams:
+ items = family_items(fam)
+ sel = want & {i for i, _ in items}
+ if want and not sel and not a.resume:
+ continue
+ plan = lambda _args, fam=fam, items=items: (item_set(fam), items) # noqa: E731
+ store, summary = results.run_attempts(
+ INSTRUMENT, dict(results.run_args(a), items=sorted(sel) or None, family=fam), plan,
+ _attempt, resume=a.resume)
+ report_from(store.rows())
+ if summary["stopped"]:
+ sys.exit(3)
+ sys.exit(0)
+ if a.cmd == "report":
+ rows = results.load_rows(INSTRUMENT, lane_mod.current().lane_id)
+ results.print_summary(results.summarize(rows))
+ return report_from(rows)
+ sys.exit(0 if validate() else 1)
if __name__ == "__main__":
- main()
\ No newline at end of file
+ main()
diff --git a/bench/tasks/router_sets.py b/bench/tasks/router_sets.py
new file mode 100644
index 0000000..0e84636
--- /dev/null
+++ b/bench/tasks/router_sets.py
@@ -0,0 +1,1032 @@
+"""Gold-labelled data for the router instrument's JUDGE and RERANK sets.
+
+JUDGE (32 items) measures a small model acting as a judge of computing work.
+ 24 "verdict" items: does `candidate` meet `task`? gold "pass" | "fail" (12 / 12).
+ 8 "pairwise" items: which of `a` / `b` better meets `task`? gold "a" | "b" (4 / 4); the
+ harness also runs each with a/b swapped to cancel position bias.
+ Categories: code (Python, Go, Rust), shell, sql, logs (is this summary faithful to the
+ lines?), config (nginx, systemd, sshd, YAML) and answer (factual sysadmin answers).
+ Fails are near-misses (negative-slice off-by-one, `$` matching before a trailing newline,
+ in-place delete while ranging, integer division, `-mtime -7`, `grep -c` under errexit,
+ COUNT(bool), a join missing its key, an invented count/event, proxy_pass without a URI,
+ cron's day-of-month OR day-of-week rule, a .255 that isn't a broadcast address). Passes
+ include terse or unusual-but-correct solutions, so surface pattern matching loses.
+
+RERANK (16 items) measures a small model acting as a reranker: order `candidates` by
+ relevance to `query`. `relevance` grades 0-3 (omitted ids are 0) with exactly one id at the
+ top grade. Every item carries lexical hard negatives (share the query's keywords, don't
+ answer it) and at least one relevant candidate with low keyword overlap.
+
+How the gold labels were verified (2026-10-12, recorded per item in "why"):
+ - Every code/shell/SQL verdict and pairwise item was executed from this module's exact
+ text in a fresh temp dir with tiny fixtures: Python with python3 3.9, Go with go 1.27,
+ Rust with rustc 1.96, shell with macOS bash 3.2 + BSD userland AND bash 5 + GNU
+ userland (Debian python:3.12-slim container), SQL with sqlite3 AND PostgreSQL 16.
+ - Config: the nginx item ran in nginx:1.27-alpine against an echo backend; the sshd item
+ via `sshd -T` plus a throwaway loopback sshd (offered auth methods); YAML via PyYAML 6.
+ The systemd item follows systemd.service(5) (not run: no systemd on the Mac).
+ - Log summaries were checked claim-by-claim against the quoted lines; answers against
+ crontab(5), ssh(1)/ssh_config(5), Python's ipaddress module and shell semantics.
+ - Rerank grades are hand-assigned; candidates' factual content was checked against the
+ relevant man pages / language docs.
+Scoring is deterministic: no model judges another.
+"""
+
+JUDGE = [
+ # ============================================================ verdict: code
+ {"id": "j-py-chunks", "cat": "code", "kind": "verdict",
+ "task": "Python: write `chunks(xs, n)` that splits the list `xs` into consecutive sub-lists of "
+ "length `n` (n >= 1) and returns them as a list of lists; the last sub-list may be "
+ "shorter. Examples: chunks([1, 2, 3, 4, 5], 2) == [[1, 2], [3, 4], [5]] and "
+ "chunks([], 3) == [].",
+ "candidate": """from itertools import islice
+
+def chunks(xs, n):
+ it = iter(xs)
+ return list(iter(lambda: list(islice(it, n)), []))
+""",
+ "gold": "pass",
+ "why": "iter(callable, sentinel) pulls n-item slices until an empty list; executed: matches a "
+ "reference on all lists of length 0-12 for n=1-6, incl. both examples."},
+
+ {"id": "j-py-tail", "cat": "code", "kind": "verdict",
+ "task": "Python: write `tail(path, n)` that returns the last `n` lines of a text file as a "
+ "list of strings without their newline characters, like `tail -n`. n >= 1. If the "
+ "file has fewer than n lines, return all of its lines.",
+ "candidate": """def tail(path, n):
+ with open(path) as f:
+ lines = f.read().splitlines()
+ return lines[len(lines) - n:]
+""",
+ "gold": "fail",
+ "why": "when n > len(lines) the start index goes negative and slices from the end; executed: "
+ "3-line file with n=5 returns 2 lines, not 3."},
+
+ {"id": "j-py-ipv4", "cat": "code", "kind": "verdict",
+ "task": "Python: write `is_ipv4(s)` that returns True only if the string `s` is exactly a "
+ "dotted-quad IPv4 address (four decimal numbers 0-255 separated by dots) and False "
+ "for anything else, including strings with leading or trailing whitespace or "
+ "newlines. Leading zeros in an octet may be accepted.",
+ "candidate": r"""import re
+
+def is_ipv4(s):
+ if not re.match(r"^\d{1,3}(\.\d{1,3}){3}$", s):
+ return False
+ return all(int(p) <= 255 for p in s.split("."))
+""",
+ "gold": "fail",
+ "why": "`$` also matches just before a trailing newline and int() strips it; executed: "
+ "is_ipv4('10.0.0.1\\n') is True (other cases like 256.1.1.1 / 1.2.3 are right)."},
+
+ {"id": "j-go-lowerbound", "cat": "code", "kind": "verdict",
+ "task": "Go: write `func LowerBound(a []int, x int) int` that, for a slice `a` sorted in "
+ "ascending order (duplicates allowed), returns the index of the first element >= x, "
+ "or len(a) if there is none. It must run in O(log n). Don't use the sort or slices "
+ "packages.",
+ "candidate": """func LowerBound(a []int, x int) int {
+ lo, n := 0, len(a)
+ for n > 0 {
+ half := n / 2
+ if a[lo+half] < x {
+ lo += half + 1
+ n -= half + 1
+ } else {
+ n = half
+ }
+ }
+ return lo
+}
+""",
+ "gold": "pass",
+ "why": "count-based (std::lower_bound-style) binary search; executed: matches a linear scan "
+ "for every sorted slice over {0..3} of length 0-7 and every x in -1..4."},
+
+ {"id": "j-go-dropempty", "cat": "code", "kind": "verdict",
+ "task": "Go: write `func DropEmpty(xs []string) []string` that returns the elements of xs that "
+ "are not the empty string, in their original order. Reusing xs's backing array is "
+ "fine.",
+ "candidate": """func DropEmpty(xs []string) []string {
+ for i, s := range xs {
+ if s == "" {
+ xs = append(xs[:i], xs[i+1:]...)
+ }
+ }
+ return xs
+}
+""",
+ "gold": "fail",
+ "why": "deleting while ranging skips the element shifted into slot i; executed: "
+ "[a \"\" \"\" b] -> [a \"\" b], and [\"\" \"\" \"\"] panics (slice bounds out of range)."},
+
+ {"id": "j-rs-median", "cat": "code", "kind": "verdict",
+ "task": "Rust: write `fn median(v: &mut Vec<i64>) -> Option<f64>` that returns None for an "
+ "empty vector and otherwise the median. For an even number of elements the median is "
+ "the mean of the two middle values, so [1, 2] gives 1.5. Sorting v in place is "
+ "allowed.",
+ "candidate": """fn median(v: &mut Vec<i64>) -> Option<f64> {
+ if v.is_empty() {
+ return None;
+ }
+ v.sort_unstable();
+ let n = v.len();
+ if n % 2 == 1 {
+ Some(v[n / 2] as f64)
+ } else {
+ Some(((v[n / 2 - 1] + v[n / 2]) / 2) as f64)
+ }
+}
+""",
+ "gold": "fail",
+ "why": "the even case divides as i64 before converting; executed (rustc): median([1, 2]) = "
+ "1.0, median([3, 1, 4, 2]) = 2.0 instead of 1.5 / 2.5."},
+
+ {"id": "j-rs-wordfreq", "cat": "code", "kind": "verdict",
+ "task": "Rust: write `fn word_freq(text: &str) -> HashMap<String, usize>` that counts words, "
+ "where words are separated by any whitespace and counted case-insensitively (keys "
+ "are lowercase). Example: \"The cat\\tthe\\n\" gives {\"the\": 2, \"cat\": 1}. Assume "
+ "`use std::collections::HashMap;` is in scope.",
+ "candidate": """fn word_freq(text: &str) -> HashMap<String, usize> {
+ text.split_whitespace()
+ .map(str::to_lowercase)
+ .fold(HashMap::new(), |mut m, w| {
+ *m.entry(w).or_default() += 1;
+ m
+ })
+}
+""",
+ "gold": "pass",
+ "why": "fold over split_whitespace with lowercase keys; executed (rustc): the example, empty "
+ "input -> {}, and mixed tabs/newlines/repeated spaces all correct."},
+
+ # ============================================================ verdict: shell
+ {"id": "j-sh-find-mtime", "cat": "shell", "kind": "verdict",
+ "task": "Shell (GNU findutils): delete the regular files under /var/log/app whose names end in "
+ ".log and that were last modified more than 7 days ago. Stay on that filesystem and "
+ "touch nothing else.",
+ "candidate": "find /var/log/app -xdev -type f -name '*.log' -mtime -7 -delete",
+ "gold": "fail",
+ "why": "-mtime -7 selects files modified LESS than 7 days ago (needs +7); executed (BSD and GNU "
+ "find): deletes the 1- and 3-day-old logs, keeps the 10- and 30-day-old ones."},
+
+ {"id": "j-sh-rm-r", "cat": "shell", "kind": "verdict",
+ "task": "Bash, in a CI script that runs under `set -e`: remove the directory named in "
+ "$BUILD_DIR and everything below it. It must never prompt (not even for read-only "
+ "files) and must not abort the script when the directory doesn't exist yet.",
+ "candidate": "rm -r -- \"$BUILD_DIR\"",
+ "gold": "fail",
+ "why": "without -f, a missing dir is an error (exit 1) that set -e turns into an abort, and rm "
+ "prompts for write-protected files on a tty; executed: script stops before its next line."},
+
+ {"id": "j-sh-top-ips", "cat": "shell", "kind": "verdict",
+ "task": "Shell: access.log is in nginx's default combined format (the client IP is the first "
+ "space-separated field). Print the 3 client IPs with the most requests, highest "
+ "first, one per line as '<count> <ip>'.",
+ "candidate": "awk '{n[$1]++} END {for (ip in n) print n[ip], ip}' access.log | sort -rn | head -n 3",
+ "gold": "pass",
+ "why": "awk tally instead of the usual sort|uniq -c; executed on a 6-IP fixture (BSD and GNU "
+ "userland): prints '7 ...', '5 ...', '3 ...' in the right order."},
+
+ {"id": "j-sh-grep-n", "cat": "shell", "kind": "verdict",
+ "task": "Shell: print every line of hosts.txt prefixed with its 1-based line number and a "
+ "colon, e.g. '1:alpha'. Blank lines must be numbered too, and the file's last line "
+ "may lack a trailing newline but must still be printed.",
+ "candidate": "grep -n '' hosts.txt",
+ "gold": "pass",
+ "why": "the empty pattern matches every line, incl. blank ones and an unterminated last line; "
+ "executed (BSD and GNU grep): '1:alpha','2:','3:gamma' for a file ending without \\n."},
+
+ {"id": "j-sh-grep-c-errexit", "cat": "shell", "kind": "verdict",
+ "task": "Bash script running under `set -euo pipefail`: store the number of lines in app.log "
+ "that contain ERROR in a variable `count`, print 'errors: <count>', and carry on with "
+ "the rest of the script. app.log may contain no ERROR lines at all, in which case it "
+ "must print 'errors: 0' and continue.",
+ "candidate": """count=$(grep -c ERROR app.log)
+echo "errors: $count"
+""",
+ "gold": "fail",
+ "why": "grep -c prints 0 but exits 1 on no match, and the assignment takes that status, so "
+ "errexit kills the script; executed (bash 3.2 and 5.2): nothing printed, exit 1."},
+
+ # ============================================================ verdict: sql
+ {"id": "j-sql-count-bool", "cat": "sql", "kind": "verdict",
+ "task": "SQL (SQLite or PostgreSQL). Tables: customers(id INTEGER PRIMARY KEY, name TEXT) and "
+ "orders(id INTEGER PRIMARY KEY, customer_id INTEGER, status TEXT). For every customer "
+ "who has at least 2 orders with status 'paid', return their id, their name and the "
+ "number of their paid orders as paid_orders.",
+ "candidate": """SELECT c.id, c.name, COUNT(o.status = 'paid') AS paid_orders
+FROM customers c
+JOIN orders o ON o.customer_id = c.id
+GROUP BY c.id, c.name
+HAVING COUNT(o.status = 'paid') >= 2;
+""",
+ "gold": "fail",
+ "why": "COUNT counts non-NULL values and false/0 is non-NULL, so it counts all orders; "
+ "executed (sqlite3 and Postgres 16): a customer with 1 paid + 2 refunded shows up as 3."},
+
+ {"id": "j-sql-never-ordered", "cat": "sql", "kind": "verdict",
+ "task": "SQL (SQLite or PostgreSQL). Tables: customers(id INTEGER PRIMARY KEY, name TEXT) and "
+ "orders(id INTEGER PRIMARY KEY, customer_id INTEGER NULL, total NUMERIC); "
+ "customer_id is NULL for guest checkouts, and two customers can share a name. Return "
+ "the id and name of every customer who has never placed an order.",
+ "candidate": """SELECT c.id, c.name
+FROM customers c
+LEFT JOIN orders o ON o.customer_id = c.id
+GROUP BY c.id, c.name
+HAVING COUNT(o.id) = 0;
+""",
+ "gold": "pass",
+ "why": "anti-join via LEFT JOIN + COUNT of the nullable side; executed (sqlite3 and Postgres "
+ "16) with guest orders and a duplicate name: returns exactly the 2 order-less customers."},
+
+ {"id": "j-sql-latest", "cat": "sql", "kind": "verdict",
+ "task": "SQL (SQLite or PostgreSQL). Table readings(sensor_id INTEGER, ts TEXT, value REAL); ts "
+ "is an ISO-8601 'YYYY-MM-DD HH:MM:SS' string and is unique per sensor, but all "
+ "sensors report on the same schedule, so the same ts appears for many sensors. Return "
+ "one row per sensor: sensor_id and the value of its most recent reading.",
+ "candidate": """SELECT r.sensor_id, r.value
+FROM readings r
+WHERE NOT EXISTS (
+ SELECT 1 FROM readings newer
+ WHERE newer.sensor_id = r.sensor_id AND newer.ts > r.ts
+);
+""",
+ "gold": "pass",
+ "why": "correlated NOT EXISTS keeps each sensor's newest row; executed (sqlite3 and Postgres "
+ "16) on shared timestamps and a sensor with one reading: one correct row per sensor."},
+
+ # ============================================================ verdict: logs
+ {"id": "j-log-ssh-count", "cat": "logs", "kind": "verdict",
+ "task": "Summarize this /var/log/auth.log excerpt in one or two sentences for the on-call "
+ "channel. The summary must be faithful: every claim supported by the lines, no "
+ "invented counts or events.\n\n"
+ "Oct 11 02:14:03 web1 sshd[30411]: Failed password for root from 203.0.113.7 port 51022 ssh2\n"
+ "Oct 11 02:14:07 web1 sshd[30411]: Failed password for root from 203.0.113.7 port 51022 ssh2\n"
+ "Oct 11 02:14:12 web1 sshd[30413]: Failed password for invalid user admin from 203.0.113.7 port 51040 ssh2\n"
+ "Oct 11 02:14:15 web1 sshd[30415]: Failed password for root from 198.51.100.23 port 40112 ssh2\n"
+ "Oct 11 02:14:20 web1 sshd[30413]: Connection closed by invalid user admin 203.0.113.7 port 51040 [preauth]\n"
+ "Oct 11 02:15:41 web1 sshd[30420]: Accepted publickey for deploy from 192.0.2.10 port 60218 ssh2: ED25519 SHA256:kq3VbR0x7Lw2mJbW0mS9a6YtD4c2r1Hk8EzQ5uN1pTo\n"
+ "Oct 11 02:15:41 web1 sshd[30420]: pam_unix(sshd:session): session opened for user deploy(uid=1001) by (uid=0)",
+ "candidate": "Between 02:14:03 and 02:14:15, 203.0.113.7 made 4 failed password attempts "
+ "(against root and the nonexistent user admin) and 198.51.100.23 failed once "
+ "against root; at 02:15:41 deploy logged in with a public key from 192.0.2.10.",
+ "gold": "fail",
+ "why": "203.0.113.7 has 3 failed attempts (2 root + 1 admin), not 4; 4 is the total across both "
+ "IPs. Everything else is supported."},
+
+ {"id": "j-log-oom", "cat": "logs", "kind": "verdict",
+ "task": "Summarize these journal lines from db1 in one or two sentences for an incident "
+ "ticket. The summary must be faithful: every claim supported by the lines, no "
+ "invented counts or events.\n\n"
+ "Oct 11 03:12:05 db1 kernel: postgres invoked oom-killer: gfp_mask=0x140cca(GFP_HIGHUSER_MOVABLE|__GFP_COMP), order=0, oom_score_adj=0\n"
+ "Oct 11 03:12:05 db1 kernel: Out of memory: Killed process 2211 (postgres) total-vm:9123456kB, anon-rss:6801232kB, file-rss:0kB, shmem-rss:131072kB, UID:113 pgtables:14212kB oom_score_adj:0\n"
+ "Oct 11 03:12:05 db1 postgres[2190]: LOG: server process (PID 2211) was terminated by signal 9: Killed\n"
+ "Oct 11 03:12:05 db1 postgres[2190]: LOG: terminating any other active server processes\n"
+ "Oct 11 03:12:06 db1 postgres[2190]: LOG: all server processes terminated; reinitializing\n"
+ "Oct 11 03:12:06 db1 postgres[2230]: LOG: database system was interrupted; last known up at 2026-10-11 03:07:44 UTC\n"
+ "Oct 11 03:12:07 db1 postgres[2230]: LOG: database system was not properly shut down; automatic recovery in progress\n"
+ "Oct 11 03:12:09 db1 postgres[2230]: LOG: redo done at 0/5A1C3F8\n"
+ "Oct 11 03:12:10 db1 postgres[2190]: LOG: database system is ready to accept connections",
+ "candidate": "03:12:05: the kernel OOM killer SIGKILLed one PostgreSQL backend (PID 2211). The "
+ "postmaster (PID 2190) stayed up, terminated the other sessions, ran crash "
+ "recovery and was accepting connections again at 03:12:10, roughly 5 s of outage.",
+ "gold": "pass",
+ "why": "each claim maps to a line: OOM kill of 2211 + signal 9, 2190 logs throughout, "
+ "'terminating any other active server processes', recovery/redo, ready at 03:12:10."},
+
+ {"id": "j-log-raid", "cat": "logs", "kind": "verdict",
+ "task": "Summarize these kernel lines from nas1 in one or two sentences for the hardware log. "
+ "The summary must be faithful: every claim supported by the lines, no invented "
+ "counts or events.\n\n"
+ "Oct 10 04:10:31 nas1 kernel: ata3.00: exception Emask 0x0 SAct 0x40000 SErr 0x0 action 0x0\n"
+ "Oct 10 04:10:31 nas1 kernel: ata3.00: failed command: READ FPDMA QUEUED\n"
+ "Oct 10 04:10:31 nas1 kernel: blk_update_request: I/O error, dev sdb, sector 1953520 op 0x0:(READ) flags 0x0 phys_seg 1 prio class 0\n"
+ "Oct 10 04:10:32 nas1 kernel: md/raid1:md0: Disk failure on sdb1, disabling device.\n"
+ "Oct 10 04:10:32 nas1 kernel: md/raid1:md0: Operation continuing on 1 devices.\n"
+ "Oct 10 04:10:40 nas1 kernel: ata3: hard resetting link\n"
+ "Oct 10 04:10:45 nas1 kernel: ata3: SATA link up 6.0 Gbps (SStatus 133 SControl 300)",
+ "candidate": "At 04:10:31 a read from sdb failed with an I/O error; a second later md disabled "
+ "sdb1, leaving the RAID1 array md0 running on one device. The ata3 link was "
+ "hard-reset and came back up at 04:10:45, but nothing shows sdb1 being re-added "
+ "or resynced.",
+ "gold": "pass",
+ "why": "every claim is in the lines (read I/O error on sdb, md0 disabling sdb1 and continuing "
+ "on 1 device, ata3 reset/link up); it doesn't claim a rebuild."},
+
+ # ============================================================ verdict: config
+ {"id": "j-cfg-nginx-prefix", "cat": "config", "kind": "verdict",
+ "task": "nginx: inside an existing server block, add a location that proxies every request "
+ "under /api/ to the backend at 127.0.0.1:8080 with the /api prefix stripped: a "
+ "request for /api/users?id=3 must reach the backend as /users?id=3.",
+ "candidate": """location /api/ {
+ proxy_pass http://127.0.0.1:8080;
+ proxy_set_header Host $host;
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+}
+""",
+ "gold": "fail",
+ "why": "proxy_pass without a URI part forwards the original URI unchanged (needs a trailing "
+ "'/'); executed in nginx 1.27: backend sees /api/users?id=3."},
+
+ {"id": "j-cfg-systemd", "cat": "config", "kind": "verdict",
+ "task": "systemd: write a unit for the long-running program /opt/app/worker. It must start at "
+ "boot once the network is actually online, be restarted whenever it exits for any "
+ "reason (including a clean exit with status 0), and wait 5 seconds before each "
+ "restart.",
+ "candidate": """[Unit]
+Description=app worker
+Wants=network-online.target
+After=network-online.target
+
+[Service]
+ExecStart=/opt/app/worker
+Restart=always
+RestartSec=5
+
+[Install]
+WantedBy=multi-user.target
+""",
+ "gold": "pass",
+ "why": "per systemd.service(5)/systemd.special(7): Restart=always covers clean exits, "
+ "RestartSec=5, Wants+After network-online.target, WantedBy for boot (not executed)."},
+
+ {"id": "j-cfg-sshd-authmethods", "cat": "config", "kind": "verdict",
+ "task": "OpenSSH sshd_config: nobody may log in with a password (including keyboard-"
+ "interactive / PAM password prompts), root may not log in at all by any method, and "
+ "every other user must still be able to log in with an SSH key. Give the directives "
+ "to add.",
+ "candidate": """PermitRootLogin no
+AuthenticationMethods publickey
+""",
+ "gold": "pass",
+ "why": "AuthenticationMethods publickey makes publickey the only method that can complete auth "
+ "(sshd_config(5)); `sshd -T` parses it, and a loopback sshd with it offers only "
+ "'(publickey)' vs '(publickey,password,keyboard-interactive)' without it."},
+
+ # ============================================================ verdict: answer
+ {"id": "j-ans-cron-dow", "cat": "answer", "kind": "verdict",
+ "task": "Answer correctly: on what schedule does the crontab line "
+ "`30 2 1-7 * 1 /usr/local/sbin/patch-reboot` run with standard Vixie cron / cronie?",
+ "candidate": "At 02:30 on the first Monday of every month: day-of-month 1-7 restricted to "
+ "day-of-week 1 (Monday) picks the Monday that falls in the first seven days.",
+ "gold": "fail",
+ "why": "crontab(5): when both day fields are restricted the job runs when EITHER matches, i.e. "
+ "02:30 on days 1-7 of every month AND every Monday."},
+
+ {"id": "j-ans-ssh-L", "cat": "answer", "kind": "verdict",
+ "task": "Answer correctly: what does `ssh -N -L 15432:db.internal:5432 admin@bastion` do?",
+ "candidate": "It logs in to bastion as admin without running a remote command (-N) and listens "
+ "on local port 15432 (loopback only, by default). Each connection to that port is "
+ "carried through the SSH session, and bastion opens a TCP connection to "
+ "db.internal:5432 (db.internal is resolved by bastion, not by your machine). So "
+ "`psql -h localhost -p 15432` reaches the database.",
+ "gold": "pass",
+ "why": "matches ssh(1) -L/-N and ssh_config(5) GatewayPorts=no default; the forward target is "
+ "resolved and connected from the server side."},
+
+ {"id": "j-ans-cidr", "cat": "answer", "kind": "verdict",
+ "task": "Answer correctly: in the subnet 10.0.12.0/22, can the address 10.0.13.255 be assigned "
+ "to a host?",
+ "candidate": "No. 10.0.13.255 ends in .255, and a .255 address is always the broadcast address "
+ "of its network, so it can't be given to a host.",
+ "gold": "fail",
+ "why": "the /22 spans 10.0.12.0-10.0.15.255; its broadcast is 10.0.15.255 and 10.0.13.255 is an "
+ "ordinary host (checked with Python ipaddress)."},
+
+ # ============================================================ pairwise
+ {"id": "j-pw-py-intervals", "cat": "code", "kind": "pairwise",
+ "task": "Python: write `merge(intervals)` that takes a list of [start, end] integer pairs "
+ "(inclusive, start <= end, in any order) and returns the merged list sorted by start, "
+ "combining intervals that overlap or share an endpoint: "
+ "merge([[5, 6], [1, 3], [3, 4]]) == [[1, 4], [5, 6]].",
+ "a": """def merge(intervals):
+ out = []
+ for s, e in sorted(intervals):
+ if out and s <= out[-1][1]:
+ out[-1][1] = max(out[-1][1], e)
+ else:
+ out.append([s, e])
+ return out
+""",
+ "b": """def merge(intervals):
+ out = []
+ for s, e in sorted(intervals):
+ if out and s <= out[-1][1]:
+ out[-1][1] = e
+ else:
+ out.append([s, e])
+ return out
+""",
+ "gold": "a",
+ "why": "b overwrites the end instead of taking the max; executed: b turns [[1, 10], [2, 3]] "
+ "into [[1, 3]]; a matches a brute-force reference on 3000 random inputs."},
+
+ {"id": "j-pw-go-countlines", "cat": "code", "kind": "pairwise",
+ "task": "Go: write `func CountLines(path string) (int, error)` that returns the number of lines "
+ "in a text file, where a final line without a trailing newline still counts. Some "
+ "lines in these files are over 1 MB long. Return an error if reading fails.",
+ "a": """func CountLines(path string) (int, error) {
+ f, err := os.Open(path)
+ if err != nil {
+ return 0, err
+ }
+ defer f.Close()
+ sc := bufio.NewScanner(f)
+ n := 0
+ for sc.Scan() {
+ n++
+ }
+ return n, nil
+}
+""",
+ "b": """func CountLines(path string) (int, error) {
+ f, err := os.Open(path)
+ if err != nil {
+ return 0, err
+ }
+ defer f.Close()
+ r := bufio.NewReader(f)
+ n := 0
+ for {
+ line, err := r.ReadString('\\n')
+ if len(line) > 0 {
+ n++
+ }
+ if err == io.EOF {
+ return n, nil
+ }
+ if err != nil {
+ return n, err
+ }
+ }
+}
+""",
+ "gold": "b",
+ "why": "Scanner's default 64 KiB token limit stops at the long line and a never checks "
+ "sc.Err(); executed: 3 lines with a 2 MB middle line -> a returns (1, nil), b returns 3."},
+
+ {"id": "j-pw-sh-ssh-loop", "cat": "shell", "kind": "pairwise",
+ "task": "Bash: hosts.txt lists one hostname per line (every line ends with a newline). For each "
+ "host, run `uptime` on it over SSH (key auth is already set up) and print the "
+ "result, so you get one uptime line per host.",
+ "a": """while read -r host; do
+ printf '%s: ' "$host"
+ ssh "$host" uptime
+done < hosts.txt
+""",
+ "b": """while read -r host; do
+ printf '%s: ' "$host"
+ ssh -n "$host" uptime
+done < hosts.txt
+""",
+ "gold": "b",
+ "why": "without -n ssh reads (and forwards) the loop's stdin, eating the remaining hostnames "
+ "(BashFAQ 89, ssh(1) -n); reproduced with a stdin-reading ssh stub: a does 1 host, b all 3."},
+
+ {"id": "j-pw-sh-distinct", "cat": "shell", "kind": "pairwise",
+ "task": "Bash: data.tsv is tab-separated, has no header, and its rows are in no particular "
+ "order. Print each distinct value of the third column exactly once.",
+ "a": "sort -t$'\\t' -k3,3 -u data.tsv | cut -f3",
+ "b": "awk -F'\\t' '{print $3}' data.tsv | uniq",
+ "gold": "a",
+ "why": "uniq only collapses ADJACENT duplicates; a's sort -u on key 3 keeps one row per key. "
+ "Executed (BSD and GNU): b repeats values from unsorted rows, a prints each once."},
+
+ {"id": "j-pw-sql-join-key", "cat": "sql", "kind": "pairwise",
+ "task": "SQL (SQLite or PostgreSQL). Table deployments(service TEXT, deployed_at TEXT, "
+ "version TEXT). Deployments go out in batches, so many services share the same "
+ "deployed_at value; deployed_at is unique per service. Return each service with the "
+ "version it is currently running (the version from its most recent deployment).",
+ "a": """SELECT d.service, d.version
+FROM deployments d
+JOIN (SELECT service, MAX(deployed_at) AS latest
+ FROM deployments GROUP BY service) m
+ ON d.deployed_at = m.latest;
+""",
+ "b": """SELECT d.service, d.version
+FROM deployments d
+JOIN (SELECT service, MAX(deployed_at) AS latest
+ FROM deployments GROUP BY service) m
+ ON d.service = m.service AND d.deployed_at = m.latest;
+""",
+ "gold": "b",
+ "why": "a's join lacks the service key, so a service's older row matches another service's "
+ "latest timestamp; executed (sqlite3 and Postgres 16): a returns 6 rows incl. a stale "
+ "version and duplicates, b the correct 3."},
+
+ {"id": "j-pw-log-backup", "cat": "logs", "kind": "pairwise",
+ "task": "Summarize these lines from backup1 for the morning report in two sentences or fewer. "
+ "Be faithful: every claim supported by the lines, no invented events.\n\n"
+ "Oct 12 02:00:01 backup1 CRON[8812]: (root) CMD (/usr/local/sbin/nightly-backup.sh)\n"
+ "Oct 12 02:00:02 backup1 nightly-backup[8813]: starting dump of 3 databases to /var/backups/db\n"
+ "Oct 12 02:04:47 backup1 nightly-backup[8813]: dumped crm (2.1G)\n"
+ "Oct 12 02:05:13 backup1 nightly-backup[8813]: pg_dump: error: could not write to output file: No space left on device\n"
+ "Oct 12 02:05:13 backup1 nightly-backup[8813]: FAILED dumping billing; aborting run (exit 1)\n"
+ "Oct 12 02:30:00 backup1 CRON[9120]: (root) CMD (/usr/local/sbin/prune-old-backups.sh --keep 7)\n"
+ "Oct 12 02:30:04 backup1 prune-old-backups[9121]: removed 4 archives, freed 11.3G on /var/backups",
+ "a": "The 02:00 nightly backup dumped crm (2.1G), then aborted at 02:05 when the billing dump "
+ "hit 'No space left on device', so the third database was never dumped. The 02:30 prune "
+ "freed 11.3G on /var/backups, but nothing shows the backup being re-run.",
+ "b": "The 02:00 nightly backup dumped crm (2.1G) and then failed on billing at 02:05 with 'No "
+ "space left on device'. After the 02:30 prune freed 11.3G on /var/backups, the backup was "
+ "re-run and completed successfully.",
+ "gold": "a",
+ "why": "b invents a re-run and success; no line after 02:30:04 mentions the backup. a's claims "
+ "(incl. third DB never dumped: 3 planned, 1 done, run aborted) are all supported."},
+
+ {"id": "j-pw-cfg-yaml-versions", "cat": "config", "kind": "pairwise",
+ "task": "YAML for a CI config that is read with a YAML 1.1 loader (e.g. PyYAML). The job matrix "
+ "must list the Python versions 3.9, 3.10 and 3.11, and the CI tool needs each version "
+ "as a string with exactly those characters.",
+ "a": """matrix:
+ python: [3.9, 3.10, 3.11]
+""",
+ "b": """matrix:
+ python: ["3.9", "3.10", "3.11"]
+""",
+ "gold": "b",
+ "why": "unquoted versions load as floats and 3.10 becomes 3.1; executed with PyYAML 6: a -> "
+ "[3.9, 3.1, 3.11] (floats), b -> ['3.9', '3.10', '3.11']."},
+
+ {"id": "j-pw-ans-sudo-redirect", "cat": "answer", "kind": "pairwise",
+ "task": "Answer correctly: why does `sudo echo 'nameserver 10.0.0.53' > /etc/resolv.conf` fail "
+ "with 'Permission denied' when run by a normal user, and what is a working one-line "
+ "replacement?",
+ "a": "The `>` redirection is set up by your own unprivileged shell before sudo even runs, so "
+ "the file is opened as you. Let a root process open it instead: "
+ "`echo 'nameserver 10.0.0.53' | sudo tee /etc/resolv.conf >/dev/null`.",
+ "b": "echo is a shell builtin, and sudo can't elevate builtins, so the write runs without root. "
+ "Call the external binary instead: "
+ "`sudo /bin/echo 'nameserver 10.0.0.53' > /etc/resolv.conf`.",
+ "gold": "a",
+ "why": "b's fix still redirects in the user's shell, so it fails identically (and sudo already "
+ "runs /bin/echo). Shown: `nosuchcmd > f` creates f before the command runs."},
+]
+
+
+RERANK = [
+ # ============================================================ code
+ {"id": "k-code-backoff", "cat": "code",
+ "query": "Python helper that retries a flaky network call, waiting longer after each failure "
+ "(exponential backoff)",
+ "candidates": {
+ "c1": """def ewma(values, alpha=0.3):
+ \"\"\"Exponentially weighted moving average of request latencies.\"\"\"
+ avg = None
+ for v in values:
+ avg = v if avg is None else alpha * v + (1 - alpha) * avg
+ return avg""",
+ "c2": """def retry(fn, attempts=3, delay=2.0):
+ for i in range(attempts):
+ try:
+ return fn()
+ except (ConnectionError, TimeoutError):
+ if i == attempts - 1:
+ raise
+ time.sleep(delay)""",
+ "c3": """def fetch_json(url, timeout=10):
+ \"\"\"Network call to the inventory API. Raises on HTTP failure.\"\"\"
+ req = urllib.request.Request(url, headers={"Accept": "application/json"})
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
+ return json.load(resp)""",
+ "c4": """def call_patiently(op, tries=6, base=0.5, cap=30.0):
+ for n in range(tries):
+ try:
+ return op()
+ except OSError:
+ if n == tries - 1:
+ raise
+ time.sleep(min(cap, base * 2 ** n) * random.uniform(0.5, 1.0))""",
+ "c5": """def backoff_delays(base=1.0, factor=2.0, limit=5):
+ \"\"\"Delay schedule [1, 2, 4, 8, 16] used by the job-runner config.\"\"\"
+ return [base * factor ** i for i in range(limit)]""",
+ "c6": """def record_failure(stats, host):
+ \"\"\"Count consecutive failed calls per host; reset on success.\"\"\"
+ stats[host] = stats.get(host, 0) + 1
+ if stats[host] >= 5:
+ log.warning("host %s failing repeatedly (%d)", host, stats[host])""",
+ "c7": """class TokenBucket:
+ def __init__(self, rate, burst):
+ self.rate, self.tokens, self.burst = rate, burst, burst
+ self.t = time.monotonic()
+
+ def take(self):
+ now = time.monotonic()
+ self.tokens = min(self.burst, self.tokens + (now - self.t) * self.rate)
+ self.t = now
+ if self.tokens >= 1:
+ self.tokens -= 1
+ return True
+ return False""",
+ },
+ "relevance": {"c4": 3, "c2": 2, "c5": 1},
+ "why": "c4 retries on OSError (covers connection/timeout errors) with capped, jittered "
+ "base*2**n sleeps, without saying 'retry' or 'backoff'; c2 retries at a fixed delay."},
+
+ {"id": "k-code-duration", "cat": "code",
+ "query": "Python function that parses a duration string like '1h30m' or '45s' into a number of "
+ "seconds",
+ "candidates": {
+ "c1": """def humanize(seconds):
+ h, rem = divmod(int(seconds), 3600)
+ m, s = divmod(rem, 60)
+ return "".join(f"{v}{u}" for v, u in ((h, "h"), (m, "m"), (s, "s")) if v) or "0s\"""",
+ "c2": """def parse_ts(s):
+ \"\"\"Parse an ISO-8601 timestamp string like '2026-10-12T08:30:00Z'.\"\"\"
+ return datetime.strptime(s, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc)""",
+ "c3": """def clock_to_seconds(text):
+ \"\"\"'01:30:00' -> 5400. Accepts MM:SS too.\"\"\"
+ total = 0
+ for p in text.split(":"):
+ total = total * 60 + int(p)
+ return total""",
+ "c4": """@dataclass
+class JobDuration:
+ \"\"\"Duration of a finished job, in seconds, as stored in the results table.\"\"\"
+ job_id: str
+ seconds: float
+
+ def __str__(self):
+ return f"{self.job_id}: {self.seconds:.1f}s\"""",
+ "c5": r"""_UNIT = {"d": 86400, "h": 3600, "m": 60, "s": 1}
+
+def to_secs(spec):
+ total, pos = 0, 0
+ for m in re.finditer(r"(\d+)([dhms])", spec):
+ if m.start() != pos:
+ raise ValueError(f"bad spec: {spec!r}")
+ total += int(m.group(1)) * _UNIT[m.group(2)]
+ pos = m.end()
+ if not spec or pos != len(spec):
+ raise ValueError(f"bad spec: {spec!r}")
+ return total""",
+ "c6": """def sleep_seconds(n):
+ \"\"\"Sleep for n seconds, logging the wait.\"\"\"
+ log.debug("sleeping %ss", n)
+ time.sleep(n)""",
+ "c7": """parser.add_argument("--timeout", type=int, default=30,
+ help="request timeout in seconds, e.g. 45")""",
+ },
+ "relevance": {"c5": 3, "c3": 2, "c1": 1},
+ "why": "c5 parses '1h30m'-style specs (d/h/m/s units) into seconds; c3 parses clock-style "
+ "durations; c1 is the inverse formatter; c2/c4/c6/c7 only share words."},
+
+ {"id": "k-code-go-cancel", "cat": "code",
+ "query": "Go HTTP handler: stop the expensive work as soon as the client disconnects",
+ "candidates": {
+ "c1": """var client = &http.Client{
+ Timeout: 10 * time.Second,
+ Transport: &http.Transport{MaxIdleConnsPerHost: 16},
+}""",
+ "c2": """func report(w http.ResponseWriter, r *http.Request) {
+ ctx := r.Context()
+ rows, err := db.QueryContext(ctx, heavyReportSQL)
+ if err != nil {
+ if errors.Is(err, context.Canceled) {
+ return // caller went away
+ }
+ http.Error(w, err.Error(), 500)
+ return
+ }
+ defer rows.Close()
+ for rows.Next() {
+ if ctx.Err() != nil {
+ return
+ }
+ // ... aggregate row
+ }
+}""",
+ "c3": """sig := make(chan os.Signal, 1)
+signal.Notify(sig, os.Interrupt, syscall.SIGTERM)
+<-sig
+ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
+defer cancel()
+srv.Shutdown(ctx)""",
+ "c4": """func logClient(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ log.Printf("client %s %s %s", r.RemoteAddr, r.Method, r.URL.Path)
+ next.ServeHTTP(w, r)
+ })
+}""",
+ "c5": """ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+defer cancel()
+req, _ := http.NewRequestWithContext(ctx, "GET", upstreamURL, nil)
+resp, err := http.DefaultClient.Do(req)""",
+ "c6": """func worker(jobs <-chan Job, done <-chan struct{}) {
+ for {
+ select {
+ case <-done:
+ return
+ case j := <-jobs:
+ process(j)
+ }
+ }
+}""",
+ "c7": """srv := &http.Server{
+ Addr: ":8080",
+ ReadTimeout: 5 * time.Second,
+ WriteTimeout: 30 * time.Second,
+ Handler: mux,
+}""",
+ },
+ "relevance": {"c2": 3, "c6": 2, "c5": 1},
+ "why": "c2 threads r.Context() (canceled when the client goes away) into the query and the row "
+ "loop; c6 is the generic done-channel pattern; c5 uses a context only for a timeout."},
+
+ {"id": "k-code-rust-from", "cat": "code",
+ "query": "Rust: make `?` convert std::io::Error into my own error enum automatically",
+ "candidates": {
+ "c1": """impl fmt::Display for AppError {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ AppError::Io(e) => write!(f, "io error: {e}"),
+ AppError::Config(msg) => write!(f, "bad config: {msg}"),
+ }
+ }
+}""",
+ "c2": """let text = fs::read_to_string(&path).map_err(AppError::Io)?;""",
+ "c3": """impl From<io::Error> for AppError {
+ fn from(e: io::Error) -> Self {
+ AppError::Io(e)
+ }
+}""",
+ "c4": """match fs::remove_file(&lock) {
+ Ok(()) => {}
+ Err(e) if e.kind() == io::ErrorKind::NotFound => {}
+ Err(e) => return Err(e),
+}""",
+ "c5": """let cfg = fs::read_to_string("app.toml")
+ .unwrap_or_else(|e| panic!("cannot read app.toml: {e}"));""",
+ "c6": """#[derive(Debug, thiserror::Error)]
+enum ParseError {
+ #[error("bad number: {0}")]
+ Num(#[from] std::num::ParseIntError),
+}""",
+ "c7": """fn main() -> Result<(), Box<dyn std::error::Error>> {
+ let cfg = std::fs::read_to_string("app.toml")?;
+ run(&cfg)?;
+ Ok(())
+}""",
+ },
+ "relevance": {"c3": 3, "c2": 2, "c6": 1, "c7": 1},
+ "why": "`?` calls From::from on the error, so c3's impl is exactly what makes it automatic; c2 "
+ "converts by hand per call site; c6 shows #[from] for a different error type."},
+
+ # ============================================================ logs
+ {"id": "k-log-ssh-accept", "cat": "logs",
+ "query": "the auth.log line showing that user deploy successfully logged in over SSH",
+ "candidates": {
+ "c1": "Oct 12 07:58:12 web1 sshd[4410]: Failed password for deploy from 198.51.100.4 port 52101 ssh2",
+ "c2": "Oct 12 07:58:20 web1 sshd[4412]: pam_unix(sshd:session): session opened for user deploy(uid=1001) by (uid=0)",
+ "c3": "Oct 12 07:58:19 web1 sshd[4412]: Accepted publickey for deploy from 198.51.100.4 port 52114 ssh2: ED25519 SHA256:3fV0kq1oZ7c9TQ8xg2Lw1mJbW0mS9a6YtD4c2r1Hk8E",
+ "c4": "Oct 12 08:02:44 web1 sshd[4460]: Accepted publickey for backup from 10.0.0.12 port 41980 ssh2: RSA SHA256:Qm9vZ2xlTm90QVJlYWxLZXlKdXN0RmFrZURhdGExMjM",
+ "c5": "Oct 12 07:58:20 web1 systemd-logind[612]: New session 17 of user deploy.",
+ "c6": "Oct 12 07:57:03 web1 sshd[4398]: Invalid user deplo from 203.0.113.50 port 40022",
+ "c7": "Oct 12 07:58:12 web1 sshd[4410]: Connection closed by authenticating user deploy 198.51.100.4 port 52101 [preauth]",
+ "c8": "Oct 12 08:41:55 web1 sshd[4412]: pam_unix(sshd:session): session closed for user deploy",
+ },
+ "relevance": {"c3": 3, "c2": 2, "c5": 2, "c8": 1},
+ "why": "sshd's 'Accepted publickey for deploy' is the authentication success itself; the PAM / "
+ "logind session lines follow from it; c4 is a success for a different user."},
+
+ {"id": "k-log-oom", "cat": "logs",
+ "query": "why was the postgres process killed at 03:12?",
+ "candidates": {
+ "c1": "Oct 11 03:12:05 db1 postgres[2190]: LOG: server process (PID 2211) was terminated by signal 9: Killed",
+ "c2": "Oct 11 03:12:05 db1 kernel: Out of memory: Killed process 2211 (postgres) total-vm:9123456kB, anon-rss:6801232kB, file-rss:0kB, shmem-rss:131072kB, UID:113 pgtables:14212kB oom_score_adj:0",
+ "c3": "Oct 10 22:15:00 db1 sudo: user : TTY=pts/1 ; PWD=/home/user ; USER=root ; COMMAND=/usr/bin/kill -TERM 1874",
+ "c4": "Oct 11 03:12:05 db1 kernel: postgres invoked oom-killer: gfp_mask=0x140cca(GFP_HIGHUSER_MOVABLE|__GFP_COMP), order=0, oom_score_adj=0",
+ "c5": "Oct 11 03:12:10 db1 postgres[2190]: LOG: database system is ready to accept connections",
+ "c6": "Oct 11 01:00:00 db1 postgres[2190]: LOG: checkpoint complete: wrote 1832 buffers (11.2%); 0 WAL file(s) added, 0 removed, 1 recycled",
+ "c7": "Oct 11 03:11:58 db1 kernel: nvme0n1: I/O 912 QID 4 timeout, completion polled",
+ "c8": "Oct 11 03:12:05 db1 postgres[2190]: LOG: terminating any other active server processes",
+ },
+ "relevance": {"c2": 3, "c1": 2, "c4": 2, "c8": 1},
+ "why": "c2 names the killer and the reason (kernel OOM, ~6.5 GiB anon RSS, PID 2211); c1 shows "
+ "only the signal; c4 shows the OOM killer starting, not who it killed."},
+
+ {"id": "k-log-tls", "cat": "logs",
+ "query": "why are the billing service's outbound API calls failing since this morning?",
+ "candidates": {
+ "c1": "2026-10-12T06:00:03Z billing INFO scheduler: starting invoice run batch=2026-10-12",
+ "c2": "2026-10-12T02:14:51Z certbot INFO renewed certificate for billing.internal.example (expires 2027-01-10)",
+ "c3": "2026-10-12T06:00:04Z billing WARN payments: retrying POST /v2/charges (attempt 2/5) in 2s",
+ "c4": "2026-10-11T23:41:10Z gateway ERROR upstream billing: connect() failed (111: Connection refused) while connecting to upstream",
+ "c5": "2026-10-12T06:00:04Z billing ERROR payments: POST https://api.payments.example/v2/charges failed: x509: certificate has expired or is not yet valid: current time 2026-10-12T06:00:04Z is after 2026-10-12T00:00:00Z",
+ "c6": "2026-10-11T09:12:30Z billing WARN payments: server certificate for api.payments.example expires at 2026-10-12T00:00:00Z (in 14h47m)",
+ "c7": "2026-10-12T06:00:31Z billing ERROR invoices: 214 invoices not charged; will retry next run",
+ "c8": "2026-10-12T06:00:04Z billing DEBUG http: dial tcp 10.0.4.17:443 ok (12ms)",
+ },
+ "relevance": {"c5": 3, "c6": 2, "c3": 1, "c7": 1, "c8": 1},
+ "why": "c5 is the failing outbound call with its cause (the payment API's cert expired at "
+ "midnight); c6 predicted it; c2 is our own cert renewing fine; c4 is inbound, yesterday."},
+
+ # ============================================================ docs
+ {"id": "k-doc-rsync-mirror", "cat": "docs",
+ "query": "rsync option to make the destination an exact mirror, removing files there that no "
+ "longer exist in the source",
+ "candidates": {
+ "c1": "--remove-source-files After a file has been transferred successfully, delete it from "
+ "the sending side (directories are left in place). Useful for moving files rather than "
+ "copying them.",
+ "c2": "--existing Skip creating files on the receiver that do not already exist there; only "
+ "update files the destination already has.",
+ "c3": "--delete Delete extraneous files from the receiving side, i.e. files that are not "
+ "present on the sending side, but only in directories being synchronized. Use with "
+ "-r/-a, and try --dry-run first: it removes data at the destination.",
+ "c4": "--delete-before, --delete-during, --delete-delay, --delete-after Choose when "
+ "receiver-side deletions happen relative to the transfer (before it, incrementally, or "
+ "at the end). They change timing and memory use, not which files get deleted.",
+ "c5": "--ignore-existing Skip updating files that already exist on the destination; new "
+ "files are still created.",
+ "c6": "-a, --archive Archive mode: recurse into directories and preserve symlinks, "
+ "permissions, modification times, group, owner and device files; equivalent to "
+ "-rlptgoD. It does not delete anything on the receiver.",
+ "c7": "--backup When a destination file would be replaced or deleted, rename the old copy "
+ "with a ~ suffix (see --suffix, --backup-dir) instead of discarding it.",
+ "c8": "--max-delete=NUM Do not delete more than NUM files or directories in one run; a "
+ "safety cap for transfers that delete.",
+ },
+ "relevance": {"c3": 3, "c4": 2, "c6": 1, "c8": 1},
+ "why": "--delete is the option that removes receiver files absent from the source; c4 only "
+ "tunes its timing; c1 removes from the SOURCE (lexical trap)."},
+
+ {"id": "k-doc-git-uncommit", "cat": "docs",
+ "query": "undo my last git commit but keep its changes in my working files",
+ "candidates": {
+ "c1": "git restore [--staged] <pathspec> Restore specified paths in the working tree from a "
+ "restore source (the index by default). With --staged, restore the index instead.",
+ "c2": "git revert <commit> Create a new commit that reverses the changes introduced by "
+ "<commit>. The original commit stays in history; requires a clean working tree.",
+ "c3": "git reset --hard <commit> Resets the index and working tree. Any changes to tracked "
+ "files in the working tree since <commit> are discarded.",
+ "c4": "git commit --amend Replace the tip of the current branch with a new commit built from "
+ "the current index; use it to fix the last commit's message or add forgotten files.",
+ "c5": "git stash push Save your local modifications to a new stash entry and roll the working "
+ "tree and index back to HEAD.",
+ "c6": "git reset [<commit>] (default --mixed mode) Resets the index to <commit> but not the "
+ "working tree: changed files are preserved but not marked for commit.",
+ "c7": "git reset --soft HEAD~1 Moves the branch back one commit without touching the index "
+ "or the working tree, so the undone commit's changes stay staged and ready to commit "
+ "again. (--mixed, the default, also keeps the files but unstages them.)",
+ "c8": "git reflog Shows where HEAD and branch tips have pointed recently, so commits that "
+ "were reset away can be found and recovered.",
+ },
+ "relevance": {"c7": 3, "c6": 2, "c2": 1, "c4": 1, "c8": 1},
+ "why": "c7 is exactly 'drop the last commit, keep its changes'; c6 is the general mixed reset "
+ "without the HEAD~1 target; c3 shares 'reset'/'working tree' but discards the changes."},
+
+ {"id": "k-doc-systemd-env", "cat": "docs",
+ "query": "set an environment variable for one systemd service without editing the unit file "
+ "that the package shipped",
+ "candidates": {
+ "c1": "/etc/environment Read by pam_env at login for user sessions; KEY=value lines. It "
+ "affects login shells and desktop sessions.",
+ "c2": "Environment= Sets environment variables for executed processes. Takes a space-"
+ "separated list of assignments, e.g. Environment=\"ONE=one\" \"TWO=two two\". May be "
+ "given more than once.",
+ "c3": "systemctl set-environment VAR=value Sets a variable in the service manager's own "
+ "environment; it is inherited by units started afterwards and is lost on reboot.",
+ "c4": "systemctl edit UNIT Opens an editor on a drop-in /etc/systemd/system/UNIT.d/"
+ "override.conf. Settings there are merged over the vendor unit, survive package "
+ "upgrades, and the manager reloads on save. Put [Service] and Environment=LOG_LEVEL="
+ "debug in it, then restart UNIT.",
+ "c5": "export VAR=value in ~/.bashrc Makes VAR available to interactive shells started by "
+ "that user.",
+ "c6": "EnvironmentFile= Like Environment=, but reads the variables from a text file; a "
+ "leading '-' on the path makes a missing file non-fatal.",
+ "c7": "systemctl daemon-reload Reload the systemd manager configuration: rerun generators "
+ "and reload all unit files.",
+ "c8": "systemctl show -p Environment UNIT Print the environment variables currently "
+ "configured for UNIT.",
+ },
+ "relevance": {"c4": 3, "c2": 2, "c6": 2, "c3": 1, "c7": 1, "c8": 1},
+ "why": "a drop-in via systemctl edit is the per-service, upgrade-safe way; c2/c6 are the "
+ "directives but not where to put them; c1/c5 never reach services."},
+
+ # ============================================================ commands
+ {"id": "k-cmd-port", "cat": "commands",
+ "query": "which process is listening on TCP port 8080 on this Linux box",
+ "candidates": {
+ "c1": "curl -sI http://127.0.0.1:8080/",
+ "c2": "sudo ss -ltnp 'sport = :8080'",
+ "c3": "sudo lsof -i :8080",
+ "c4": "nc -l 8080",
+ "c5": "grep -i ':1F90 ' /proc/net/tcp",
+ "c6": "sudo netstat -tlnp | grep 8080",
+ "c7": "sudo iptables -A INPUT -p tcp --dport 8080 -j ACCEPT",
+ "c8": "ss -s",
+ },
+ "relevance": {"c2": 3, "c3": 2, "c6": 2, "c5": 1},
+ "why": "c2 filters listening TCP sockets on exactly port 8080 and shows the owning process; c3 "
+ "also lists clients/UDP; c6's grep can hit 18080; c5 shows the socket but no process."},
+
+ {"id": "k-cmd-bigdirs", "cat": "commands",
+ "query": "find which directories under /var are using the most space",
+ "candidates": {
+ "c1": "df -h /var",
+ "c2": "sudo find /var -xdev -type f -size +500M -exec ls -lh {} +",
+ "c3": "du -sh /var",
+ "c4": "ls -lS /var",
+ "c5": "sudo du -xh --max-depth=2 /var 2>/dev/null | sort -rh | head -n 20",
+ "c6": "sudo du -sh /var/*",
+ "c7": "sudo lsof +L1",
+ "c8": "journalctl --disk-usage",
+ },
+ "relevance": {"c5": 3, "c6": 2, "c2": 1, "c3": 1, "c8": 1},
+ "why": "c5 sizes directories two levels down and sorts them largest first; c6 is unsorted, "
+ "top level only; c1 and c4 share 'size' semantics but say nothing per directory."},
+
+ {"id": "k-cmd-tar-list", "cat": "commands",
+ "query": "see the list of files inside backup.tar.gz without unpacking it",
+ "candidates": {
+ "c1": "tar -tzvf backup.tar.gz",
+ "c2": "tar -xzvf backup.tar.gz",
+ "c3": "gzip -l backup.tar.gz",
+ "c4": "tar -tzf backup.tar.gz | grep '^etc/'",
+ "c5": "zcat backup.tar.gz | head -c 512",
+ "c6": "tar -czf backup.tar.gz /etc",
+ "c7": "mkdir /tmp/peek && tar -xzf backup.tar.gz -C /tmp/peek && ls -R /tmp/peek",
+ "c8": "unzip -l backup.tar.gz",
+ },
+ "relevance": {"c1": 3, "c4": 2, "c7": 1},
+ "why": "-t lists the archive without extracting; c4 lists only etc/; c7 gets a listing by "
+ "unpacking; c3 'lists' only gzip sizes, c2 extracts, c6 overwrites the archive."},
+
+ # ============================================================ errors
+ {"id": "k-err-modnotfound", "cat": "errors",
+ "query": "ModuleNotFoundError: No module named 'yaml' when I run my script with python3",
+ "candidates": {
+ "c1": "yaml.scanner.ScannerError: mapping values are not allowed here. That's a YAML syntax "
+ "problem: usually a missing space after a colon or bad indentation in the .yml file.",
+ "c2": "The importable module is called yaml but the PyPI distribution is PyYAML. Install it "
+ "into the interpreter that runs the script: `python3 -m pip install PyYAML` (or the "
+ "distro package python3-yaml).",
+ "c3": "ImportError: attempted relative import with no known parent package. Run it as "
+ "`python -m package.module` from the project root instead of executing the file "
+ "directly.",
+ "c4": "ModuleNotFoundError just means the import system searched every entry of sys.path "
+ "and found nothing; print sys.path to see where it looked.",
+ "c5": "You probably installed it into a different interpreter or virtualenv. Compare `which "
+ "python3` with the interpreter pip belongs to (`pip --version`) and activate the right "
+ "venv.",
+ "c6": "AttributeError: module 'yaml' has no attribute 'FullLoader'. Your PyYAML predates 5.1; "
+ "upgrade it.",
+ "c7": "To read YAML in Go, add gopkg.in/yaml.v3 to go.mod and call yaml.Unmarshal.",
+ },
+ "relevance": {"c2": 3, "c5": 2, "c4": 1},
+ "why": "the module 'yaml' ships in the PyYAML distribution, installed via the same python3; c5 "
+ "covers the wrong-interpreter case; c1/c6/c7 share 'yaml' but are other problems."},
+
+ {"id": "k-err-nilmap", "cat": "errors",
+ "query": "Go program crashes with: panic: assignment to entry in nil map",
+ "candidates": {
+ "c1": "fatal error: concurrent map writes. Two goroutines wrote the same map at once; guard "
+ "it with a sync.Mutex or use sync.Map.",
+ "c2": "panic: runtime error: invalid memory address or nil pointer dereference. You "
+ "dereferenced a nil pointer; check for nil before using it.",
+ "c3": "Struct fields of map type start out nil. If your type has `counts map[string]int`, "
+ "give it a constructor that sets `counts: make(map[string]int)` before anything writes "
+ "to it.",
+ "c4": "panic: runtime error: index out of range [3] with length 3. A slice index is past the "
+ "end; check len() first.",
+ "c5": "A map declared with `var m map[string]int` is nil: reading from it returns zero values, "
+ "but writing to it panics. Allocate it first with `m = make(map[string]int)` or a "
+ "literal `map[string]int{}`.",
+ "c6": "The zero value of a map type is nil; len() of a nil map is 0 and ranging over it does "
+ "nothing.",
+ "c7": "invalid operation: cannot index m (variable of type *map[string]int). You're indexing "
+ "a pointer to a map; dereference it with (*m)[k].",
+ },
+ "relevance": {"c5": 3, "c3": 2, "c6": 1},
+ "why": "c5 explains the panic (writing to a nil map) and the fix (make/literal); c3 is the same "
+ "fix for struct fields only; c1/c2 share 'map'/'nil'/'panic' but are other errors."},
+
+ {"id": "k-err-502-refused", "cat": "errors",
+ "query": "nginx error.log says 'connect() failed (111: Connection refused) while connecting to "
+ "upstream' and clients get 502 Bad Gateway",
+ "candidates": {
+ "c1": "upstream timed out (110: Connection timed out) while reading response header from "
+ "upstream: the backend accepted the connection but answered too slowly; raise "
+ "proxy_read_timeout or fix the slow endpoint.",
+ "c2": "connect() to 127.0.0.1:8000 failed (13: Permission denied) while connecting to "
+ "upstream: on SELinux hosts nginx may not open network connections; run `setsebool -P "
+ "httpd_can_network_connect 1`.",
+ "c3": "A 502 Bad Gateway means nginx could not get a valid response from the upstream; the "
+ "specific reason is in nginx's error.log.",
+ "c4": "client intended to send too large body: raise client_max_body_size (default 1m); "
+ "clients get 413.",
+ "c5": "Check that the app's service is actually running (`systemctl status app`); if it "
+ "crashed on start, nginx has nothing to connect to.",
+ "c6": "Errno 111 means nothing accepted the connection at the upstream address nginx was "
+ "given: the app is down, crashed on start, or listens on another port or address (e.g. "
+ "::1 vs 127.0.0.1). Compare the proxy_pass target with `ss -ltnp`, then read the app's "
+ "own logs.",
+ "c7": "no live upstreams while connecting to upstream: every server in the upstream block is "
+ "currently marked failed; see max_fails and fail_timeout.",
+ "c8": "If the backend listens on a Unix socket, proxy_pass must name it (proxy_pass "
+ "http://unix:/run/app.sock;) and the path must match the socket the app creates.",
+ },
+ "relevance": {"c6": 3, "c5": 2, "c3": 1, "c7": 1, "c8": 1},
+ "why": "c6 explains errno 111 and how to find which cause applies; c5 covers one cause; c1/c2 "
+ "share 'connect()'/'upstream' but are errno 110/13 with different fixes."},
+]
diff --git a/bench/tasks/sleuth.py b/bench/tasks/sleuth.py
new file mode 100644
index 0000000..7fae038
--- /dev/null
+++ b/bench/tasks/sleuth.py
@@ -0,0 +1,347 @@
+"""Sleuth instrument: troubleshoot a broken Linux machine through a root shell. Scored on reaching
+the right conclusion and on how directly the model got there.
+
+Each attempt gets a throwaway container with no network. A live case is a really broken install the
+model must fix; afterwards the case's hidden CHECK must pass. A snapshot case is a captured host (its
+files under / plus canned output for commands that need its kernel) entered with chroot; diagnose
+only. Cases: bench/tasks/sleuth_cases/ (contract in its __init__.py).
+
+Tools: run(command), submit_findings(culprit, root_cause, fix) (ends the attempt).
+Gates: culprit (every CULPRIT pattern matches culprit + root_cause, no REJECT pattern matches the
+culprit); fix (live: CHECK exits 0; snapshot: a FIX pattern matches the fix); seen (a KEY marker was
+in output the model was shown). Rows add checks, first_key_check, expert_checks and investigate_s.
+"""
+import hashlib
+import importlib
+import os
+import re
+import subprocess
+import sys
+import threading
+import time
+
+from bench.core import tools
+from bench.tasks import agentic_multitask as harness
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+CASES_DIR = os.path.join(HERE, "sleuth_cases")
+CACHE_DIR = os.path.join(os.path.dirname(HERE), "data", "sleuth", "cache")
+
+# 1.37.0-musl is a static binary, so it runs inside any snapshot's chroot.
+BUSYBOX = "busybox@sha256:5cec3fc171c87218698e85a52af7087de727372aae264a787b8112901a5b0092"
+ALPINE = "alpine@sha256:5291449c3df73caf6ed85e649dec1b9e818b39a5d8c871e97afc13e9cd5e8fa8" # 3.22
+
+CMD_TIMEOUT = 60
+MAX_TURNS = 40
+MAX_TOKENS = 8000
+TEMPERATURE = 0.6
+GATES = ("culprit", "fix", "seen")
+FINDINGS = ("culprit", "root_cause", "fix")
+PATH = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
+DOCKER_ERR = re.compile(r"Cannot connect to the Docker daemon|Error response from daemon|"
+ r"OCI runtime exec failed|No such container")
+
+SYSTEM = ("You are troubleshooting a Linux machine for its owner through a root shell on it. The run "
+ "tool executes a command there; common tools are the BusyBox versions. {task} When you "
+ "are done, call submit_findings.")
+TASK_DIAGNOSE = ("Find the root cause of the problem the owner describes. Do not change the system: "
+ "report the cause and the fix for the owner to apply.")
+TASK_FIX = ("Find the root cause of the problem the owner describes and fix it on the machine, "
+ "keeping its services running, then check that the fix works.")
+NUDGE = "Use run to keep investigating, or call submit_findings with your conclusion."
+
+
+class Case:
+ """One sleuth item; the fields are described in sleuth_cases/__init__.py."""
+
+ def __init__(self, *, case_id, category, complaint, context, culprit, key, expert, reference,
+ wrong, reject=(), fix=(), check=None, setup=(), ready=None, docker_args=()):
+ self.case_id, self.category, self.complaint = case_id, category, complaint
+ self.context, self.culprit, self.reject, self.fix = context, culprit, reject, fix
+ self.key, self.expert, self.reference, self.wrong = key, expert, reference, wrong
+ self.check, self.setup, self.ready, self.docker_args = check, setup, ready, docker_args
+ self.live = check is not None
+ self.source_files = ()
+ if not wrong:
+ raise ValueError(f"{case_id}: needs >= 1 wrong answer to prove the culprit gate bites")
+ if not self.live and not fix:
+ raise ValueError(f"{case_id}: a snapshot case needs FIX patterns")
+ self._ctx = None
+ self._lock = threading.Lock()
+
+ def build_context(self):
+ with self._lock:
+ if self._ctx is None:
+ self._ctx = self.context()
+ return self._ctx
+
+
+# ============================================================ snapshot hosts
+
+SHIM = """#!/bin/sh
+n=${0##*/}; k="$n $*"
+while :; do
+ f=/usr/share/sleuth/cmd/$(printf %s "$k" | tr -c 'A-Za-z0-9._=-' _)
+ [ -f "$f" ] && exec cat "$f"
+ [ "$k" = "${k% *}" ] && exit 1
+ k=${k% *}
+done
+"""
+
+SNAPSHOT_DOCKERFILE = f"""FROM {BUSYBOX}
+COPY snap/ /snap/
+COPY shims/ /snap/usr/bin/
+RUN cp /bin/busybox /snap/usr/bin/busybox && /bin/busybox --install -s /snap/usr/bin \\
+ && mkdir -p /snap/dev /snap/root /snap/run /snap/tmp /snap/var/tmp \\
+ && chmod 1777 /snap/tmp /snap/var/tmp && chmod 700 /snap/root \\
+ && mknod -m 666 /snap/dev/null c 1 3 && mknod -m 666 /snap/dev/zero c 1 5 \\
+ && mknod -m 444 /snap/dev/urandom c 1 9 \\
+ && find /snap/usr/bin /snap/usr/sbin /snap/etc/init.d -type f -exec chmod 755 {{}} + 2>/dev/null; true
+CMD ["sleep", "2147483647"]
+"""
+
+
+def cmd_key(command):
+ """File name of a canned command output (the shim's `tr -c` mapping)."""
+ return re.sub(r"[^A-Za-z0-9._=-]", "_", command)
+
+
+def snapshot(files, commands):
+ """Build context of a snapshot host: `files` land under its / (merged /usr), each `commands` key
+ ("uname -r") prints its text; other argument lists fall back to the longest matching key prefix,
+ so every command needs a bare-name key."""
+ ctx = {"Dockerfile": SNAPSHOT_DOCKERFILE, "snap/bin": tools.Symlink("usr/bin"),
+ "snap/sbin": tools.Symlink("usr/sbin"), "snap/lib": tools.Symlink("usr/lib"),
+ "snap/lib64": tools.Symlink("usr/lib64")}
+ for path, content in files.items():
+ ctx["snap/" + path.lstrip("/")] = content
+ for name in sorted({k.split()[0] for k in commands}):
+ if name not in commands:
+ raise ValueError(f"command {name!r} needs a bare-name key")
+ ctx["shims/" + name] = SHIM
+ for k, text in commands.items():
+ ctx["snap/usr/share/sleuth/cmd/" + cmd_key(k)] = text
+ return ctx
+
+
+# ============================================================ containers
+
+_image_lock = threading.Lock()
+
+
+def _docker(args, timeout):
+ try:
+ return subprocess.run(["docker", *args], capture_output=True, text=True, timeout=timeout)
+ except (OSError, subprocess.TimeoutExpired) as e:
+ raise tools.InfraError(f"docker {args[0]}: {e!r}; is Docker Desktop running?")
+
+
+def _digest(ctx):
+ h = hashlib.sha256()
+ for path in sorted(ctx):
+ c = ctx[path]
+ kind = b"L" if isinstance(c, tools.Symlink) else b"B" if isinstance(c, bytes) else b"T"
+ h.update(path.encode() + b"\0" + kind + (c if isinstance(c, bytes) else c.encode()) + b"\0")
+ return h.hexdigest()[:12]
+
+
+def image(case):
+ """The case's image tag, built once per context digest."""
+ ctx = case.build_context()
+ tag = f"llm-bench-sleuth/{case.case_id}:{_digest(ctx)}"
+ with _image_lock:
+ if _docker(["image", "inspect", tag], 60).returncode != 0:
+ d = tools.materialize(ctx, os.path.join(tools.WORK_ROOT, "_sleuth-build", case.case_id))
+ r = _docker(["build", "-q", "-t", tag, d], 1800)
+ if r.returncode != 0:
+ raise tools.InfraError(f"docker build {case.case_id} failed: {r.stderr[-600:]}")
+ return tag
+
+
+def exec_in(ws, case, cmd, timeout=CMD_TIMEOUT):
+ """One shell command on the case's host -> tools.RunResult, stdout and stderr merged in .out."""
+ script = "cd /root 2>/dev/null; exec 2>&1\n" + cmd
+ shell = ["sh", "-c", script] if case.live else ["chroot", "/snap", "/bin/sh", "-c", script]
+ r = ws.run(["docker", "exec", "-e", "PATH=" + PATH, "-e", "HOME=/root", "-e", "TERM=dumb",
+ ws.state["container"], "timeout", "-s", "KILL", str(timeout), *shell], timeout + 30)
+ if r.timed_out or DOCKER_ERR.search(r.err):
+ raise tools.InfraError(f"docker exec failed: {(r.err or 'timed out')[-300:]}")
+ return r
+
+
+def start(ws, case):
+ """Start the attempt's container, run the case's setup and wait for it to be ready."""
+ tag = image(case)
+ name = "llm-bench-sleuth-" + ws.marker[:12]
+ ws.cleanups.append(lambda: _docker(["rm", "-f", name], 60))
+ r = _docker(["run", "-d", "--rm", "--name", name, "--network", "none", "--memory", "1g",
+ "--pids-limit", "512", *case.docker_args, tag], 120)
+ if r.returncode != 0:
+ raise tools.InfraError(f"docker run {case.case_id} failed: {r.stderr[-400:]}")
+ ws.state["container"] = name
+ for cmd in case.setup:
+ s = exec_in(ws, case, cmd, 300)
+ if s.rc != 0:
+ raise tools.InfraError(f"setup {cmd[:60]!r} exited {s.rc}: {s.out[-300:]}")
+ end = time.time() + 180
+ while case.ready and exec_in(ws, case, case.ready, 30).rc != 0:
+ if time.time() > end:
+ raise tools.InfraError(f"{case.case_id}: not ready after 180 s ({case.ready[:60]!r})")
+ time.sleep(1)
+
+
+# ============================================================ tools
+
+def _t_run(ws, args):
+ cmd = tools._str_arg(args, "command", "")
+ if not cmd.strip():
+ raise tools.ToolError("`command` is empty; pass one shell command line")
+ st = ws.state
+ r = exec_in(ws, st["case"], cmd)
+ text = r.text()
+ st["checks"].append({"cmd": cmd[:300], "rc": r.rc, "s": round(r.dt, 2),
+ "key": any(k in text[:tools.RESULT_CAP] for k in st["case"].key)})
+ return text
+
+
+def _t_submit(ws, args):
+ f = {}
+ for k in FINDINGS:
+ v = args.get(k)
+ if not isinstance(v, str) or not v.strip():
+ raise tools.ToolError(f"submit_findings needs `{k}` as a non-empty string")
+ f[k] = v.strip()
+ ws.state.update(findings=f, t_submit=time.time())
+ return tools.ToolResult("findings received", stop=True)
+
+
+def _toolset(live):
+ fix = ("What you changed on the machine to fix it." if live else
+ "The exact change or commands the owner should apply to fix it.")
+ schema = [
+ {"type": "function", "function": {
+ "name": "run",
+ "description": f"Run one shell command on the machine as root (sh -c, {CMD_TIMEOUT} s "
+ "timeout). Returns the exit code and the combined output; long output is "
+ "truncated, so filter it (grep, head, tail, awk).",
+ "parameters": {"type": "object", "properties": {
+ "command": {"type": "string"}}, "required": ["command"]},
+ }},
+ {"type": "function", "function": {
+ "name": "submit_findings",
+ "description": "Report your conclusion. This ends the session; call it once.",
+ "parameters": {"type": "object", "properties": {
+ "culprit": {"type": "string", "description": "The single thing at fault, named as "
+ "specifically as you can (a file and function, config option, "
+ "package, process, setting...)."},
+ "root_cause": {"type": "string",
+ "description": "How it causes the problem, in 1-3 sentences."},
+ "fix": {"type": "string", "description": fix},
+ }, "required": list(FINDINGS)},
+ }},
+ ]
+ return tools.Toolset("sleuth-live" if live else "sleuth-snapshot", schema,
+ {"run": _t_run, "submit_findings": _t_submit},
+ commands={"timeout": CMD_TIMEOUT})
+
+
+TOOLSETS = {True: _toolset(True), False: _toolset(False)}
+
+
+# ============================================================ grading
+
+def grade(case, findings):
+ """{culprit[, fix]} for submitted findings; fix is graded here only on snapshot cases."""
+ text = findings["culprit"] + "\n" + findings["root_cause"]
+ g = {"culprit": all(re.search(p, text, re.I) for p in case.culprit)
+ and not any(re.search(p, findings["culprit"], re.I) for p in case.reject)}
+ if not case.live:
+ g["fix"] = any(re.search(p, findings["fix"], re.I) for p in case.fix)
+ return g
+
+
+def _gates(case):
+ def gates(ws, port=None):
+ st = ws.state
+ f = st.get("findings")
+ g, d = grade(case, f) if f else {}, {}
+ if case.live and "container" in st:
+ r = exec_in(ws, case, case.check, 120)
+ g["fix"] = r.rc == 0
+ d["check_tail"] = r.text()[-300:]
+ g["seen"] = any(c["key"] for c in st.get("checks", ()))
+ return {k: g.get(k, False) for k in GATES}, d
+ return gates
+
+
+def _extra(ws):
+ st = ws.state
+ checks = st.get("checks", [])
+ keys = [i for i, c in enumerate(checks, 1) if c["key"]]
+ t0, t1 = st.get("t_start"), st.get("t_submit")
+ return {"checks": len(checks), "first_key_check": keys[0] if keys else None,
+ "expert_checks": len(st["case"].expert) if "case" in st else None,
+ "investigate_s": round(t1 - t0, 2) if t0 and t1 else None,
+ "findings": st.get("findings")}
+
+
+def _validate(case):
+ """Offline proof of a case: the expert path shows a KEY, the reference passes, every wrong
+ answer fails the culprit gate; live cases also fail CHECK broken and pass it after the path."""
+ def validate(ws, port=None):
+ ws.state.update(case=case, checks=[])
+ start(ws, case)
+ g = {}
+ if case.live:
+ g["check_fails_broken"] = exec_in(ws, case, case.check, 120).rc != 0
+ outs = [exec_in(ws, case, c).text()[:tools.RESULT_CAP] for c in case.expert]
+ g["expert_sees_key"] = any(k in o for o in outs for k in case.key)
+ g["reference_passes"] = all(grade(case, case.reference).values())
+ blank = dict.fromkeys(FINDINGS, "")
+ g["wrong_rejected"] = not any(grade(case, dict(blank, **w))["culprit"] for w in case.wrong)
+ if case.live:
+ g["expert_fixes"] = exec_in(ws, case, case.check, 120).rc == 0
+ return all(g.values()), g, {}
+ return validate
+
+
+# ============================================================ cases + CLI
+
+def load_cases():
+ names = sorted(os.listdir(CASES_DIR))
+ helpers = [os.path.join(CASES_DIR, f) for f in names if f.startswith("_") and f.endswith(".py")]
+ cases = []
+ for f in names:
+ if f.endswith(".py") and not f.startswith("_"):
+ m = importlib.import_module(f"bench.tasks.sleuth_cases.{f[:-3]}")
+ for c in m.CASES:
+ c.source_files = (os.path.abspath(m.__file__), *helpers)
+ cases.append(c)
+ ids = [c.case_id for c in cases]
+ if len(set(ids)) != len(ids):
+ raise ValueError(f"duplicate sleuth case ids: {sorted(i for i in ids if ids.count(i) > 1)}")
+ return cases
+
+
+def task(case):
+ def user(ws):
+ ws.state.update(case=case, checks=[])
+ start(ws, case)
+ ws.state["t_start"] = time.time()
+ return case.complaint
+ return harness.AgenticTask(
+ item_id=case.case_id, category=case.category, plan="", starter={},
+ toolset=TOOLSETS[case.live], gates=_gates(case), gate_names=GATES,
+ validate=_validate(case), system_tmpl=SYSTEM.format(task=TASK_FIX if case.live else TASK_DIAGNOSE),
+ user=user, nudge=NUDGE, give_up_after=3, done_word=False, max_tokens=MAX_TOKENS,
+ temperature=TEMPERATURE, extra=_extra, source_files=case.source_files, prune=())
+
+
+def main(argv=None):
+ sys.exit(harness.cli_main("sleuth", "sleuth", [task(c) for c in load_cases()],
+ sys.argv[1:] if argv is None else argv, multi=True,
+ default_cmd="--help", max_turns_default=MAX_TURNS))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/bench/tasks/sleuth_cases/__init__.py b/bench/tasks/sleuth_cases/__init__.py
new file mode 100644
index 0000000..72ce5ac
--- /dev/null
+++ b/bench/tasks/sleuth_cases/__init__.py
@@ -0,0 +1,23 @@
+"""Sleuth cases — auto-discovered by sleuth.py. Each .py file (not starting with _) exposes
+CASES, a list of sleuth.Case; `_*.py` files are shared helpers, hashed into every case.
+
+Case fields:
+ case_id stable item_id
+ category capability bucket: sleuth/<area>
+ complaint what the owner tells the model; never the cause
+ context() -> Docker build context {path: str | bytes | tools.Symlink}, "Dockerfile" included;
+ snapshot cases use sleuth.snapshot(files, commands). Leave no trace of how the box
+ was broken: flatten live images (FROM scratch + COPY --from) and ship no break script.
+ culprit regexes (re.I), every one must match findings culprit + root_cause
+ reject regexes, any match in the culprit fails it (a shotgun or wrong answer)
+ fix regexes, any match in findings fix passes (snapshot cases)
+ check live cases: shell command run after the session; exit 0 = fixed
+ setup live cases: commands run before the model connects (the breakage that needs runtime)
+ ready shell command polled until it exits 0 before the model connects
+ key substrings; output containing one shows the evidence (gate `seen`, first_key_check)
+ expert the shortest check sequence an expert would run (live: ending with the fix);
+ validate requires it to show a KEY, len() is the row's expert_checks
+ reference findings {culprit, root_cause, fix} that must pass the gates
+ wrong findings (culprit[, root_cause]) that must fail the culprit gate
+ docker_args extra `docker run` arguments (tmpfs sizes, hostname)
+"""
diff --git a/bench/tasks/sleuth_cases/_home.py b/bench/tasks/sleuth_cases/_home.py
new file mode 100644
index 0000000..b6ae32e
--- /dev/null
+++ b/bench/tasks/sleuth_cases/_home.py
@@ -0,0 +1,476 @@
+"""The owner's desktop as a snapshot host: Gentoo (OpenRC, merged /usr), i5-12600KF (6P+4E, 16
+threads), RX 9060 XT, ASRock Z690M-ITX/ax, 2x16 GB DDR4-3600. host() returns (files, commands)
+for sleuth.snapshot(); cases layer their evidence on top."""
+import gzip
+
+from bench.core.tools import Symlink
+
+HOSTNAME = "atlas"
+CPU = "12th Gen Intel(R) Core(TM) i5-12600KF"
+P_CPUS, E_CPUS = range(0, 12), range(12, 16)
+NOW = "Mon Oct 12 14:20:07 CDT 2026"
+FLAGS = (
+ "fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx "
+ "fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts "
+ "rep_good nopl xtopology nonstop_tsc cpuid aperfmperf tsc_known_freq pni pclmulqdq dtes64 monitor "
+ "ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm sse4_1 sse4_2 x2apic movbe popcnt "
+ "tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb ssbd ibrs "
+ "ibpb stibp ibrs_enhanced tpr_shadow flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 "
+ "smep bmi2 erms invpcid rdseed adx smap clflushopt clwb intel_pt sha_ni xsaveopt xsavec xgetbv1 "
+ "xsaves split_lock_detect user_shstk avx_vnni dtherm ida arat pln pts hwp hwp_notify "
+ "hwp_act_window hwp_epp hwp_pkg_req hfi vnmi umip pku ospke waitpkg gfni vaes vpclmulqdq rdpid "
+ "movdiri movdir64b fsrm md_clear serialize arch_lbr ibt flush_l1d arch_capabilities")
+
+SERVICES = {"sysinit": ["devfs", "dmesg", "sysfs", "udev", "udev-trigger"],
+ "boot": ["bootmisc", "fsck", "hostname", "hwclock", "localmount", "modules", "procfs",
+ "root", "swap", "sysctl", "urandom"],
+ "default": ["chronyd", "cronie", "cpupower", "dbus", "elogind", "local", "NetworkManager",
+ "sshd", "syslog-ng"]}
+
+CONFIG_BASE = """\
+CONFIG_CC_IS_CLANG=y
+CONFIG_LD_IS_LLD=y
+CONFIG_LOCALVERSION="-tkg-bore-llvm"
+CONFIG_DEFAULT_HOSTNAME="(none)"
+CONFIG_SYSVIPC=y
+CONFIG_POSIX_MQUEUE=y
+CONFIG_NO_HZ_FULL=y
+CONFIG_HIGH_RES_TIMERS=y
+CONFIG_BPF_JIT=y
+CONFIG_PREEMPT_DYNAMIC=y
+CONFIG_SCHED_BORE=y
+CONFIG_IKCONFIG=y
+CONFIG_IKCONFIG_PROC=y
+CONFIG_LOG_BUF_SHIFT=18
+CONFIG_CGROUPS=y
+CONFIG_NAMESPACES=y
+CONFIG_SMP=y
+CONFIG_X86_X2APIC=y
+CONFIG_X86_INTEL_LPSS=y
+CONFIG_MALDERLAKE=y
+CONFIG_PROCESSOR_SELECT=y
+CONFIG_CPU_SUP_INTEL=y
+# CONFIG_CPU_SUP_AMD is not set
+CONFIG_NR_CPUS=16
+CONFIG_SCHED_CLUSTER=y
+CONFIG_SCHED_SMT=y
+CONFIG_SCHED_MC=y
+CONFIG_SCHED_MC_PRIO=y
+CONFIG_X86_MCE=y
+CONFIG_X86_MCE_INTEL=y
+CONFIG_PERF_EVENTS_INTEL_UNCORE=y
+CONFIG_PERF_EVENTS_INTEL_RAPL=y
+CONFIG_MICROCODE=y
+CONFIG_X86_MSR=m
+CONFIG_X86_CPUID=m
+CONFIG_HZ_1000=y
+CONFIG_HZ=1000
+CONFIG_KEXEC=y
+CONFIG_HIBERNATION=y
+CONFIG_PM=y
+CONFIG_ACPI=y
+CONFIG_ACPI_PROCESSOR=y
+CONFIG_ACPI_THERMAL=y
+CONFIG_ACPI_FAN=y
+CONFIG_CPU_FREQ=y
+CONFIG_CPU_FREQ_GOV_ATTR_SET=y
+CONFIG_CPU_FREQ_GOV_COMMON=y
+CONFIG_CPU_FREQ_STAT=y
+CONFIG_CPU_FREQ_DEFAULT_GOV_SCHEDUTIL=y
+CONFIG_CPU_FREQ_GOV_PERFORMANCE=y
+CONFIG_CPU_FREQ_GOV_POWERSAVE=y
+CONFIG_CPU_FREQ_GOV_USERSPACE=y
+CONFIG_CPU_FREQ_GOV_ONDEMAND=y
+CONFIG_CPU_FREQ_GOV_CONSERVATIVE=y
+CONFIG_CPU_FREQ_GOV_SCHEDUTIL=y
+{pstate}CONFIG_X86_ACPI_CPUFREQ=y
+CONFIG_CPU_IDLE=y
+CONFIG_CPU_IDLE_GOV_MENU=y
+CONFIG_CPU_IDLE_GOV_TEO=y
+CONFIG_INTEL_IDLE=y
+CONFIG_PCI=y
+CONFIG_PCIEPORTBUS=y
+CONFIG_HOTPLUG_PCI_PCIE=y
+CONFIG_PCIEAER=y
+CONFIG_PCIEASPM=y
+CONFIG_BLK_DEV_NVME=y
+CONFIG_NVME_CORE=y
+CONFIG_NVME_HWMON=y
+CONFIG_EXT4_FS=y
+CONFIG_BTRFS_FS=m
+CONFIG_VFAT_FS=y
+CONFIG_TMPFS=y
+CONFIG_NET=y
+CONFIG_INET=y
+CONFIG_IPV6=y
+CONFIG_NETFILTER=y
+CONFIG_NF_TABLES=m
+CONFIG_WIREGUARD=m
+CONFIG_ETHERNET=y
+CONFIG_R8169=m
+CONFIG_WLAN=y
+CONFIG_IWLWIFI=m
+CONFIG_IWLMVM=m
+CONFIG_BT=m
+CONFIG_BT_INTEL=m
+CONFIG_INPUT_EVDEV=y
+CONFIG_HID_GENERIC=y
+CONFIG_USB_HID=y
+CONFIG_I2C_I801=m
+CONFIG_SENSORS_CORETEMP=m
+CONFIG_SENSORS_NCT6775=m
+CONFIG_DRM=y
+CONFIG_DRM_AMDGPU=m
+CONFIG_DRM_AMD_DC=y
+CONFIG_HSA_AMD=y
+CONFIG_SND_HDA_INTEL=m
+CONFIG_SND_HDA_CODEC_REALTEK=m
+CONFIG_SND_HDA_CODEC_HDMI=m
+CONFIG_SND_USB_AUDIO=m
+CONFIG_USB_XHCI_HCD=y
+CONFIG_USB_STORAGE=m
+CONFIG_INTEL_TURBO_MAX_3=y
+CONFIG_INTEL_HFI_THERMAL=y
+CONFIG_X86_PKG_TEMP_THERMAL=m
+CONFIG_INTEL_POWERCLAMP=m
+CONFIG_INTEL_RAPL=m
+CONFIG_POWERCAP=y
+CONFIG_ZRAM=m
+CONFIG_TRANSPARENT_HUGEPAGE=y
+CONFIG_TRANSPARENT_HUGEPAGE_MADVISE=y
+"""
+
+
+def kernel_config(pstate=True, trimmed=False):
+ """The kernel .config; `trimmed` drops the iGPU and unused-driver options the owner removed."""
+ text = CONFIG_BASE.format(pstate="CONFIG_X86_INTEL_PSTATE=y\n" if pstate
+ else "# CONFIG_X86_INTEL_PSTATE is not set\n")
+ if not trimmed:
+ text += """\
+CONFIG_DRM_I915=m
+CONFIG_DRM_I915_CAPTURE_ERROR=y
+CONFIG_DRM_I915_USERPTR=y
+CONFIG_DRM_XE=m
+CONFIG_DRM_RADEON=m
+CONFIG_DRM_NOUVEAU=m
+CONFIG_DRM_VGEM=m
+CONFIG_SND_HDA_CODEC_CONEXANT=m
+CONFIG_SND_HDA_CODEC_CA0132=m
+CONFIG_SND_SOC_SOF_ALDERLAKE=m
+CONFIG_INTEL_GTT=m
+CONFIG_INTEL_MEI_GSC=m
+CONFIG_INTEL_MEI_HDCP=m
+CONFIG_INTEL_MEI_PXP=m
+CONFIG_E1000E=m
+CONFIG_IGB=m
+CONFIG_IGC=m
+CONFIG_ATH11K=m
+CONFIG_ATH12K=m
+CONFIG_MT7921E=m
+CONFIG_RTW89=m
+CONFIG_BRCMFMAC=m
+CONFIG_MEDIA_SUPPORT=m
+CONFIG_VIDEO_V4L2=m
+CONFIG_USB_VIDEO_CLASS=m
+CONFIG_THUNDERBOLT=m
+CONFIG_SENSORS_IT87=m
+"""
+ return text
+
+
+def cpufreq(driver, load):
+ """/sys cpufreq tree for intel_pstate (active, HWP) or acpi-cpufreq; `load` busy or idle."""
+ files = {"sys/devices/system/cpu/online": "0-15\n", "sys/devices/system/cpu/possible": "0-15\n",
+ "sys/devices/system/cpu/present": "0-15\n"}
+ for n in list(P_CPUS) + list(E_CPUS):
+ p = f"sys/devices/system/cpu/cpufreq/policy{n}/"
+ files[f"sys/devices/system/cpu/cpu{n}/cpufreq"] = Symlink(f"../cpufreq/policy{n}")
+ for f in ("core_throttle_count", "package_throttle_count"):
+ files[f"sys/devices/system/cpu/cpu{n}/thermal_throttle/{f}"] = "0\n"
+ files[f"sys/devices/system/cpu/cpu{n}/topology/core_type"] = (
+ "intel_core\n" if n in P_CPUS else "intel_atom\n")
+ if driver == "intel_pstate":
+ top, base = (4900000, 3700000) if n in P_CPUS else (3600000, 2800000)
+ cur = (4500000 + 37000 * (n % 5) if n in P_CPUS else 3500000 + 21000 * (n % 3)) \
+ if load == "busy" else 800000 + 13000 * (n % 7)
+ files.update({p + "scaling_driver": "intel_pstate\n",
+ p + "scaling_available_governors": "performance powersave\n",
+ p + "energy_performance_preference": "balance_performance\n",
+ p + "energy_performance_available_preferences":
+ "default performance balance_performance balance_power power\n",
+ p + "base_frequency": f"{base}\n"})
+ else:
+ top, cur = 3701000, 800000 - 9 * (n % 4)
+ files.update({p + "scaling_driver": "acpi-cpufreq\n",
+ p + "scaling_available_governors":
+ "conservative ondemand userspace powersave performance schedutil\n",
+ p + "scaling_available_frequencies":
+ "3701000 3700000 3500000 3300000 3100000 2900000 2700000 2500000 "
+ "2300000 2100000 1900000 1700000 1500000 1300000 1100000 900000 "
+ "800000\n",
+ p + "cpuinfo_transition_latency": "10000\n"})
+ files.update({p + "scaling_governor": "powersave\n", p + "cpuinfo_min_freq": "800000\n",
+ p + "cpuinfo_max_freq": f"{top}\n", p + "scaling_min_freq": "800000\n",
+ p + "scaling_max_freq": f"{top}\n", p + "scaling_cur_freq": f"{cur}\n",
+ p + "affected_cpus": f"{n}\n", p + "related_cpus": f"{n}\n"})
+ if driver == "intel_pstate":
+ for f, v in (("status", "active"), ("no_turbo", "0"), ("max_perf_pct", "100"),
+ ("min_perf_pct", "16"), ("hwp_dynamic_boost", "0"), ("num_pstates", "42")):
+ files["sys/devices/system/cpu/intel_pstate/" + f] = v + "\n"
+ else:
+ files["sys/devices/system/cpu/cpufreq/boost"] = "1\n"
+ return files
+
+
+def cpuinfo(mhz):
+ out = []
+ for n in list(P_CPUS) + list(E_CPUS):
+ core = n // 2 * 4 if n in P_CPUS else 24 + (n - 12)
+ out.append(
+ f"processor\t: {n}\nvendor_id\t: GenuineIntel\ncpu family\t: 6\nmodel\t\t: 151\n"
+ f"model name\t: {CPU}\nstepping\t: 2\nmicrocode\t: 0x3a\ncpu MHz\t\t: {mhz(n):.3f}\n"
+ f"cache size\t: 20480 KB\nphysical id\t: 0\nsiblings\t: 16\ncore id\t\t: {core}\n"
+ f"cpu cores\t: 10\napicid\t\t: {n if n in P_CPUS else 32 + 2 * (n - 12)}\nfpu\t\t: yes\n"
+ f"fpu_exception\t: yes\ncpuid level\t: 32\nwp\t\t: yes\nflags\t\t: {FLAGS}\n"
+ "bugs\t\t: spectre_v1 spectre_v2 spec_store_bypass swapgs eibrs_pbrsb rfds bhi\n"
+ "bogomips\t: 7372.80\nclflush size\t: 64\ncache_alignment\t: 64\n"
+ "address sizes\t: 39 bits physical, 48 bits virtual\npower management:\n")
+ return "\n".join(out)
+
+
+def dmesg(kernel, cmdline, pstate, extra=""):
+ lines = [
+ f"Linux version {kernel} (user@atlas) (clang version 21.1.8, LLD 21.1.8) #1 SMP "
+ "PREEMPT_DYNAMIC Sun Oct 11 21:02:44 CDT 2026",
+ f"Command line: {cmdline}",
+ "BIOS-provided physical RAM map:",
+ "BIOS-e820: [mem 0x0000000000000000-0x000000000009efff] usable",
+ "BIOS-e820: [mem 0x0000000000100000-0x000000006c4fefff] usable",
+ "BIOS-e820: [mem 0x0000000100000000-0x000000087f7fffff] usable",
+ "NX (Execute Disable) protection: active",
+ "SMBIOS 3.5.0 present.",
+ "DMI: ASRock Z690M-ITX/ax/Z690M-ITX/ax, BIOS 21.01 09/26/2025",
+ "tsc: Detected 3700.000 MHz processor",
+ "tsc: Detected 3686.400 MHz TSC",
+ "e820: update [mem 0x00000000-0x00000fff] usable ==> reserved",
+ "last_pfn = 0x87f800 max_arch_pfn = 0x400000000",
+ "x86/PAT: Configuration [0-7]: WB WC UC- UC WB WP UC- WT",
+ "ACPI: Early table checksum verification disabled",
+ "ACPI: RSDP 0x00000000000F05B0 000024 (v02 ALASKA)",
+ "ACPI: FACP 0x0000000069D1B000 000114 (v06 ALASKA A M I 01072009 AMI 01000013)",
+ "ACPI: SSDT 0x0000000069D26000 0001B6 (v02 ALASKA CpuSsdt 00003000 INTL 20200717)",
+ "Zone ranges:",
+ " DMA [mem 0x0000000000001000-0x0000000000ffffff]",
+ " DMA32 [mem 0x0000000001000000-0x00000000ffffffff]",
+ " Normal [mem 0x0000000100000000-0x000000087f7fffff]",
+ "percpu: Embedded 66 pages/cpu s229376 r8192 d114688 u262144",
+ f"Kernel command line: {cmdline}",
+ "Memory: 32535616K/33352676K available (22528K kernel code, 2867K rwdata, 9748K rodata)",
+ "SLUB: HWalign=64, Order=0-3, MinObjects=0, CPUs=16, Nodes=1",
+ "rcu: Preemptible hierarchical RCU implementation.",
+ "NR_IRQS: 524544, nr_irqs: 2200, preallocated irqs: 16",
+ "Console: colour dummy device 80x25",
+ "clocksource: tsc-early: mask: 0xffffffffffffffff max_cycles: 0x6a42cd84e0e",
+ "Calibrating delay loop (skipped), value calculated using timer frequency.. 7372.80 BogoMIPS",
+ "x86/cpu: User Mode Instruction Prevention (UMIP) activated",
+ "Spectre V1 : Mitigation: usercopy/swapgs barriers and __user pointer sanitization",
+ "Spectre V2 : Mitigation: Enhanced / Automatic IBRS",
+ "smpboot: CPU0: 12th Gen Intel(R) Core(TM) i5-12600KF (family: 0x6, model: 0x97, stepping: 0x2)",
+ "Performance Events: XSAVE Architectural LBR, PEBS fmt4+-baseline, AnyThread deprecated, "
+ "Alderlake Hybrid events, 32-deep LBR, full-width counters, Intel PMU driver.",
+ "core: cpu_core PMU driver: ",
+ "core: cpu_atom PMU driver: ",
+ "smp: Bringing up secondary CPUs ...",
+ "smp: Brought up 1 node, 16 CPUs",
+ "smpboot: Total of 16 processors activated (117964.80 BogoMIPS)",
+ "devtmpfs: initialized",
+ "ACPI: Interpreter enabled",
+ "ACPI: PM: (supports S0 S3 S4 S5)",
+ "PCI: Using host bridge windows from ACPI; if necessary, use \"pci=nocrs\" and report a bug",
+ "pci 0000:00:00.0: [8086:4648] type 00 class 0x060000 conventional PCI endpoint",
+ "pci 0000:00:01.0: [8086:460d] type 01 class 0x060400 PCIe Root Port",
+ "pci 0000:03:00.0: [1002:7590] type 00 class 0x030000 PCIe Legacy Endpoint",
+ "pci 0000:04:00.0: [144d:a80c] type 00 class 0x010802 PCIe Endpoint",
+ "iommu: Default domain type: Translated",
+ "clocksource: Switched to clocksource tsc-early",
+ "NET: Registered PF_INET protocol family",
+ "Freeing initrd memory: 18432K",
+ "RAPL PMU: API unit is 2^-32 Joules, 4 fixed counters, 655360 ms ovfl timer",
+ "Initialise system trusted keyrings",
+ "zbud: loaded",
+ "io scheduler mq-deadline registered",
+ "thermal LNXTHERM:00: registered as thermal_zone0",
+ ]
+ if pstate:
+ lines += ["intel_pstate: Intel P-state driver initializing",
+ "intel_pstate: HWP enabled"]
+ lines += [
+ "nvme nvme0: pci function 0000:04:00.0",
+ "nvme nvme0: 16/0/0 default/read/poll queues",
+ " nvme0n1: p1 p2 p3",
+ "EXT4-fs (nvme0n1p3): mounted filesystem 6d3e0b6f-0b0c-4c51-9a3d-6c1a4b7e2f10 ro with "
+ "ordered data mode. Quota mode: none.",
+ "Run /sbin/init as init process",
+ "udevd[412]: starting version 257.9",
+ "intel_rapl_common: Found RAPL domain package",
+ "intel_rapl_common: Found RAPL domain core",
+ "nct6775: Found NCT6798D or compatible chip at 0x2e:0x290",
+ "r8169 0000:06:00.0 eth0: RTL8125B, 9c:6b:00:4a:21:7e, XID 641, IRQ 156",
+ "iwlwifi 0000:05:00.0: Detected Intel(R) Wi-Fi 6E AX210 160MHz, REV=0x420",
+ "[drm] amdgpu kernel modesetting enabled.",
+ "amdgpu 0000:03:00.0: amdgpu: Fetched VBIOS from VFCT",
+ "amdgpu 0000:03:00.0: amdgpu: VRAM: 16304M 0x0000008000000000 - 0x00000083FAFFFFFF "
+ "(16304M used)",
+ "[drm] Initialized amdgpu 3.64.0 for 0000:03:00.0 on minor 1",
+ "snd_hda_intel 0000:00:1f.3: enabling device (0000 -> 0002)",
+ "snd_hda_codec_realtek hdaudioC0D0: autoconfig for ALC897: line_outs=1",
+ "EXT4-fs (nvme0n1p3): re-mounted 6d3e0b6f-0b0c-4c51-9a3d-6c1a4b7e2f10 r/w.",
+ "Adding 16777212k swap on /dev/nvme0n1p2. Priority:-2 extents:1 across:16777212k SS",
+ "r8169 0000:06:00.0 eth0: Link is Up - 1Gbps/Full - flow control rx/tx",
+ ]
+ stamp = [0.0] * 32 + [0.01 * i for i in range(1, 40)] + [1.2 + 0.31 * i for i in range(60)]
+ out = "".join(f"[{stamp[i]:12.6f}] {line}\n" for i, line in enumerate(lines))
+ return out + extra
+
+
+def messages(load):
+ """/var/log/messages for the last day: boot, then periodic noise (cron, chrony, NetworkManager)."""
+ out = []
+ for i in range(24 * 12):
+ h, m = divmod(14 * 60 + 20 - 5 * (24 * 12 - i), 60)
+ day, h = (11, h + 24) if h < 0 else (12, h)
+ ts = f"Oct {day} {h:02d}:{m:02d}:01"
+ if m % 15 == 0:
+ out.append(f"{ts} atlas CROND[{3100 + i}]: (root) CMD (/usr/lib/sa/sa1 1 1)")
+ if m % 30 == 5:
+ out.append(f"{ts} atlas chronyd[2088]: Selected source 192.168.4.1")
+ if i % 37 == 0:
+ out.append(f"{ts} atlas NetworkManager[2140]: <info> [{1760200000 + i * 300}.0141] "
+ "dhcp4 (eth0): state changed new lease, address=192.168.4.23")
+ if load == "busy" and i > 270:
+ out.append(f"{ts} atlas kernel: [drm] amdgpu: PCIE GART of 512M enabled.")
+ return "\n".join(out) + "\n"
+
+
+def host(*, kernel, cmdline, driver="intel_pstate", load="idle", dmesg_extra="", ps=None):
+ """-> (files, commands) for the desktop under the given kernel, cpufreq driver and load."""
+ busy = load == "busy"
+ mhz = (lambda n: 799.986 + 0.004 * n) if driver == "acpi-cpufreq" else (
+ (lambda n: 4512.3 if n in P_CPUS else 3504.0) if busy else (lambda n: 800.0 + 11.7 * n))
+ files = {
+ "etc/os-release": 'NAME=Gentoo\nID=gentoo\nPRETTY_NAME="Gentoo Linux"\nVERSION_ID="2.17"\n'
+ 'HOME_URL="https://www.gentoo.org/"\nBUG_REPORT_URL="https://bugs.gentoo.org/"\n',
+ "etc/gentoo-release": "Gentoo Base System release 2.17\n",
+ "etc/hostname": HOSTNAME + "\n",
+ "etc/conf.d/hostname": f'hostname="{HOSTNAME}"\n',
+ "etc/conf.d/cpupower": '# Options to pass to cpupower on start/stop\nSTART_OPTS="--governor '
+ 'powersave"\nSTOP_OPTS=""\nSYSFS_EXTRA=""\n',
+ "etc/fstab": "# <fs>\t\t<mountpoint>\t<type>\t<opts>\t\t<dump> <pass>\n"
+ "UUID=6d3e0b6f-0b0c-4c51-9a3d-6c1a4b7e2f10\t/\text4\tnoatime\t\t0 1\n"
+ "UUID=3A1F-9C2B\t/efi\tvfat\tumask=0077\t0 2\n"
+ "UUID=8c41e2a7-55d0-4f6e-a0b3-2f6e8d9c1b44\tnone\tswap\tsw\t0 0\n",
+ "etc/portage/make.conf": 'COMMON_FLAGS="-march=alderlake -O2 -pipe"\nCFLAGS="${COMMON_FLAGS}"\n'
+ 'CXXFLAGS="${COMMON_FLAGS}"\nMAKEOPTS="-j16 -l16"\n'
+ 'VIDEO_CARDS="amdgpu radeonsi"\nUSE="wayland pipewire vulkan -gnome"\n'
+ 'ACCEPT_LICENSE="*"\nGENTOO_MIRRORS="https://distfiles.gentoo.org"\n',
+ "proc/cpuinfo": cpuinfo(mhz),
+ "proc/cmdline": cmdline + "\n",
+ "proc/version": f"Linux version {kernel} (user@atlas) (clang version 21.1.8, LLD 21.1.8) #1 "
+ "SMP PREEMPT_DYNAMIC Sun Oct 11 21:02:44 CDT 2026\n",
+ "proc/loadavg": "15.92 15.41 12.07 19/1184 31877\n" if busy else "0.41 0.38 0.33 2/902 8811\n",
+ "proc/uptime": "62214.37 701233.10\n",
+ "proc/meminfo": "MemTotal: 32535616 kB\nMemFree: 9811244 kB\nMemAvailable: "
+ "21342780 kB\nBuffers: 402112 kB\nCached: 11012340 kB\n"
+ "SwapCached: 0 kB\nSwapTotal: 16777212 kB\nSwapFree: "
+ "16777212 kB\nShmem: 612004 kB\nHugePages_Total: 0\n",
+ "proc/mounts": "/dev/nvme0n1p3 / ext4 rw,noatime 0 0\nproc /proc proc rw,nosuid,nodev,noexec 0 0\n"
+ "sysfs /sys sysfs rw,nosuid,nodev,noexec 0 0\ndevtmpfs /dev devtmpfs rw,nosuid 0 0\n"
+ "tmpfs /run tmpfs rw,nosuid,nodev,mode=755 0 0\n/dev/nvme0n1p1 /efi vfat rw 0 0\n"
+ "tmpfs /tmp tmpfs rw,nosuid,nodev,size=16267808k 0 0\n",
+ "proc/modules": "".join(f"{m} {s} {u} - Live 0x0000000000000000\n" for m, s, u in (
+ ("amdgpu", 14954496, 34), ("iwlmvm", 815104, 0), ("iwlwifi", 581632, 1),
+ ("r8169", 122880, 0), ("snd_hda_codec_realtek", 225280, 1), ("snd_hda_intel", 65536, 3),
+ ("nct6775", 94208, 0), ("coretemp", 20480, 0), ("intel_rapl_msr", 20480, 0),
+ ("x86_pkg_temp_thermal", 20480, 0), ("btusb", 77824, 0), ("wireguard", 118784, 0))),
+ "var/log/messages": messages(load),
+ "root/.bash_history": "",
+ }
+ for level, svcs in SERVICES.items():
+ for s in svcs:
+ files[f"etc/init.d/{s}"] = f"#!/sbin/openrc-run\n# {s}\n"
+ files[f"etc/runlevels/{level}/{s}"] = Symlink(f"/etc/init.d/{s}")
+ files.update(cpufreq(driver, load))
+ up = "1 day, 1:16" if not busy else "17:16"
+ la = "15.92, 15.41, 12.07" if busy else "0.41, 0.38, 0.33"
+ commands = {
+ "uname": "Linux\n",
+ "uname -r": kernel + "\n",
+ "uname -m": "x86_64\n",
+ "uname -a": f"Linux {HOSTNAME} {kernel} #1 SMP PREEMPT_DYNAMIC Sun Oct 11 21:02:44 CDT 2026 "
+ f"x86_64 {CPU} GenuineIntel GNU/Linux\n",
+ "hostname": HOSTNAME + "\n",
+ "date": NOW + "\n",
+ "nproc": "16\n",
+ "uptime": f" 14:20:07 up {up}, 2 users, load average: {la}\n",
+ "free": " total used free shared buff/cache available\n"
+ "Mem: 32535616 11192832 9811244 612004 11414452 21342780\n"
+ "Swap: 16777212 0 16777212\n",
+ "free -h": " total used free shared buff/cache available\n"
+ "Mem: 31Gi 10Gi 9.4Gi 597Mi 10Gi 20Gi\n"
+ "Swap: 15Gi 0B 15Gi\n",
+ "df": "Filesystem 1K-blocks Used Available Use% Mounted on\n"
+ "/dev/nvme0n1p3 959863856 412088120 498910384 46% /\n"
+ "/dev/nvme0n1p1 523248 91204 432044 18% /efi\n"
+ "tmpfs 16267808 604112 15663696 4% /tmp\n",
+ "df -h": "Filesystem Size Used Avail Use% Mounted on\n/dev/nvme0n1p3 916G 393G 476G 46% /\n"
+ "/dev/nvme0n1p1 511M 90M 422M 18% /efi\ntmpfs 16G 590M 15G 4% /tmp\n",
+ "dmesg": dmesg(kernel, cmdline, driver == "intel_pstate", dmesg_extra),
+ "lspci": "00:00.0 Host bridge: Intel Corporation 12th Gen Core Processor Host Bridge/DRAM "
+ "Registers (rev 02)\n00:01.0 PCI bridge: Intel Corporation 12th Gen Core Processor PCI "
+ "Express x16 Controller #1 (rev 02)\n00:14.0 USB controller: Intel Corporation Alder "
+ "Lake-S PCH USB 3.2 Gen 2x2 XHCI Controller (rev 11)\n00:1f.3 Audio device: Intel "
+ "Corporation Alder Lake-S HD Audio Controller (rev 11)\n00:1f.4 SMBus: Intel Corporation "
+ "Alder Lake-S PCH SMBus Controller (rev 11)\n03:00.0 VGA compatible controller: Advanced "
+ "Micro Devices, Inc. [AMD/ATI] Navi 44 [Radeon RX 9060 XT] (rev c0)\n04:00.0 Non-Volatile "
+ "memory controller: Samsung Electronics Co Ltd NVMe SSD Controller PM9C1a\n05:00.0 Network "
+ "controller: Intel Corporation Wi-Fi 6E(802.11ax) AX210/AX1675* 2x2 [Typhoon Peak] (rev "
+ "1a)\n06:00.0 Ethernet controller: Realtek Semiconductor Co., Ltd. RTL8125 2.5GbE "
+ "Controller (rev 05)\n",
+ "lscpu": f"Architecture: x86_64\n CPU op-mode(s): 32-bit, 64-bit\n"
+ f" Address sizes: 39 bits physical, 48 bits virtual\nCPU(s): 16\n"
+ f" On-line CPU(s) list: 0-15\nVendor ID: GenuineIntel\n"
+ f" Model name: {CPU}\n CPU family: 6\n Model: 151\n"
+ f" Thread(s) per core: 2\n Core(s) per socket: 10\n Socket(s): 1\n"
+ f" Stepping: 2\n CPU(s) scaling MHz: "
+ f"{'22' if driver == 'acpi-cpufreq' else '16'}%\n CPU max MHz: "
+ f"{'3701.0000' if driver == 'acpi-cpufreq' else '4900.0000'}\n"
+ f" CPU min MHz: 800.0000\n BogoMIPS: 7372.80\n"
+ f"Caches (sum of all):\n L1d: 416 KiB (10 instances)\n"
+ f" L2: 9.5 MiB (7 instances)\n L3: 20 MiB (1 instance)\n",
+ "rc-status": "Runlevel: default\n" + "".join(
+ f" {s:<52}[ started ]\n" for s in SERVICES["default"]) + "Dynamic Runlevel: hotplugged\n",
+ "sensors": "coretemp-isa-0000\nAdapter: ISA adapter\nPackage id 0: "
+ + ("+41.0°C" if busy else "+34.0°C") + " (high = +80.0°C, crit = +100.0°C)\n"
+ "Core 0: +38.0°C (high = +80.0°C, crit = +100.0°C)\n\n"
+ "nct6798-isa-0290\nAdapter: ISA adapter\nin0: "
+ + ("744.00 mV" if busy else "632.00 mV") + " (min = +0.00 V, max = +1.74 V)\n"
+ "fan2: " + ("812 RPM" if busy else "640 RPM") + " (min = 0 RPM)\n"
+ "CPUTIN: +35.5°C (high = +80.0°C, hyst = +75.0°C)\n\n"
+ "amdgpu-pci-0300\nAdapter: PCI adapter\nedge: +36.0°C (crit = +100.0°C)\n"
+ "junction: +38.0°C (crit = +110.0°C)\nPPT: 8.00 W (cap = 160.00 W)\n",
+ "ps": ps or "PID USER TIME COMMAND\n 1 root 0:01 init [3]\n 2088 ntp 0:00 "
+ "/usr/sbin/chronyd\n 2140 root 0:03 /usr/sbin/NetworkManager --pid-file "
+ "/run/NetworkManager.pid\n 2201 root 0:00 /usr/sbin/crond\n 2733 user 2:11 "
+ "/usr/bin/kwin_wayland --xwayland\n 2790 user 5:40 /usr/lib64/firefox/firefox\n",
+ }
+ commands["ps aux"] = commands["ps -ef"] = commands["ps"]
+ commands["top"] = commands["top -bn1"] = commands["top -b -n 1"] = (
+ f"top - 14:20:07 up {up}, 2 users, load average: {la}\n"
+ "%Cpu(s): " + ("97.8 us, 1.9 sy, 0.0 ni, 0.3 id" if busy else "1.2 us, 0.6 sy, 0.0 ni, 98.1 id")
+ + ", 0.0 wa, 0.0 hi, 0.0 si, 0.0 st\n" + commands["ps"])
+ return files, commands
+
+
+def gz(text):
+ """Deterministic gzip (mtime 0) for /proc/config.gz."""
+ return gzip.compress(text.encode(), mtime=0)
diff --git a/bench/tasks/sleuth_cases/_ramsleuth-dmidecode.txt b/bench/tasks/sleuth_cases/_ramsleuth-dmidecode.txt
new file mode 100644
index 0000000..f3f6af8
--- /dev/null
+++ b/bench/tasks/sleuth_cases/_ramsleuth-dmidecode.txt
@@ -0,0 +1,75 @@
+# dmidecode 3.7
+
+Getting SMBIOS data from sysfs.
+SMBIOS 3.5.0 present.
+
+Handle 0x000C, DMI type 17, 92 bytes
+Memory Device
+Array Handle: 0x000B
+Error Information Handle: Not Provided
+Total Width: 64 bits
+Data Width: 64 bits
+Size: 16 GiB
+Form Factor: DIMM
+Set: None
+Locator: Controller0-ChannelA-DIMM0
+Bank Locator: BANK 0
+Type: DDR4
+Type Detail: Synchronous
+Speed: 2400 MT/s
+Manufacturer: Team Group Inc
+Serial Number: SER10001
+Asset Tag: 9876543210
+Part Number: TEAMGROUP-UD4-3600
+Rank: 1
+Configured Memory Speed: 3600 MT/s
+Minimum Voltage: 1.2 V
+Maximum Voltage: 1.35 V
+Configured Voltage: 1.2 V
+Memory Technology: DRAM
+Memory Operating Mode Capability: Volatile memory
+Firmware Version: Not Specified
+Module Manufacturer ID: Bank 5, Hex 0xEF
+Module Product ID: Unknown
+Memory Subsystem Controller Manufacturer ID: Unknown
+Memory Subsystem Controller Product ID: Unknown
+Non-Volatile Size: None
+Volatile Size: 16 GiB
+Cache Size: None
+Logical Size: None
+
+Handle 0x000D, DMI type 17, 92 bytes
+Memory Device
+Array Handle: 0x000B
+Error Information Handle: Not Provided
+Total Width: 64 bits
+Data Width: 64 bits
+Size: 16 GiB
+Form Factor: DIMM
+Set: None
+Locator: Controller1-ChannelA-DIMM0
+Bank Locator: BANK 0
+Type: DDR4
+Type Detail: Synchronous
+Speed: 2400 MT/s
+Manufacturer: Team Group Inc
+Serial Number: SER10002
+Asset Tag: 9876543210
+Part Number: TEAMGROUP-UD4-3600
+Rank: 1
+Configured Memory Speed: 3600 MT/s
+Minimum Voltage: 1.2 V
+Maximum Voltage: 1.35 V
+Configured Voltage: 1.2 V
+Memory Technology: DRAM
+Memory Operating Mode Capability: Volatile memory
+Firmware Version: Not Specified
+Module Manufacturer ID: Bank 5, Hex 0xEF
+Module Product ID: Unknown
+Memory Subsystem Controller Manufacturer ID: Unknown
+Memory Subsystem Controller Product ID: Unknown
+Non-Volatile Size: None
+Volatile Size: 16 GiB
+Cache Size: None
+Logical Size: None
+
diff --git a/bench/tasks/sleuth_cases/_ramsleuth-probe.md b/bench/tasks/sleuth_cases/_ramsleuth-probe.md
new file mode 100644
index 0000000..e4ceb60
--- /dev/null
+++ b/bench/tasks/sleuth_cases/_ramsleuth-probe.md
@@ -0,0 +1,596 @@
+# RamSleuth Probe Report
+
+> **12th Gen Intel(R) Core™ i5-12600KF** — AlderLake on linux (kernel 7.3.0-rc5-tkg-bore-llvm), RamSleuth v2.4.14
+
+## System
+
+| Field | Value |
+|----|----|
+| CPU | 12th Gen Intel(R) Core™ i5-12600KF |
+| Vendor | Intel |
+| Generation | AlderLake |
+| PCI Host Bridge | 0x4648 |
+| Kernel | 7.3.0-rc5-tkg-bore-llvm |
+| OS | linux |
+| Arch | x86_64 |
+| RamSleuth Version | 2.4.14 |
+| Telemetry Source | dev-mem |
+
+## Decoded Telemetry
+
+### CPU
+
+| Field | Value |
+|----|----|
+| vendor | Intel AlderLake |
+| brand | 12th Gen Intel(R) Core™ i5-12600KF |
+| CPU Core Voltage | 0.704 V \[est\] |
+
+### AMD
+
+N/A (unsupported hardware)
+
+### Intel
+
+| Field | Value |
+|----|----|
+| channel mode | Single-Channel |
+
+#### Channel 0
+
+| Clock | Value |
+|----|----|
+| MCLK | 3600.00 MHz |
+| MT/s | 7200 MT/s |
+| UCLK | 3600.00 MHz |
+| FCLK | N/A (not applicable) |
+| UCLK:MCLK | N/A (not applicable) |
+| gear mode | 1x |
+| GDM | N/A (not applicable) |
+| PDM | N/A (not applicable) |
+| command rate | N/A (not applicable) |
+
+
+| Timing (ticks) | Value |
+|----|----|
+| tCL | N/A (parse error: tCL 0 ticks outside plausible range \[1, 2048\]) |
+| tRCDWR | 2 |
+| tRCDRD | 2 |
+| tRP | 8 |
+| tRAS | N/A (parse error: tRAS 0 ticks outside plausible range \[1, 2048\]) |
+| tRC | N/A (not applicable) |
+| tRRDS | 4 |
+| tRRLD | N/A (parse error: tRRD_L 0 ticks outside plausible range \[1, 2048\]) |
+| tFAW | N/A (parse error: tFAW 0 ticks outside plausible range \[1, 2048\]) |
+| tWTRS | 26 |
+| tWTRL | 2 |
+| tWR | N/A (parse error: tWR 0 ticks outside plausible range \[1, 2048\]) |
+| tRFC1 | 1024 |
+| tRFC2 | N/A (not applicable) |
+| tRFCsb | N/A (parse error: tRFCsb 0 ticks outside plausible range \[1, 2048\]) |
+| tCWL | 1 |
+| tRTP | 1 |
+| tRDWR | N/A (not applicable) |
+| tWRRD | N/A (not applicable) |
+| tRDRD(SD) | N/A (parse error: tRDRD(dr) 0 ticks outside plausible range \[1, 2048\]) |
+| tRDRD(CCD) | N/A (parse error: tRDRD(dd) 0 ticks outside plausible range \[1, 2048\]) |
+| tRDRD(SCL) | N/A (parse error: tRDRD(sg) 0 ticks outside plausible range \[1, 2048\]) |
+| tRDRD(SC) | N/A (parse error: tRDRD(dg) 0 ticks outside plausible range \[1, 2048\]) |
+| tWRWR(SD) | N/A (not applicable) |
+| tWRWR(CCD) | N/A (not applicable) |
+| tWRWR(SCL) | N/A (parse error: tWRWR(sg) 0 ticks outside plausible range \[1, 2048\]) |
+| tWRWR(SC) | N/A (parse error: tWRWR(dg) 0 ticks outside plausible range \[1, 2048\]) |
+
+
+| CAD bus (ohms) | Value |
+|----|----|
+| proc ODT | N/A (not applicable) |
+| RTT nom | N/A (not applicable) |
+| RTT wr | N/A (not applicable) |
+| RTT park | N/A (not applicable) |
+| CLK drive | N/A (not applicable) |
+| ADD/CMD drive | N/A (not applicable) |
+| CS/ODT drive | N/A (not applicable) |
+| CKE drive | N/A (not applicable) |
+
+
+| Rail (V) | Value |
+|----|----|
+| VDDCR_SOC | N/A (not applicable) |
+| VDDIO_MEM | N/A (not applicable) |
+| VDD_MISC | N/A (not applicable) |
+| VPP | N/A (not applicable) |
+
+
+| RTL (ticks) | Value |
+|----|----|
+| RTL | N/A (not applicable) |
+
+#### Channel 1
+
+| Clock | Value |
+|----|----|
+| MCLK | 3600.00 MHz |
+| MT/s | 7200 MT/s |
+| UCLK | 3600.00 MHz |
+| FCLK | N/A (not applicable) |
+| UCLK:MCLK | N/A (not applicable) |
+| gear mode | 1x |
+| GDM | N/A (not applicable) |
+| PDM | N/A (not applicable) |
+| command rate | N/A (not applicable) |
+
+
+| Timing (ticks) | Value |
+|----|----|
+| tCL | N/A (parse error: tCL: register read failed) |
+| tRCDWR | N/A (parse error: tRCD: register read failed) |
+| tRCDRD | N/A (parse error: tRCD: register read failed) |
+| tRP | N/A (parse error: tRP: register read failed) |
+| tRAS | N/A (parse error: tRAS: register read failed) |
+| tRC | N/A (not applicable) |
+| tRRDS | N/A (parse error: tRRD_S: register read failed) |
+| tRRLD | N/A (parse error: tRRD_L: register read failed) |
+| tFAW | N/A (parse error: tFAW: register read failed) |
+| tWTRS | N/A (parse error: tWTR_S: register read failed) |
+| tWTRL | N/A (parse error: tWTR_L: register read failed) |
+| tWR | N/A (parse error: tWR: register read failed) |
+| tRFC1 | N/A (parse error: tRFC1: register read failed) |
+| tRFC2 | N/A (not applicable) |
+| tRFCsb | N/A (parse error: tRFCsb: register read failed) |
+| tCWL | N/A (parse error: tCWL: register read failed) |
+| tRTP | N/A (parse error: tRTP: register read failed) |
+| tRDWR | N/A (not applicable) |
+| tWRRD | N/A (not applicable) |
+| tRDRD(SD) | N/A (parse error: tRDRD(dr): register read failed) |
+| tRDRD(CCD) | N/A (parse error: tRDRD(dd): register read failed) |
+| tRDRD(SCL) | N/A (parse error: tRDRD(sg): register read failed) |
+| tRDRD(SC) | N/A (parse error: tRDRD(dg): register read failed) |
+| tWRWR(SD) | N/A (not applicable) |
+| tWRWR(CCD) | N/A (not applicable) |
+| tWRWR(SCL) | N/A (parse error: tWRWR(sg): register read failed) |
+| tWRWR(SC) | N/A (parse error: tWRWR(dg): register read failed) |
+
+
+| CAD bus (ohms) | Value |
+|----|----|
+| proc ODT | N/A (not applicable) |
+| RTT nom | N/A (not applicable) |
+| RTT wr | N/A (not applicable) |
+| RTT park | N/A (not applicable) |
+| CLK drive | N/A (not applicable) |
+| ADD/CMD drive | N/A (not applicable) |
+| CS/ODT drive | N/A (not applicable) |
+| CKE drive | N/A (not applicable) |
+
+
+| Rail (V) | Value |
+|----|----|
+| VDDCR_SOC | N/A (not applicable) |
+| VDDIO_MEM | N/A (not applicable) |
+| VDD_MISC | N/A (not applicable) |
+| VPP | N/A (not applicable) |
+
+
+| RTL (ticks) | Value |
+|----|----|
+| RTL | N/A (not applicable) |
+
+#### Channel 2
+
+| Clock | Value |
+|----|----|
+| MCLK | 3600.00 MHz |
+| MT/s | 7200 MT/s |
+| UCLK | 3600.00 MHz |
+| FCLK | N/A (not applicable) |
+| UCLK:MCLK | N/A (not applicable) |
+| gear mode | 1x |
+| GDM | N/A (not applicable) |
+| PDM | N/A (not applicable) |
+| command rate | N/A (not applicable) |
+
+
+| Timing (ticks) | Value |
+|----|----|
+| tCL | N/A (parse error: tCL 0 ticks outside plausible range \[1, 2048\]) |
+| tRCDWR | N/A (parse error: tRCD 0 ticks outside plausible range \[1, 2048\]) |
+| tRCDRD | N/A (parse error: tRCD 0 ticks outside plausible range \[1, 2048\]) |
+| tRP | N/A (parse error: tRP 0 ticks outside plausible range \[1, 2048\]) |
+| tRAS | N/A (parse error: tRAS 0 ticks outside plausible range \[1, 2048\]) |
+| tRC | N/A (not applicable) |
+| tRRDS | 1 |
+| tRRLD | N/A (parse error: tRRD_L 0 ticks outside plausible range \[1, 2048\]) |
+| tFAW | N/A (parse error: tFAW 0 ticks outside plausible range \[1, 2048\]) |
+| tWTRS | N/A (parse error: tWTR_S 0 ticks outside plausible range \[1, 2048\]) |
+| tWTRL | 24 |
+| tWR | N/A (parse error: tWR 0 ticks outside plausible range \[1, 2048\]) |
+| tRFC1 | N/A (parse error: tRFC1 0 ticks outside plausible range \[1, 2048\]) |
+| tRFC2 | N/A (not applicable) |
+| tRFCsb | N/A (parse error: tRFCsb 0 ticks outside plausible range \[1, 2048\]) |
+| tCWL | 16 |
+| tRTP | 16 |
+| tRDWR | N/A (not applicable) |
+| tWRRD | N/A (not applicable) |
+| tRDRD(SD) | N/A (parse error: tRDRD(dr) 0 ticks outside plausible range \[1, 2048\]) |
+| tRDRD(CCD) | N/A (parse error: tRDRD(dd) 0 ticks outside plausible range \[1, 2048\]) |
+| tRDRD(SCL) | N/A (parse error: tRDRD(sg) 0 ticks outside plausible range \[1, 2048\]) |
+| tRDRD(SC) | N/A (parse error: tRDRD(dg) 0 ticks outside plausible range \[1, 2048\]) |
+| tWRWR(SD) | N/A (not applicable) |
+| tWRWR(CCD) | N/A (not applicable) |
+| tWRWR(SCL) | N/A (parse error: tWRWR(sg) 0 ticks outside plausible range \[1, 2048\]) |
+| tWRWR(SC) | N/A (parse error: tWRWR(dg) 0 ticks outside plausible range \[1, 2048\]) |
+
+
+| CAD bus (ohms) | Value |
+|----|----|
+| proc ODT | N/A (not applicable) |
+| RTT nom | N/A (not applicable) |
+| RTT wr | N/A (not applicable) |
+| RTT park | N/A (not applicable) |
+| CLK drive | N/A (not applicable) |
+| ADD/CMD drive | N/A (not applicable) |
+| CS/ODT drive | N/A (not applicable) |
+| CKE drive | N/A (not applicable) |
+
+
+| Rail (V) | Value |
+|----|----|
+| VDDCR_SOC | N/A (not applicable) |
+| VDDIO_MEM | N/A (not applicable) |
+| VDD_MISC | N/A (not applicable) |
+| VPP | N/A (not applicable) |
+
+
+| RTL (ticks) | Value |
+|----|----|
+| RTL | N/A (not applicable) |
+
+#### Channel 3
+
+| Clock | Value |
+|----|----|
+| MCLK | 3600.00 MHz |
+| MT/s | 7200 MT/s |
+| UCLK | 3600.00 MHz |
+| FCLK | N/A (not applicable) |
+| UCLK:MCLK | N/A (not applicable) |
+| gear mode | 1x |
+| GDM | N/A (not applicable) |
+| PDM | N/A (not applicable) |
+| command rate | N/A (not applicable) |
+
+
+| Timing (ticks) | Value |
+|----|----|
+| tCL | N/A (parse error: tCL: register read failed) |
+| tRCDWR | N/A (parse error: tRCD: register read failed) |
+| tRCDRD | N/A (parse error: tRCD: register read failed) |
+| tRP | N/A (parse error: tRP: register read failed) |
+| tRAS | N/A (parse error: tRAS: register read failed) |
+| tRC | N/A (not applicable) |
+| tRRDS | N/A (parse error: tRRD_S: register read failed) |
+| tRRLD | N/A (parse error: tRRD_L: register read failed) |
+| tFAW | N/A (parse error: tFAW: register read failed) |
+| tWTRS | N/A (parse error: tWTR_S: register read failed) |
+| tWTRL | N/A (parse error: tWTR_L: register read failed) |
+| tWR | N/A (parse error: tWR: register read failed) |
+| tRFC1 | N/A (parse error: tRFC1: register read failed) |
+| tRFC2 | N/A (not applicable) |
+| tRFCsb | N/A (parse error: tRFCsb: register read failed) |
+| tCWL | N/A (parse error: tCWL: register read failed) |
+| tRTP | N/A (parse error: tRTP: register read failed) |
+| tRDWR | N/A (not applicable) |
+| tWRRD | N/A (not applicable) |
+| tRDRD(SD) | N/A (parse error: tRDRD(dr): register read failed) |
+| tRDRD(CCD) | N/A (parse error: tRDRD(dd): register read failed) |
+| tRDRD(SCL) | N/A (parse error: tRDRD(sg): register read failed) |
+| tRDRD(SC) | N/A (parse error: tRDRD(dg): register read failed) |
+| tWRWR(SD) | N/A (not applicable) |
+| tWRWR(CCD) | N/A (not applicable) |
+| tWRWR(SCL) | N/A (parse error: tWRWR(sg): register read failed) |
+| tWRWR(SC) | N/A (parse error: tWRWR(dg): register read failed) |
+
+
+| CAD bus (ohms) | Value |
+|----|----|
+| proc ODT | N/A (not applicable) |
+| RTT nom | N/A (not applicable) |
+| RTT wr | N/A (not applicable) |
+| RTT park | N/A (not applicable) |
+| CLK drive | N/A (not applicable) |
+| ADD/CMD drive | N/A (not applicable) |
+| CS/ODT drive | N/A (not applicable) |
+| CKE drive | N/A (not applicable) |
+
+
+| Rail (V) | Value |
+|----|----|
+| VDDCR_SOC | N/A (not applicable) |
+| VDDIO_MEM | N/A (not applicable) |
+| VDD_MISC | N/A (not applicable) |
+| VPP | N/A (not applicable) |
+
+
+| RTL (ticks) | Value |
+|----|----|
+| RTL | N/A (not applicable) |
+
+### SPD
+
+#### Module 0x50 (DDR4)
+
+| Field | Value |
+|----|----|
+| maker | 0xEF (bank 5) |
+| die maker | SK hynix |
+| die type | N/A (not applicable) |
+| devices | 8 |
+| part | TEAMGROUP-UD4-3600 |
+| serial | SER10001 |
+| rank | 1 |
+| density | 16384 Mbit |
+| speed | 3200 MT/s |
+
+* profile 1 (XMP): 3200 MT/s, 15-19-19-37 @ 1.350 V
+
+### Platform
+
+| Field | Value |
+|----|----|
+| CPU clock (MHz) | 799.15 MHz |
+| motherboard | Z690M-ITX/ax |
+| BIOS | 21.01 + 09/26/2025 |
+| AGESA | N/A (not applicable) |
+| SMU version | N/A (not applicable) |
+| total capacity | 31.2 GiB |
+| per-DIMM sizes | 16.0 GiB |
+
+## Raw Registers
+
+| Register | Value |
+|----|----|
+| MC_BIOS_REQ | 0x79E00124 |
+| TC_CH0_DBP | 0xFFFFFFFF |
+| TC_CH0_RAP | 0xFFFFFFFF |
+| TC_CH0_RFP | 0xFFFFFFFF |
+| TC_CH0_RAP2 | 0xFFFFFFFF |
+| TC_CH0_RDRD | 0xFFFFFFFF |
+| TC_CH0_RDWR | 0xFFFFFFFF |
+| TC_CH0_WRRD | 0xFFFFFFFF |
+| TC_CH0_WRWR | 0xFFFFFFFF |
+| TC_CH1_DBP | 0xFFFFFFFF |
+| TC_CH1_RAP | 0xFFFFFFFF |
+| TC_CH1_RFP | 0xFFFFFFFF |
+| TC_CH1_RAP2 | 0xFFFFFFFF |
+| TC_CH1_RDRD | 0xFFFFFFFF |
+| TC_CH1_RDWR | 0xFFFFFFFF |
+| TC_CH1_WRRD | 0xFFFFFFFF |
+| TC_CH1_WRWR | 0xFFFFFFFF |
+| TC_CH2_DBP | 0xFFFFFFFF |
+| TC_CH2_RAP | 0xFFFFFFFF |
+| TC_CH2_RFP | 0xFFFFFFFF |
+| TC_CH2_RAP2 | 0xFFFFFFFF |
+| TC_CH2_RDRD | 0xFFFFFFFF |
+| TC_CH2_RDWR | 0xFFFFFFFF |
+| TC_CH2_WRRD | 0xFFFFFFFF |
+| TC_CH2_WRWR | 0xFFFFFFFF |
+| TC_CH3_DBP | 0xFFFFFFFF |
+| TC_CH3_RAP | 0xFFFFFFFF |
+| TC_CH3_RFP | 0xFFFFFFFF |
+| TC_CH3_RAP2 | 0xFFFFFFFF |
+| TC_CH3_RDRD | 0xFFFFFFFF |
+| TC_CH3_RDWR | 0xFFFFFFFF |
+| TC_CH3_WRRD | 0xFFFFFFFF |
+| TC_CH3_WRWR | 0xFFFFFFFF |
+| MCL0_PRE | 0x01000208 |
+| MCL0_ACT | 0x00000400 |
+| MCL0_ACT2 | 0xFFFFFFFF |
+| MCL0_WTR | 0x0100021A |
+| MCL0_RFP | 0x00000400 |
+| MCL0_RFP2 | 0x00000000 |
+| MCL0_RDRD | 0x00000000 |
+| MCL0_WRWR | 0x00620000 |
+| MCL1_PRE | 0x10000000 |
+| MCL1_ACT | 0x00000100 |
+| MCL1_ACT2 | 0x00000000 |
+| MCL1_WTR | 0x10001800 |
+| MCL1_RFP | 0x00000000 |
+| MCL1_RFP2 | 0x00000000 |
+| MCL1_RDRD | 0x00000000 |
+| MCL1_WRWR | 0x00000000 |
+| MAD_INTER_CHANNEL | N/A (absent) |
+| MAD_INTRA_CH0 | N/A (absent) |
+| MAD_INTRA_CH1 | N/A (absent) |
+| MAD_DIMM_CH0 | N/A (absent) |
+| MAD_DIMM_CH1 | N/A (absent) |
+| MAD_DIMM_CH2 | N/A (absent) |
+| MAD_DIMM_CH3 | N/A (absent) |
+| MCHBAR_BASE | 0xFEDC0000 |
+| MCHBAR_ENABLED | true |
+
+## N/A Reasons
+
+* `amd (whole branch)` — N/A (unsupported hardware)
+* `intel.ch0.clocks.fclk` — N/A (not applicable)
+* `intel.ch0.clocks.div_mode` — N/A (not applicable)
+* `intel.ch0.clocks.gdm` — N/A (not applicable)
+* `intel.ch0.clocks.pdm` — N/A (not applicable)
+* `intel.ch0.clocks.command_rate` — N/A (not applicable)
+* `intel.ch0.timings.cl` — N/A (parse error: tCL 0 ticks outside plausible range \[1, 2048\])
+* `intel.ch0.timings.ras` — N/A (parse error: tRAS 0 ticks outside plausible range \[1, 2048\])
+* `intel.ch0.timings.rc` — N/A (not applicable)
+* `intel.ch0.timings.rrld` — N/A (parse error: tRRD_L 0 ticks outside plausible range \[1, 2048\])
+* `intel.ch0.timings.faw` — N/A (parse error: tFAW 0 ticks outside plausible range \[1, 2048\])
+* `intel.ch0.timings.wr` — N/A (parse error: tWR 0 ticks outside plausible range \[1, 2048\])
+* `intel.ch0.timings.rfc2` — N/A (not applicable)
+* `intel.ch0.timings.rfcsb` — N/A (parse error: tRFCsb 0 ticks outside plausible range \[1, 2048\])
+* `intel.ch0.timings.rdwr` — N/A (not applicable)
+* `intel.ch0.timings.wrrd` — N/A (not applicable)
+* `intel.ch0.timings.rdrd_sd` — N/A (parse error: tRDRD(dr) 0 ticks outside plausible range \[1, 2048\])
+* `intel.ch0.timings.rdrd_dd` — N/A (parse error: tRDRD(dd) 0 ticks outside plausible range \[1, 2048\])
+* `intel.ch0.timings.rdrd_scl` — N/A (parse error: tRDRD(sg) 0 ticks outside plausible range \[1, 2048\])
+* `intel.ch0.timings.rdrd_sc` — N/A (parse error: tRDRD(dg) 0 ticks outside plausible range \[1, 2048\])
+* `intel.ch0.timings.wrwr_sd` — N/A (not applicable)
+* `intel.ch0.timings.wrwr_dd` — N/A (not applicable)
+* `intel.ch0.timings.wrwr_scl` — N/A (parse error: tWRWR(sg) 0 ticks outside plausible range \[1, 2048\])
+* `intel.ch0.timings.wrwr_sc` — N/A (parse error: tWRWR(dg) 0 ticks outside plausible range \[1, 2048\])
+* `intel.ch0.cad_bus.proc_odt` — N/A (not applicable)
+* `intel.ch0.cad_bus.rtt_nom` — N/A (not applicable)
+* `intel.ch0.cad_bus.rtt_wr` — N/A (not applicable)
+* `intel.ch0.cad_bus.rtt_park` — N/A (not applicable)
+* `intel.ch0.cad_bus.clk_drv` — N/A (not applicable)
+* `intel.ch0.cad_bus.addr_cmd_drv` — N/A (not applicable)
+* `intel.ch0.cad_bus.cs_odt_drv` — N/A (not applicable)
+* `intel.ch0.cad_bus.cke_drv` — N/A (not applicable)
+* `intel.ch0.voltages.vddcr_soc` — N/A (not applicable)
+* `intel.ch0.voltages.vddio_mem` — N/A (not applicable)
+* `intel.ch0.voltages.vdd_misc` — N/A (not applicable)
+* `intel.ch0.voltages.vpp` — N/A (not applicable)
+* `intel.ch0.rtl` — N/A (not applicable)
+* `intel.ch1.clocks.fclk` — N/A (not applicable)
+* `intel.ch1.clocks.div_mode` — N/A (not applicable)
+* `intel.ch1.clocks.gdm` — N/A (not applicable)
+* `intel.ch1.clocks.pdm` — N/A (not applicable)
+* `intel.ch1.clocks.command_rate` — N/A (not applicable)
+* `intel.ch1.timings.cl` — N/A (parse error: tCL: register read failed)
+* `intel.ch1.timings.rcwdwr` — N/A (parse error: tRCD: register read failed)
+* `intel.ch1.timings.rcdrd` — N/A (parse error: tRCD: register read failed)
+* `intel.ch1.timings.rp` — N/A (parse error: tRP: register read failed)
+* `intel.ch1.timings.ras` — N/A (parse error: tRAS: register read failed)
+* `intel.ch1.timings.rc` — N/A (not applicable)
+* `intel.ch1.timings.rrds` — N/A (parse error: tRRD_S: register read failed)
+* `intel.ch1.timings.rrld` — N/A (parse error: tRRD_L: register read failed)
+* `intel.ch1.timings.faw` — N/A (parse error: tFAW: register read failed)
+* `intel.ch1.timings.wtrs` — N/A (parse error: tWTR_S: register read failed)
+* `intel.ch1.timings.wtrl` — N/A (parse error: tWTR_L: register read failed)
+* `intel.ch1.timings.wr` — N/A (parse error: tWR: register read failed)
+* `intel.ch1.timings.rfc1` — N/A (parse error: tRFC1: register read failed)
+* `intel.ch1.timings.rfc2` — N/A (not applicable)
+* `intel.ch1.timings.rfcsb` — N/A (parse error: tRFCsb: register read failed)
+* `intel.ch1.timings.cwl` — N/A (parse error: tCWL: register read failed)
+* `intel.ch1.timings.rtp` — N/A (parse error: tRTP: register read failed)
+* `intel.ch1.timings.rdwr` — N/A (not applicable)
+* `intel.ch1.timings.wrrd` — N/A (not applicable)
+* `intel.ch1.timings.rdrd_sd` — N/A (parse error: tRDRD(dr): register read failed)
+* `intel.ch1.timings.rdrd_dd` — N/A (parse error: tRDRD(dd): register read failed)
+* `intel.ch1.timings.rdrd_scl` — N/A (parse error: tRDRD(sg): register read failed)
+* `intel.ch1.timings.rdrd_sc` — N/A (parse error: tRDRD(dg): register read failed)
+* `intel.ch1.timings.wrwr_sd` — N/A (not applicable)
+* `intel.ch1.timings.wrwr_dd` — N/A (not applicable)
+* `intel.ch1.timings.wrwr_scl` — N/A (parse error: tWRWR(sg): register read failed)
+* `intel.ch1.timings.wrwr_sc` — N/A (parse error: tWRWR(dg): register read failed)
+* `intel.ch1.cad_bus.proc_odt` — N/A (not applicable)
+* `intel.ch1.cad_bus.rtt_nom` — N/A (not applicable)
+* `intel.ch1.cad_bus.rtt_wr` — N/A (not applicable)
+* `intel.ch1.cad_bus.rtt_park` — N/A (not applicable)
+* `intel.ch1.cad_bus.clk_drv` — N/A (not applicable)
+* `intel.ch1.cad_bus.addr_cmd_drv` — N/A (not applicable)
+* `intel.ch1.cad_bus.cs_odt_drv` — N/A (not applicable)
+* `intel.ch1.cad_bus.cke_drv` — N/A (not applicable)
+* `intel.ch1.voltages.vddcr_soc` — N/A (not applicable)
+* `intel.ch1.voltages.vddio_mem` — N/A (not applicable)
+* `intel.ch1.voltages.vdd_misc` — N/A (not applicable)
+* `intel.ch1.voltages.vpp` — N/A (not applicable)
+* `intel.ch1.rtl` — N/A (not applicable)
+* `intel.ch2.clocks.fclk` — N/A (not applicable)
+* `intel.ch2.clocks.div_mode` — N/A (not applicable)
+* `intel.ch2.clocks.gdm` — N/A (not applicable)
+* `intel.ch2.clocks.pdm` — N/A (not applicable)
+* `intel.ch2.clocks.command_rate` — N/A (not applicable)
+* `intel.ch2.timings.cl` — N/A (parse error: tCL 0 ticks outside plausible range \[1, 2048\])
+* `intel.ch2.timings.rcwdwr` — N/A (parse error: tRCD 0 ticks outside plausible range \[1, 2048\])
+* `intel.ch2.timings.rcdrd` — N/A (parse error: tRCD 0 ticks outside plausible range \[1, 2048\])
+* `intel.ch2.timings.rp` — N/A (parse error: tRP 0 ticks outside plausible range \[1, 2048\])
+* `intel.ch2.timings.ras` — N/A (parse error: tRAS 0 ticks outside plausible range \[1, 2048\])
+* `intel.ch2.timings.rc` — N/A (not applicable)
+* `intel.ch2.timings.rrld` — N/A (parse error: tRRD_L 0 ticks outside plausible range \[1, 2048\])
+* `intel.ch2.timings.faw` — N/A (parse error: tFAW 0 ticks outside plausible range \[1, 2048\])
+* `intel.ch2.timings.wtrs` — N/A (parse error: tWTR_S 0 ticks outside plausible range \[1, 2048\])
+* `intel.ch2.timings.wr` — N/A (parse error: tWR 0 ticks outside plausible range \[1, 2048\])
+* `intel.ch2.timings.rfc1` — N/A (parse error: tRFC1 0 ticks outside plausible range \[1, 2048\])
+* `intel.ch2.timings.rfc2` — N/A (not applicable)
+* `intel.ch2.timings.rfcsb` — N/A (parse error: tRFCsb 0 ticks outside plausible range \[1, 2048\])
+* `intel.ch2.timings.rdwr` — N/A (not applicable)
+* `intel.ch2.timings.wrrd` — N/A (not applicable)
+* `intel.ch2.timings.rdrd_sd` — N/A (parse error: tRDRD(dr) 0 ticks outside plausible range \[1, 2048\])
+* `intel.ch2.timings.rdrd_dd` — N/A (parse error: tRDRD(dd) 0 ticks outside plausible range \[1, 2048\])
+* `intel.ch2.timings.rdrd_scl` — N/A (parse error: tRDRD(sg) 0 ticks outside plausible range \[1, 2048\])
+* `intel.ch2.timings.rdrd_sc` — N/A (parse error: tRDRD(dg) 0 ticks outside plausible range \[1, 2048\])
+* `intel.ch2.timings.wrwr_sd` — N/A (not applicable)
+* `intel.ch2.timings.wrwr_dd` — N/A (not applicable)
+* `intel.ch2.timings.wrwr_scl` — N/A (parse error: tWRWR(sg) 0 ticks outside plausible range \[1, 2048\])
+* `intel.ch2.timings.wrwr_sc` — N/A (parse error: tWRWR(dg) 0 ticks outside plausible range \[1, 2048\])
+* `intel.ch2.cad_bus.proc_odt` — N/A (not applicable)
+* `intel.ch2.cad_bus.rtt_nom` — N/A (not applicable)
+* `intel.ch2.cad_bus.rtt_wr` — N/A (not applicable)
+* `intel.ch2.cad_bus.rtt_park` — N/A (not applicable)
+* `intel.ch2.cad_bus.clk_drv` — N/A (not applicable)
+* `intel.ch2.cad_bus.addr_cmd_drv` — N/A (not applicable)
+* `intel.ch2.cad_bus.cs_odt_drv` — N/A (not applicable)
+* `intel.ch2.cad_bus.cke_drv` — N/A (not applicable)
+* `intel.ch2.voltages.vddcr_soc` — N/A (not applicable)
+* `intel.ch2.voltages.vddio_mem` — N/A (not applicable)
+* `intel.ch2.voltages.vdd_misc` — N/A (not applicable)
+* `intel.ch2.voltages.vpp` — N/A (not applicable)
+* `intel.ch2.rtl` — N/A (not applicable)
+* `intel.ch3.clocks.fclk` — N/A (not applicable)
+* `intel.ch3.clocks.div_mode` — N/A (not applicable)
+* `intel.ch3.clocks.gdm` — N/A (not applicable)
+* `intel.ch3.clocks.pdm` — N/A (not applicable)
+* `intel.ch3.clocks.command_rate` — N/A (not applicable)
+* `intel.ch3.timings.cl` — N/A (parse error: tCL: register read failed)
+* `intel.ch3.timings.rcwdwr` — N/A (parse error: tRCD: register read failed)
+* `intel.ch3.timings.rcdrd` — N/A (parse error: tRCD: register read failed)
+* `intel.ch3.timings.rp` — N/A (parse error: tRP: register read failed)
+* `intel.ch3.timings.ras` — N/A (parse error: tRAS: register read failed)
+* `intel.ch3.timings.rc` — N/A (not applicable)
+* `intel.ch3.timings.rrds` — N/A (parse error: tRRD_S: register read failed)
+* `intel.ch3.timings.rrld` — N/A (parse error: tRRD_L: register read failed)
+* `intel.ch3.timings.faw` — N/A (parse error: tFAW: register read failed)
+* `intel.ch3.timings.wtrs` — N/A (parse error: tWTR_S: register read failed)
+* `intel.ch3.timings.wtrl` — N/A (parse error: tWTR_L: register read failed)
+* `intel.ch3.timings.wr` — N/A (parse error: tWR: register read failed)
+* `intel.ch3.timings.rfc1` — N/A (parse error: tRFC1: register read failed)
+* `intel.ch3.timings.rfc2` — N/A (not applicable)
+* `intel.ch3.timings.rfcsb` — N/A (parse error: tRFCsb: register read failed)
+* `intel.ch3.timings.cwl` — N/A (parse error: tCWL: register read failed)
+* `intel.ch3.timings.rtp` — N/A (parse error: tRTP: register read failed)
+* `intel.ch3.timings.rdwr` — N/A (not applicable)
+* `intel.ch3.timings.wrrd` — N/A (not applicable)
+* `intel.ch3.timings.rdrd_sd` — N/A (parse error: tRDRD(dr): register read failed)
+* `intel.ch3.timings.rdrd_dd` — N/A (parse error: tRDRD(dd): register read failed)
+* `intel.ch3.timings.rdrd_scl` — N/A (parse error: tRDRD(sg): register read failed)
+* `intel.ch3.timings.rdrd_sc` — N/A (parse error: tRDRD(dg): register read failed)
+* `intel.ch3.timings.wrwr_sd` — N/A (not applicable)
+* `intel.ch3.timings.wrwr_dd` — N/A (not applicable)
+* `intel.ch3.timings.wrwr_scl` — N/A (parse error: tWRWR(sg): register read failed)
+* `intel.ch3.timings.wrwr_sc` — N/A (parse error: tWRWR(dg): register read failed)
+* `intel.ch3.cad_bus.proc_odt` — N/A (not applicable)
+* `intel.ch3.cad_bus.rtt_nom` — N/A (not applicable)
+* `intel.ch3.cad_bus.rtt_wr` — N/A (not applicable)
+* `intel.ch3.cad_bus.rtt_park` — N/A (not applicable)
+* `intel.ch3.cad_bus.clk_drv` — N/A (not applicable)
+* `intel.ch3.cad_bus.addr_cmd_drv` — N/A (not applicable)
+* `intel.ch3.cad_bus.cs_odt_drv` — N/A (not applicable)
+* `intel.ch3.cad_bus.cke_drv` — N/A (not applicable)
+* `intel.ch3.voltages.vddcr_soc` — N/A (not applicable)
+* `intel.ch3.voltages.vddio_mem` — N/A (not applicable)
+* `intel.ch3.voltages.vdd_misc` — N/A (not applicable)
+* `intel.ch3.voltages.vpp` — N/A (not applicable)
+* `intel.ch3.rtl` — N/A (not applicable)
+* `spd[0x50].die_type` — N/A (not applicable)
+* `platform.agesa` — N/A (not applicable)
+* `platform.smu_version` — N/A (not applicable)
+* `raw.mad_inter_channel` — N/A (register absent / read failed)
+* `raw.mad_intra_ch0` — N/A (register absent / read failed)
+* `raw.mad_intra_ch1` — N/A (register absent / read failed)
+* `raw.mad_dimm_ch0` — N/A (register absent / read failed)
+* `raw.mad_dimm_ch1` — N/A (register absent / read failed)
+* `raw.mad_dimm_ch2` — N/A (register absent / read failed)
+* `raw.mad_dimm_ch3` — N/A (register absent / read failed)
+
+---
+
+*This report was auto-generated by RamSleuth v2.4.14. It contains no personal information (no username, hostname, IP, MAC, or serial numbers).*
+
diff --git a/bench/tasks/sleuth_cases/cpufreq.py b/bench/tasks/sleuth_cases/cpufreq.py
new file mode 100644
index 0000000..31db611
--- /dev/null
+++ b/bench/tasks/sleuth_cases/cpufreq.py
@@ -0,0 +1,88 @@
+"""The owner trimmed the kernel config by hand and dropped CONFIG_X86_INTEL_PSTATE with the iGPU
+options. The kernel falls back to acpi-cpufreq, where the powersave governor from
+/etc/conf.d/cpupower (chosen for intel_pstate's HWP powersave) pins every core at 800 MHz."""
+from bench.core.tools import Symlink
+from bench.tasks import sleuth
+from bench.tasks.sleuth_cases import _home
+
+KERNEL = "7.3.0-tkg-bore-llvm"
+CMDLINE = (f"BOOT_IMAGE=/vmlinuz-{KERNEL} root=UUID=6d3e0b6f-0b0c-4c51-9a3d-6c1a4b7e2f10 ro quiet "
+ "nowatchdog split_lock_detect=off")
+PS = """PID USER TIME COMMAND
+ 1 root 0:01 init [3]
+ 2088 ntp 0:00 /usr/sbin/chronyd
+ 2140 root 0:03 /usr/sbin/NetworkManager --pid-file /run/NetworkManager.pid
+ 2201 root 0:00 /usr/sbin/crond
+ 2733 user 3:02 /usr/bin/kwin_wayland --xwayland
+ 8120 root 0:06 /usr/bin/python3.13 /usr/lib/python-exec/python3.13/emerge -uDN @world
+ 9311 portage 0:00 [llvm-core/llvm-21.1.8] sandbox /usr/lib/portage/python3.13/ebuild.sh compile
+ 9402 portage 0:41 ninja -v -j16 -l16
+31810 portage 1:12 /usr/lib/llvm/21/bin/clang++ -O2 -march=alderlake -c lib/Target/X86/X86ISelLowering.cpp
+31822 portage 0:58 /usr/lib/llvm/21/bin/clang++ -O2 -march=alderlake -c lib/Transforms/Vectorize/LoopVectorize.cpp
+31840 portage 0:47 /usr/lib/llvm/21/bin/clang++ -O2 -march=alderlake -c lib/CodeGen/SelectionDAG/DAGCombiner.cpp
+31851 portage 0:31 /usr/lib/llvm/21/bin/clang++ -O2 -march=alderlake -c lib/Analysis/ScalarEvolution.cpp
+"""
+CPUPOWER = """analyzing CPU 0:
+ driver: acpi-cpufreq
+ CPUs which run at the same hardware frequency: 0
+ CPUs which need to have their frequency coordinated by software: 0
+ maximum transition latency: 10.0 us
+ hardware limits: 800 MHz - 3.70 GHz
+ available frequency steps: 3.70 GHz, 3.70 GHz, 3.50 GHz, 3.30 GHz, 3.10 GHz, 2.90 GHz, 2.70 GHz, 2.50 GHz, 2.30 GHz, 2.10 GHz, 1.90 GHz, 1.70 GHz, 1.50 GHz, 1.30 GHz, 1.10 GHz, 900 MHz, 800 MHz
+ available cpufreq governors: conservative ondemand userspace powersave performance schedutil
+ current policy: frequency should be within 800 MHz and 3.70 GHz.
+ The governor "powersave" may decide which speed to use
+ within this range.
+ current CPU frequency: 800 MHz (asserted by call to hardware)
+ boost state support:
+ Supported: yes
+ Active: yes
+"""
+
+
+def context():
+ files, commands = _home.host(kernel=KERNEL, cmdline=CMDLINE, driver="acpi-cpufreq",
+ load="busy", ps=PS)
+ new, old = _home.kernel_config(pstate=False, trimmed=True), _home.kernel_config()
+ src = f"usr/src/linux-{KERNEL}/"
+ files.update({
+ "proc/config.gz": _home.gz(new),
+ f"boot/config-{KERNEL}": new, f"boot/config-{KERNEL}.old": old,
+ f"boot/vmlinuz-{KERNEL}": b"\x4d\x5a" + bytes(4094),
+ f"boot/vmlinuz-{KERNEL}.old": b"\x4d\x5a" + bytes(4094),
+ src + ".config": new, src + ".config.old": old,
+ src + "Makefile": "VERSION = 7\nPATCHLEVEL = 3\nSUBLEVEL = 0\nEXTRAVERSION =\nNAME = Baby Opossum Posse\n",
+ "usr/src/linux": Symlink(f"linux-{KERNEL}"),
+ })
+ commands.update({"cpupower": "Usage:\tcpupower [-d|--debug] [-c|--cpu cpulist ] <command> [<args>]\n",
+ "cpupower frequency-info": CPUPOWER})
+ return sleuth.snapshot(files, commands)
+
+
+PSTATE = r"intel[_ -]?p[_ -]?state"
+
+CASES = [sleuth.Case(
+ case_id="cpufreq-driver", category="sleuth/kernel", context=context,
+ complaint=("I rebuilt my kernel last night after trimming the config by hand: I dropped the iGPU "
+ "drivers (this is a -KF, no iGPU) and a pile of drivers for hardware I don't have. "
+ "Since then the machine is sluggish. The emerge running right now is taking about "
+ "three times as long as usual and the desktop stutters. Temps look low. What "
+ "happened?"),
+ culprit=[PSTATE], reject=[r"thermal|throttl|i915|microcode|mitigation"],
+ fix=[r"X86_INTEL_PSTATE\s*=\s*y",
+ r"(re-?enable|enable|restore|rebuild|build|turn\s+(back\s+)?on|add\s+(it\s+)?back|re-?add|"
+ r"select|set)\b[^.\n]{0,80}" + PSTATE,
+ PSTATE + r"\b[^.\n]{0,60}\b(back|=\s*y|built[- ]in|enabled)"],
+ key=["acpi-cpufreq", "CONFIG_X86_INTEL_PSTATE is not set"],
+ expert=["cat /sys/devices/system/cpu/cpufreq/policy0/scaling_driver",
+ "zcat /proc/config.gz | grep INTEL_PSTATE"],
+ reference={"culprit": "CONFIG_X86_INTEL_PSTATE was dropped from the trimmed kernel config",
+ "root_cause": "Without intel_pstate the kernel falls back to acpi-cpufreq, where the "
+ "powersave governor set by /etc/conf.d/cpupower pins every core at the "
+ "800 MHz minimum.",
+ "fix": "Set CONFIG_X86_INTEL_PSTATE=y again, rebuild and reboot; until then "
+ "cpupower frequency-set -g schedutil."},
+ wrong=[{"culprit": "powersave governor pinning the CPUs at 800 MHz"},
+ {"culprit": "thermal throttling of the package"},
+ {"culprit": "CONFIG_SCHED_MC_PRIO missing, so tasks land on the E-cores"}],
+)]
diff --git a/bench/tasks/sleuth_cases/ingest_disk.py b/bench/tasks/sleuth_cases/ingest_disk.py
new file mode 100644
index 0000000..4e354f8
--- /dev/null
+++ b/bench/tasks/sleuth_cases/ingest_disk.py
@@ -0,0 +1,117 @@
+"""Live: an Alpine/OpenRC box whose ingest service fails with ENOSPC on /srv (a 64 MiB tmpfs) while
+du finds almost nothing. The nightly srv-rotate job renamed and deleted metricsd's log without making
+metricsd reopen it, so metricsd keeps writing to the deleted inode until /srv is full. Setup does
+that rotation and replays ~70 days of samples into the held file; restarting metricsd (or
+truncating its fd) frees the space."""
+from bench.tasks import sleuth
+
+METRICSD = """#!/bin/sh
+# metricsd: sample load and memory every 5 s into the spool log
+LOG=/srv/metricsd/current.log
+mkdir -p "${LOG%/*}"
+exec 3>>"$LOG"
+echo "metricsd: started, logging to $LOG"
+while :; do
+\tset -- $(cat /proc/loadavg)
+\tmem=$(awk '/MemAvailable/ {print $2}' /proc/meminfo)
+\techo "$(date +%s) load1=$1 load5=$2 memavail_kb=$mem" >&3
+\tsleep 5 3>&-
+done
+"""
+
+INGEST = """#!/bin/sh
+# ingest: pull collector batches into the spool queue for the uploader
+Q=/srv/ingest/queue
+mkdir -p "$Q"
+n=$(date +%s)
+echo "ingest: started, queue $Q"
+while :; do
+\tn=$((n + 1))
+\tif err=$(head -c 1048576 /dev/urandom | cat 2>&1 > "$Q/batch-$n.part") && mv "$Q/batch-$n.part" "$Q/batch-$n.dat"; then
+\t\techo "$(date '+%F %T') batch $n queued (1048576 bytes)"
+\telse
+\t\techo "$(date '+%F %T') batch $n: ${err:-write failed}"
+\t\trm -f "$Q/batch-$n.part"
+\tfi
+\tls -t "$Q"/*.dat 2>/dev/null | tail -n +6 | xargs -r rm -f
+\tsleep 10
+done
+"""
+
+ROTATE = """#!/bin/sh
+# Rotate the metricsd sample log; compressed copies go to /srv/archive.
+A=/srv/archive
+f=/srv/metricsd/current.log
+mkdir -p "$A"
+[ -s "$f" ] || exit 0
+mv "$f" "$f.1"
+gzip -c "$f.1" > "$A/metricsd-$(date +%Y%m%d).gz" && rm -f "$f.1"
+"""
+
+
+def _service(name, desc):
+ return (f'#!/sbin/openrc-run\ndescription="{desc}"\nsupervisor=supervise-daemon\n'
+ f'command="/usr/sbin/{name}"\noutput_log="/var/log/{name}.log"\n'
+ f'error_log="/var/log/{name}.log"\n\ndepend() {{\n\tneed localmount\n\tafter syslog\n}}\n')
+
+
+DOCKERFILE = f"""FROM {sleuth.ALPINE} AS build
+RUN apk add --no-cache openrc busybox-openrc lsof \\
+ && sed -i -e 's/^#\\?rc_sys=.*/rc_sys="docker"/' \\
+ -e 's/^#\\?rc_controller_cgroups=.*/rc_controller_cgroups="NO"/' /etc/rc.conf
+COPY rootfs/ /
+RUN chmod 755 /usr/sbin/metricsd /usr/sbin/ingest /etc/init.d/metricsd /etc/init.d/ingest \\
+ /etc/periodic/daily/srv-rotate \\
+ && rc-update add syslog boot && rc-update add crond default \\
+ && rc-update add metricsd default && rc-update add ingest default && mkdir -p /srv
+FROM scratch
+COPY --from=build / /
+CMD ["/sbin/init"]
+"""
+
+
+def context():
+ return {"Dockerfile": DOCKERFILE,
+ "rootfs/etc/inittab": "::sysinit:/sbin/openrc sysinit\n::sysinit:/sbin/openrc boot\n"
+ "::wait:/sbin/openrc default\n::shutdown:/sbin/openrc shutdown\n",
+ "rootfs/etc/init.d/metricsd": _service("metricsd", "host metrics sampler"),
+ "rootfs/etc/init.d/ingest": _service("ingest", "collector batch ingest"),
+ "rootfs/usr/sbin/metricsd": METRICSD, "rootfs/usr/sbin/ingest": INGEST,
+ "rootfs/etc/periodic/daily/srv-rotate": ROTATE}
+
+
+# Rotated 70 days ago; metricsd has written to the deleted file since (~1.2M samples fill /srv).
+SETUP = ("""until pgrep -x metricsd >/dev/null && [ -s /srv/metricsd/current.log ]; do sleep 1; done
+t=$(( $(date +%s) - 70 * 86400 ))
+a=/srv/archive/metricsd-$(date -d @$t +%Y%m%d).gz
+mkdir -p /srv/archive
+mv /srv/metricsd/current.log /srv/metricsd/current.log.1
+gzip -c /srv/metricsd/current.log.1 > $a && touch -d @$t $a && rm -f /srv/metricsd/current.log.1
+for fd in /proc/$(pgrep -x metricsd)/fd/*; do
+ case $(readlink $fd) in *current.log.1*) held=$fd ;; esac
+done
+awk -v t=$t 'BEGIN { for (i = 0; i < 1300000; i++) printf "%d load1=0.%02d load5=0.%02d memavail_kb=%d\\n", t + i * 5, i % 97, i % 89, 1800000 + i % 40000 }' >> $held 2>/dev/null
+true""",)
+
+CASES = [sleuth.Case(
+ case_id="ingest-disk", category="sleuth/live", context=context,
+ docker_args=("--hostname", "ingest01", "--tmpfs", "/srv:size=64m"),
+ setup=SETUP, ready="tail -n 1 /var/log/ingest.log | grep -q 'No space left'",
+ complaint=("The ingest service on this box stopped queueing batches this morning and logs write "
+ "errors. Restarting ingest didn't help. Can you find out what's wrong and fix it?"),
+ culprit=[r"metricsd",
+ r"delet|unlink|rotat|still open|held open|open (file )?(descriptor|fd|handle)|\bfd\b"],
+ check=("pgrep -x metricsd >/dev/null && pgrep -x ingest >/dev/null "
+ "&& [ \"$(df -P /srv | awk 'NR==2 {print $4}')\" -gt 32768 ] "
+ "&& head -c 8388608 /dev/zero > /srv/.check && rm -f /srv/.check"),
+ key=["(deleted)"],
+ expert=["tail -n 3 /var/log/ingest.log", "df -h /srv; du -sh /srv",
+ "lsof 2>/dev/null | grep deleted", "rc-service metricsd restart"],
+ reference={"culprit": "metricsd holding its rotated, deleted /srv/metricsd/current.log.1 open",
+ "root_cause": "srv-rotate renamed and deleted the log without making metricsd reopen it, "
+ "so metricsd kept writing to the deleted inode until /srv filled; du can't "
+ "see it, df counts it.",
+ "fix": "rc-service metricsd restart; make srv-rotate restart metricsd after rotating."},
+ wrong=[{"culprit": "the ingest queue filling /srv with batch files"},
+ {"culprit": "metricsd's log /srv/metricsd/current.log grew too large"}],
+)]
diff --git a/bench/tasks/sleuth_cases/ramsleuth.py b/bench/tasks/sleuth_cases/ramsleuth.py
new file mode 100644
index 0000000..b66d338
--- /dev/null
+++ b/bench/tasks/sleuth_cases/ramsleuth.py
@@ -0,0 +1,206 @@
+"""RamSleuth 2.4.14 (MIT, github.com/MadGoatHaz/RamSleuth @ 115e99b) on a gamer's desktop, from a
+hardware-forum report (2026-10-10). Ground truth is upstream's 2.4.15 fixes: 71dcffd (collect_from
+reads /sys/firmware/dmi/entries/17-N itself, a directory, and `Err(_) => continue` swallows EISDIR,
+so the SMBIOS dual-channel override never fires) and d639c71 (decode_mclk takes Alder Lake's
+MC_BIOS_REQ ratio x refclk, already the data rate, as MCLK; the reporters double it to 7200 MT/s).
+The 17-N raw bytes and dmidecode output are a real dump with personal identifiers (serials)
+replaced by synthetic ones; everything else is verbatim."""
+import io
+import os
+import subprocess
+import tarfile
+
+from bench.core import tools
+from bench.tasks import sleuth
+from bench.tasks.sleuth_cases import _home
+
+REPO = "https://github.com/MadGoatHaz/RamSleuth.git"
+COMMIT = "115e99bb3f73afd531297e9ba8ce358f8a992778" # tag v2.4.14
+SRC = "home/user/src/RamSleuth/"
+HERE = os.path.dirname(os.path.abspath(__file__))
+TYPE17 = bytes.fromhex(
+ "115c0c000b00feff400040000040090001021a80006009030405060100000000100eb0044605b004030800"
+ "0004ef0000000000000000000000000000000000000400000000000000000000000000000000000000000000"
+ "0000000000436f6e74726f6c6c6572302d4368616e6e656c412d44494d4d300042414e4b2030005465616d"
+ "2047726f757020496e630053455231303030310039383736353433323130005445414d47524f55502d5544"
+ "342d3336303020200000")
+
+
+def _read(name):
+ with open(os.path.join(HERE, name)) as f:
+ return f.read()
+
+
+def source_tree():
+ """{path: bytes | Symlink} of RamSleuth at COMMIT, from a bare clone in the sleuth cache."""
+ repo = os.path.join(sleuth.CACHE_DIR, "RamSleuth.git")
+ try:
+ if not os.path.isdir(repo):
+ subprocess.run(["git", "clone", "--quiet", "--bare", REPO, repo], check=True,
+ capture_output=True, timeout=600)
+ if subprocess.run(["git", "-C", repo, "cat-file", "-e", COMMIT + "^{commit}"],
+ capture_output=True).returncode != 0:
+ subprocess.run(["git", "-C", repo, "fetch", "--quiet", "origin", COMMIT], check=True,
+ capture_output=True, timeout=600)
+ tar = subprocess.run(["git", "-C", repo, "archive", "--format=tar", COMMIT], check=True,
+ capture_output=True, timeout=120).stdout
+ except (OSError, subprocess.SubprocessError) as e:
+ raise tools.InfraError(f"fetching RamSleuth {COMMIT[:7]} failed: {e!r}")
+ out = {}
+ with tarfile.open(fileobj=io.BytesIO(tar)) as t:
+ for m in t.getmembers():
+ if m.issym():
+ out[SRC + m.name] = tools.Symlink(m.linkname)
+ elif m.isfile():
+ out[SRC + m.name] = t.extractfile(m).read()
+ return out
+
+
+def _smbios(typ, handle, body, strings=()):
+ s = b"".join(x.encode() + b"\0" for x in strings) + b"\0" if strings else b"\0\0"
+ return bytes([typ, 4 + len(body), handle & 0xFF, handle >> 8]) + body + s
+
+
+def dmi_entries():
+ oem = "To Be Filled By O.E.M."
+ t17b = TYPE17.replace(b"Controller0", b"Controller1").replace(b"SER10001", b"SER10002")
+ entries = [
+ ("0-0", 0, _smbios(0, 0x0000, bytes([1, 2, 0x00, 0xF0, 3, 0xFF, 0x80, 0x98, 0x8B, 0x3F, 1, 0,
+ 0, 0, 0x33, 0x0D, 5, 27, 0xFF, 0xFF, 0x20, 0x00]),
+ ("American Megatrends International, LLC.", "21.01", "09/26/2025"))),
+ ("1-0", 1, _smbios(1, 0x0001, bytes([1, 2, 3, 4]) + bytes(range(0x10, 0x20)) + bytes([6, 5, 6]),
+ ("ASRock", "Z690M-ITX/ax", oem, oem, oem, oem))),
+ ("2-0", 2, _smbios(2, 0x0002, bytes([1, 2, 3, 4, 5, 0x09, 6, 0x03, 0x00, 0x0A, 0]),
+ ("ASRock", "Z690M-ITX/ax", oem, oem, oem, oem))),
+ ("16-0", 16, _smbios(16, 0x000B, bytes([3, 3, 3]) + (0x08000000).to_bytes(4, "little")
+ + bytes([0xFE, 0xFF, 2, 0]) + bytes(8))),
+ ("17-0", 17, TYPE17), ("17-1", 17, t17b),
+ ("127-0", 127, _smbios(127, 0xFFFE, b"")),
+ ]
+ files, table = {}, b""
+ for pos, (name, typ, raw) in enumerate(entries):
+ d = f"sys/firmware/dmi/entries/{name}/"
+ files.update({d + "raw": raw, d + "type": f"{typ}\n", d + "instance": name.split("-")[1] + "\n",
+ d + "handle": f"{raw[2] | raw[3] << 8}\n", d + "length": f"{raw[1]}\n",
+ d + "position": f"{pos}\n"})
+ table += raw
+ ep = bytearray(b"_SM3_\0\x18\x03\x05\x00\x01\x00" + len(table).to_bytes(4, "little")
+ + (0x69D0F000).to_bytes(8, "little"))
+ ep[5] = -sum(ep) & 0xFF
+ files.update({"sys/firmware/dmi/tables/DMI": table, "sys/firmware/dmi/tables/smbios_entry_point": bytes(ep)})
+ for f, v in (("bios_vendor", "American Megatrends International, LLC."), ("bios_version", "21.01"),
+ ("bios_date", "09/26/2025"), ("board_vendor", "ASRock"), ("board_name", "Z690M-ITX/ax"),
+ ("sys_vendor", "ASRock"), ("product_name", oem)):
+ files["sys/class/dmi/id/" + f] = v + "\n"
+ return files
+
+
+DMIDECODE_HEAD = """# dmidecode 3.7
+Getting SMBIOS data from sysfs.
+SMBIOS 3.5.0 present.
+Table at 0x69D0F000.
+
+Handle 0x0000, DMI type 0, 26 bytes
+BIOS Information
+\tVendor: American Megatrends International, LLC.
+\tVersion: 21.01
+\tRelease Date: 09/26/2025
+\tROM Size: 32 MB
+\tBIOS Revision: 5.27
+
+Handle 0x0001, DMI type 1, 27 bytes
+System Information
+\tManufacturer: ASRock
+\tProduct Name: Z690M-ITX/ax
+
+Handle 0x0002, DMI type 2, 15 bytes
+Base Board Information
+\tManufacturer: ASRock
+\tProduct Name: Z690M-ITX/ax
+
+Handle 0x000B, DMI type 16, 23 bytes
+Physical Memory Array
+\tLocation: System Board Or Motherboard
+\tUse: System Memory
+\tError Correction Type: None
+\tMaximum Capacity: 128 GB
+\tNumber Of Devices: 2
+
+"""
+
+
+def context():
+ files, commands = _home.host(kernel="7.3.0-rc5-tkg-bore-llvm",
+ cmdline="BOOT_IMAGE=/vmlinuz-7.3.0-rc5-tkg-bore-llvm "
+ "root=UUID=6d3e0b6f-0b0c-4c51-9a3d-6c1a4b7e2f10 ro quiet")
+ files.update(source_tree())
+ files.update(dmi_entries())
+ files["home/user/ramsleuth-probe.md"] = _read("_ramsleuth-probe.md")
+ t17 = _read("_ramsleuth-dmidecode.txt")
+ t17_blocks = t17[t17.index("Handle 0x000C"):]
+ commands.update({"dmidecode": DMIDECODE_HEAD + t17_blocks, "dmidecode -t 17": t17,
+ "dmidecode --type 17": t17,
+ "dmidecode -t memory": DMIDECODE_HEAD[:DMIDECODE_HEAD.index("Handle 0x0000")]
+ + DMIDECODE_HEAD[DMIDECODE_HEAD.index("Handle 0x000B"):] + t17_blocks})
+ commands["dmidecode --type memory"] = commands["dmidecode -t memory"]
+ return sleuth.snapshot(files, commands)
+
+
+DOUBLED = r"half|/\s*2\b|÷\s*2|divid|doubl|twice|[x×*]\s*2(\.0)?\b|data[ -]?rate|1800"
+
+CASES = [
+ sleuth.Case(
+ case_id="ramsleuth-channel", category="sleuth/code", context=context,
+ complaint=("I'm testing RamSleuth 2.4.14, built from the checkout in /home/user/src/RamSleuth. It "
+ "reports my memory as Single-Channel, but this is a 2x16 GB DDR4-3600 kit in both slots "
+ "of a two-slot ITX board and the BIOS shows dual channel. The 2.4.14 release notes say a "
+ "populated dual-channel kit reads as dual-channel again. The probe report it wrote is "
+ "/home/user/ramsleuth-probe.md. Why is it still wrong?"),
+ # Tightened 2026-10-12 after Opus passed `\braw file` / `\braw\b` with offhand mentions.
+ culprit=[r"EISDIR|os error 21|\bis a director|\bare director|\bas (a )?director|\bon (a|the|each) director|"
+ r"director(y|ies)[^.]{0,40}\b(instead of|not|rather than)\b[^.]{0,30}(file|raw)|"
+ r"\b(instead of|rather than|not)\b[^.]{0,40}17-\S*/raw\b|join\(\s*[\"']raw[\"']",
+ r"smbios|\bdmi\b|type[ -]?17|\b17-|collect_from|intel_smbios"],
+ fix=[r"join\(\s*[\"']raw[\"']|\b(read|open|use|point)\w*\b[^.]{0,60}17-\S*/raw\b|"
+ r"17-\S*/raw\b[^.]{0,40}\b(instead of|rather than)\b|\bappend\w*\b[^.]{0,20}/?raw\b"],
+ key=["Err(_) => continue, // unreadable -> skip", "let bytes = match std::fs::read(&path)"],
+ expert=["grep -rn 'dmi/entries' /home/user/src/RamSleuth/crates --include=*.rs",
+ "sed -n 146,180p /home/user/src/RamSleuth/crates/ramsleuth-telemetry/src/intel_smbios.rs",
+ "ls -l /sys/firmware/dmi/entries/17-0"],
+ reference={"culprit": "intel_smbios::collect_from reads each /sys/firmware/dmi/entries/17-N with "
+ "fs::read, but 17-N is a directory (the bytes are in 17-N/raw)",
+ "root_cause": "fs::read fails on the directory, Err(_) => continue skips every entry, "
+ "populated_count stays 0, so the SMBIOS dual-channel override never fires "
+ "and the MCHBAR Single-Channel decode is reported.",
+ "fix": "Read path.join(\"raw\") for each 17-N entry, then check the Type 17 parser "
+ "offsets against the SMBIOS 3.5 layout."},
+ wrong=[{"culprit": "MCHBAR MAD_INTER_CHANNEL registers read as absent, so the MMIO decode says "
+ "Single-Channel"},
+ {"culprit": "the SMBIOS Type 17 parser reads capacity at offset 0x28 instead of 0x0C"},
+ {"culprit": "channel_of cannot tell Controller0-ChannelA from Controller1-ChannelA"},
+ {"culprit": "intel_smbios.rs parse_type17() reads the Device Locator from 0x06/0x0C, not 0x10",
+ "root_cause": "string_at assumes the string table starts with an empty string, which the "
+ "kernel's raw file does not have, so both DIMMs get an empty locator"}]),
+ sleuth.Case(
+ case_id="ramsleuth-mts", category="sleuth/code", context=context,
+ complaint=("RamSleuth 2.4.14 (source in /home/user/src/RamSleuth, probe report in "
+ "/home/user/ramsleuth-probe.md) says my DDR4-3600 kit runs at 7200 MT/s. dmidecode and "
+ "the BIOS say 3600. Where does the 7200 come from?"),
+ culprit=[r"mclk|MC_BIOS_REQ|clk[_ ]?ratio|\bratio\b", DOUBLED],
+ reject=[r"\bSPD\b|XMP|dmidecode|\bgear\b"],
+ fix=[r"/\s*2\b|÷\s*2|\bhal(f|ve|ving)\b|divid|1800|"
+ r"(drop|remove|don'?t|do not|stop)\b[^.\n]{0,40}(doubl|[x×*]\s*2)"],
+ key=["clock_section(f64::from(ratio) * refclk)", '{:.0} MT/s", value * 2.0)',
+ '{:.0} MT/s", mclk * 2.0)'],
+ expert=["grep -rn 'MT/s\", ' /home/user/src/RamSleuth/crates --include=*.rs",
+ "grep -n 'fn decode_mclk' -A 22 "
+ "/home/user/src/RamSleuth/crates/ramsleuth-telemetry/src/intel_readout.rs"],
+ reference={"culprit": "decode_mclk in intel_readout.rs takes MC_BIOS_REQ ratio x refclk "
+ "(36 x 100 = 3600) as the DRAM clock",
+ "root_cause": "On Alder Lake that product is already the DDR data rate (the real MCLK is "
+ "1800 MHz), and the reporters then multiply MCLK by 2, giving 7200 MT/s.",
+ "fix": "Divide by 2 for 11th-gen and later in decode_mclk (MCLK = ratio x refclk / 2) "
+ "so the reported MT/s is 3600."},
+ wrong=[{"culprit": "SPD XMP profile decoded at the wrong speed"},
+ {"culprit": "UCLK reported equal to MCLK in gear 1"}]),
+]
diff --git a/bench/tasks/toolcall_probes.py b/bench/tasks/toolcall_probes.py
new file mode 100644
index 0000000..e4457a8
--- /dev/null
+++ b/bench/tasks/toolcall_probes.py
@@ -0,0 +1,194 @@
+"""Tool-calling and structured-output probes for the conformance preflight, moved verbatim from
+coding-suite (2026-10-12). Each probe: id, tools (None = none declared), messages, validator(resp)
+-> (ok, detail[, extra]). They test that a call or JSON object comes back well-formed through the
+lane's template, parser and provider; a wrong value is the model's, a call that never arrives as a
+call is usually not (conformance tells the two apart). tc-xml is the probe a provider's Qwen tool
+parser swallowed in 2026-10 (DeepInfra, plain-text <tool_call> with no tools declared).
+"""
+import json
+import re
+
+from bench.core import client
+
+WEATHER_TOOL = [{"type": "function", "function": {
+ "name": "get_weather",
+ "description": "Get the current weather for a location.",
+ "parameters": {"type": "object", "properties": {
+ "location": {"type": "string", "description": "City name"},
+ "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}},
+ "required": ["location", "unit"]}}}]
+CALC_TOOL = [{"type": "function", "function": {
+ "name": "calculator",
+ "description": "Evaluate an arithmetic expression.",
+ "parameters": {"type": "object", "properties": {"expression": {"type": "string"}},
+ "required": ["expression"]}}}]
+WEB_TOOL = {"type": "function", "function": {
+ "name": "web_search", "description": "Search the web.",
+ "parameters": {"type": "object", "properties": {"query": {"type": "string"}, "limit": {"type": "integer"}},
+ "required": ["query"]}}}
+THREE_TOOLS = [WEATHER_TOOL[0], CALC_TOOL[0], WEB_TOOL]
+TIMER_TOOL = [{"type": "function", "function": {
+ "name": "set_timer", "description": "Set a countdown timer.",
+ "parameters": {"type": "object", "properties": {"seconds": {"type": "integer", "description": "duration in seconds"}},
+ "required": ["seconds"]}}}]
+
+
+
+def _first_call(resp, name):
+ """(arguments, None) if the first tool call is `name` with JSON arguments, else (None, why)."""
+ tcs = client.tool_calls(resp)
+ if not tcs:
+ return None, "no tool call; content=%r" % client.content(resp)[:140]
+ fn = tcs[0]["function"]
+ if fn["name"] != name:
+ return None, "picked %s" % fn["name"]
+ try:
+ return json.loads(fn["arguments"]), None
+ except Exception:
+ return None, "bad args %r" % str(fn["arguments"])[:120]
+
+
+def _json_object(resp):
+ """(obj, None) for the outermost {...} of the answer, else (None, why)."""
+ c = client.content(resp).strip()
+ m = re.search(r"\{.*\}", c, re.DOTALL)
+ if not m:
+ return None, "no JSON object in output: %r" % c[:160]
+ try:
+ return json.loads(m.group(0)), None
+ except Exception as e:
+ return None, "JSON parse error: %s | %r" % (e, m.group(0)[:160])
+
+
+def _v_native(resp):
+ args, why = _first_call(resp, "get_weather")
+ if why:
+ return False, why
+ loc_ok = "paris" in str(args.get("location", "")).lower()
+ unit_ok = str(args.get("unit", "")).lower() == "celsius"
+ return (loc_ok and unit_ok), "args=%s loc_ok=%s unit_ok=%s" % (args, loc_ok, unit_ok)
+
+
+# One <tool_call>{...}</tool_call> line.
+_TC_OPEN = "<tool_call>"
+_TC_CLOSE = "</tool_call>"
+
+
+def _v_xml(resp):
+ """Returns (ok, detail, extra). A missing closing tag is accepted (extra xml_unclosed)."""
+ c = client.content(resp)
+ i = c.find(_TC_OPEN)
+ if i < 0:
+ return False, "no %s{...}%s found: %r" % (_TC_OPEN, _TC_CLOSE, c[:160]), {}
+ rest = c[i + len(_TC_OPEN):].lstrip()
+ if not rest.startswith("{"):
+ return False, "inner JSON did not parse: %r" % rest[:160], {}
+ try:
+ obj, end = json.JSONDecoder().raw_decode(rest)
+ except ValueError:
+ return False, "inner JSON did not parse: %r" % rest[:160], {}
+ tail = rest[end:].strip()
+ unclosed = not tail.startswith(_TC_CLOSE)
+ if unclosed and tail:
+ return False, "no %s after the JSON: %r" % (_TC_CLOSE, tail[:80]), {}
+ if not isinstance(obj, dict):
+ return False, "tool call is not an object: %r" % (obj,), {"xml_unclosed": unclosed}
+ args = obj.get("arguments", obj.get("parameters", {}))
+ if not isinstance(args, dict):
+ args = {}
+ name_ok = obj.get("name") == "web_search"
+ q_ok = "gemma" in str(args.get("query", "")).lower()
+ limit_ok = str(args.get("limit")) == "5"
+ return ((name_ok and q_ok and limit_ok),
+ "obj=%s name_ok=%s q_ok=%s limit_ok=%s" % (obj, name_ok, q_ok, limit_ok),
+ {"xml_unclosed": unclosed})
+
+
+def _v_json(resp):
+ obj, why = _json_object(resp)
+ if why:
+ return False, why
+ name_ok = isinstance(obj.get("name"), str) and "maria" in obj["name"].lower()
+ age_ok = obj.get("age") == 34
+ sk = obj.get("skills")
+ skills_ok = isinstance(sk, list) and {"go", "rust"} <= {str(x).lower() for x in sk}
+ return (name_ok and age_ok and skills_ok), "obj=%s name=%s age=%s skills=%s" % (obj, name_ok, age_ok, skills_ok)
+
+
+def _v_notool(resp):
+ tcs = client.tool_calls(resp)
+ if tcs:
+ return False, "incorrectly called a tool: %s" % tcs[0]["function"]["name"]
+ c = client.content(resp).lower()
+ return ("paris" in c), "answered in text, mentions Paris=%s" % ("paris" in c)
+
+
+def _v_multi(resp):
+ tcs = client.tool_calls(resp)
+ locs = []
+ for tc in tcs:
+ try:
+ a = json.loads(tc["function"]["arguments"])
+ except Exception:
+ a = {}
+ locs.append(str(a.get("location", "")).lower())
+ blob = " ".join(locs)
+ ok = len(tcs) >= 2 and "paris" in blob and "tokyo" in blob
+ return ok, "n_calls=%d locs=%s" % (len(tcs), locs)
+
+
+def _v_select(resp):
+ a, why = _first_call(resp, "calculator")
+ if why:
+ return False, why
+ expr = str(a.get("expression", ""))
+ return ("47" in expr and "89" in expr), "expr=%r" % expr
+
+
+def _v_nested(resp):
+ o, why = _json_object(resp)
+ if why:
+ return False, why
+ svc = o.get("service", {})
+ ok = (isinstance(svc, dict) and str(svc.get("name", "")).lower() == "api"
+ and svc.get("port") == 8080 and o.get("replicas") == 3
+ and "prod" in str(o.get("env", "")).lower())
+ return ok, "obj=%s" % o
+
+
+def _v_derived(resp):
+ a, why = _first_call(resp, "set_timer")
+ if why:
+ return False, why
+ return a.get("seconds") == 150, "args=%s" % a
+
+_XML_SYS = ("You can call tools. To call a tool you MUST output exactly one line of the form "
+ "<tool_call>{\"name\": \"<tool>\", \"arguments\": {...}}</tool_call> "
+ "and nothing else \u2014 no prose, no markdown. "
+ "Available tool: web_search(query: string, limit: integer).")
+
+
+TOOLCALL = [
+ {"id": "tc-native", "cat": "toolcall", "tools": WEATHER_TOOL, "validator": _v_native,
+ "messages": [{"role": "user", "content": "What is the current weather in Paris? Use celsius."}]},
+ {"id": "tc-xml", "cat": "toolcall", "tools": None, "validator": _v_xml,
+ "messages": [
+ {"role": "system", "content": _XML_SYS},
+ {"role": "user", "content": "Search the web for 'gemma benchmarks' and return at most 5 results."}]},
+ {"id": "tc-json", "cat": "toolcall", "tools": None, "validator": _v_json,
+ "messages": [
+ {"role": "system", "content": "Output ONLY a single JSON object and nothing else. No markdown fences, no commentary."},
+ {"role": "user", "content": "Extract this person into JSON with keys name (string), age (integer), skills (array of strings): 'Maria is 34 years old and knows Go and Rust.'"}]},
+ {"id": "tc-notool", "cat": "toolcall", "tools": CALC_TOOL, "validator": _v_notool,
+ "messages": [{"role": "user", "content": "What is the capital of France? Answer in one word."}]},
+ {"id": "tc-multi", "cat": "toolcall", "tools": WEATHER_TOOL, "validator": _v_multi,
+ "messages": [{"role": "user", "content": "What's the weather in Paris and in Tokyo right now? Use celsius for both."}]},
+ {"id": "tc-select", "cat": "toolcall", "tools": THREE_TOOLS, "validator": _v_select,
+ "messages": [{"role": "user", "content": "Using the tools available to you, compute 47 * 89 and give me the exact product."}]},
+ {"id": "tc-nested-json", "cat": "toolcall", "tools": None, "validator": _v_nested,
+ "messages": [
+ {"role": "system", "content": "Output ONLY a single JSON object, no markdown, no commentary."},
+ {"role": "user", "content": "Produce a deployment config JSON with this shape: {\"service\": {\"name\": string, \"port\": integer}, \"replicas\": integer, \"env\": string}. The service is named 'api', listens on port 8080, runs 3 replicas, in the production environment."}]},
+ {"id": "tc-derived", "cat": "toolcall", "tools": TIMER_TOOL, "validator": _v_derived,
+ "messages": [{"role": "user", "content": "Set a timer for two and a half minutes."}]},
+]
diff --git a/lanes/cards.json b/lanes/cards.json
new file mode 100644
index 0000000..0bb9657
--- /dev/null
+++ b/lanes/cards.json
@@ -0,0 +1,39 @@
+{
+ "Qwen/Qwen3.8-27B": {
+ "revision": "1d4bf0f2ff6012fd82039f2fa52739d0dd7c60c0",
+ "checked": "2026-10-12",
+ "source": "README.md, Best Practices > 1. Sampling Parameters",
+ "thinking": {"temperature": 1.0, "top_p": 0.95, "top_k": 20, "min_p": 0.0,
+ "presence_penalty": 0.0, "repetition_penalty": 1.0},
+ "non_thinking": {"temperature": 0.7, "top_p": 0.8, "top_k": 20, "min_p": 0.0,
+ "presence_penalty": 1.5, "repetition_penalty": 1.0},
+ "note": "Also covers its straight quants: unsloth/Qwen3.8-27B-GGUF (rev 4ca7207) repeats this block, bartowski/Qwen3.8-27B-GGUF (rev 0c92138) gives no sampler advice."
+ },
+ "Qwen/Qwen3.8-Flash-Next": {
+ "revision": "de4b8e4d43b917e7706784d8bb445c9af86a3540",
+ "checked": "2026-10-12",
+ "source": "README.md, Best Practices > 1. Sampling Parameters",
+ "thinking": {"temperature": 1.0, "top_p": 0.95, "top_k": 20, "min_p": 0.0,
+ "presence_penalty": 0.0, "repetition_penalty": 1.0},
+ "non_thinking": {"temperature": 0.7, "top_p": 0.8, "top_k": 20, "min_p": 0.0,
+ "presence_penalty": 1.5, "repetition_penalty": 1.0},
+ "note": "Also covers ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF (rev ed59f92), which gives no sampler advice."
+ },
+ "prism-ml/Ternary-Bonsai-2-27B-gguf": {
+ "revision": "b072e1d3b35a0a630cece372c2127528e0994386",
+ "checked": "2026-10-12",
+ "source": "README.md, Best Practices > Generation Parameters",
+ "thinking": {"temperature": 1.0, "top_p": 0.95, "top_k": 20, "min_p": 0.05,
+ "presence_penalty": 0.0, "repetition_penalty": 1.0},
+ "non_thinking": {"temperature": 0.7, "top_p": 0.8, "top_k": 20, "min_p": 0.0,
+ "presence_penalty": 1.5, "repetition_penalty": 1.0},
+ "note": "QAT of Qwen/Qwen3.8-27B. Thinking min_p 0.05 is the card's own call (scored at least as well as 0.0 and followed instructions better; llama.cpp's default), though its published benchmarks used 0.0."
+ },
+ "deepseek-ai/DeepSeek-V4.1-Flash": {
+ "revision": "5254448103b6254fc646dacbca1cbbf20e9216c1",
+ "checked": "2026-10-12",
+ "source": "README.md, Minimal Inference > Recommended sampling parameters (every eval: temperature=1.0, top_p=0.95)",
+ "thinking": {"temperature": 1.0, "top_p": 0.95},
+ "note": "Card: top_p 0.95 or 1.0, max_tokens >= 256K, no top_k/min_p advice. Native reasoning effort is an integer 1-100 (evals at 100); OpenRouter's effort 'low' maps onto it. MIT license."
+ }
+}
diff --git a/lanes/example-lmstudio.json b/lanes/example-lmstudio.json
new file mode 100644
index 0000000..1060da9
--- /dev/null
+++ b/lanes/example-lmstudio.json
@@ -0,0 +1,20 @@
+{
+ "lane_id": "example-lmstudio",
+ "description": "Example lane: a model served locally by LM Studio, sampler matching its card's thinking block. Copy this file for your own endpoint/model.",
+ "card": "Qwen/Qwen3.8-27B",
+ "endpoint": "http://127.0.0.1:1234/v1/chat/completions",
+ "model": "qwen/qwen3.8-27b",
+ "auth": null,
+ "thinking": "on",
+ "request": {
+ "temperature": 1.0,
+ "top_p": 0.95,
+ "top_k": 20,
+ "min_p": 0.0,
+ "presence_penalty": 0.0,
+ "repetition_penalty": 1.0,
+ "max_tokens": 8000
+ },
+ "http_timeout": 1800,
+ "snapshot": "none"
+}
diff --git a/tests/_util.py b/tests/_util.py
new file mode 100644
index 0000000..bc261fd
--- /dev/null
+++ b/tests/_util.py
@@ -0,0 +1,32 @@
+"""Shared test setup. Import it before any bench module: results and work dirs go to a fresh
+temp dir, LANE is unset, retries back off ~instantly."""
+import io
+import os
+import sys
+import tempfile
+from contextlib import redirect_stdout
+
+TMP = tempfile.mkdtemp(prefix="llm-bench-test-")
+os.environ["BENCH_RESULTS_DIR"] = TMP
+os.environ["BENCH_WORK_DIR"] = os.path.join(TMP, "work")
+os.environ["BENCH_BACKOFF_SCALE"] = "0.001"
+os.environ["BENCH_PREFLIGHT"] = "0" # tests that need it turn it back on
+os.environ.pop("LANE", None)
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+
+def run_main(mod, argv):
+ """mod.main(argv) with stdout captured -> its exit code."""
+ try:
+ with redirect_stdout(io.StringIO()):
+ mod.main(argv)
+ except SystemExit as e:
+ return e.code
+ return 0
+
+
+def run_dir(instrument, lane_id):
+ """The run dir of the only run of `instrument` on `lane_id`."""
+ root = os.path.join(TMP, instrument, lane_id)
+ (name,) = os.listdir(root)
+ return os.path.join(root, name)
diff --git a/tests/fake_claude.py b/tests/fake_claude.py
new file mode 100755
index 0000000..1235202
--- /dev/null
+++ b/tests/fake_claude.py
@@ -0,0 +1,95 @@
+#!/usr/bin/env python3
+"""Stand-in for `claude -p` in the claude_cli tests: speaks stream-json in and out and calls the
+real MCP relay from --mcp-config, so relay + bridge + event parsing run end to end offline.
+
+Scenario: JSON in env FAKE_CLAUDE —
+ {"connected": true, "sleep": 0, "argv_file": path, # + path.system: the system prompt file's text
+ "queries": [[msg, ...], ...], # one list per user message received on stdin
+ "forever": msg} # instead of queries: repeat msg until killed
+ msg = {"tools": [[name, args], ...], "text": "...", "out": 10, "think": 3, "error": "..."}
+A msg with "error" ends its query with an is_error result carrying that text.
+"""
+import json
+import os
+import subprocess
+import sys
+import time
+
+SC = json.loads(os.environ["FAKE_CLAUDE"])
+N = [0]
+
+
+def emit(obj):
+ sys.stdout.write(json.dumps(obj) + "\n")
+ sys.stdout.flush()
+
+
+class Relay:
+ def __init__(self, cfg_path):
+ with open(cfg_path) as f:
+ srv = json.load(f)["mcpServers"]["bench"]
+ self.p = subprocess.Popen([srv["command"], *srv["args"]], env=dict(os.environ, **srv["env"]),
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
+ self.rpc("initialize", {"protocolVersion": "2025-06-18"})
+ self.p.stdin.write(json.dumps({"jsonrpc": "2.0", "method": "notifications/initialized"}) + "\n")
+ self.tools = [t["name"] for t in self.rpc("tools/list", {})["tools"]]
+
+ def rpc(self, method, params):
+ N[0] += 1
+ self.p.stdin.write(json.dumps({"jsonrpc": "2.0", "id": N[0], "method": method, "params": params}) + "\n")
+ self.p.stdin.flush()
+ return json.loads(self.p.stdout.readline())["result"]
+
+
+def message(relay, m):
+ mid = "msg_%d" % N[0]
+ N[0] += 1
+ emit({"type": "stream_event", "event": {"type": "message_start", "message": {"id": mid}}})
+ blocks = [{"type": "text", "text": m.get("text", "")}] if m.get("text") else []
+ blocks += [{"type": "tool_use", "id": "tu%d" % i, "name": "mcp__bench__" + n, "input": a}
+ for i, (n, a) in enumerate(m.get("tools", []))]
+ emit({"type": "assistant", "message": {"id": mid, "content": blocks}})
+ emit({"type": "stream_event", "event": {
+ "type": "message_delta", "delta": {"stop_reason": "tool_use" if m.get("tools") else "end_turn"},
+ "usage": {"input_tokens": 2, "cache_read_input_tokens": 100, "cache_creation_input_tokens": 8,
+ "output_tokens": m.get("out", 10), "output_tokens_details": {"thinking_tokens": m.get("think", 0)}}}})
+ emit({"type": "stream_event", "event": {"type": "message_stop"}})
+ if m.get("tools"):
+ results = [relay.rpc("tools/call", {"name": n, "arguments": a}) for n, a in m["tools"]]
+ emit({"type": "user", "message": {"role": "user", "content": [
+ {"type": "tool_result", "tool_use_id": "tu%d" % i, "content": r["content"]}
+ for i, r in enumerate(results)]}})
+
+
+def main():
+ argv = sys.argv[1:]
+ if SC.get("argv_file"):
+ with open(SC["argv_file"], "w") as f:
+ json.dump(argv, f)
+ if "--system-prompt-file" in argv:
+ with open(argv[argv.index("--system-prompt-file") + 1]) as src, \
+ open(SC["argv_file"] + ".system", "w") as dst:
+ dst.write(src.read())
+ time.sleep(SC.get("sleep", 0))
+ relay = Relay(argv[argv.index("--mcp-config") + 1])
+ emit({"type": "system", "subtype": "init", "model": argv[argv.index("--model") + 1],
+ "claude_code_version": "0.0-fake", "tools": ["mcp__bench__" + t for t in relay.tools],
+ "mcp_servers": [{"name": "bench", "status": "connected" if SC.get("connected", True) else "failed"}]})
+ queries = iter(SC.get("queries", []))
+ for _line in sys.stdin:
+ if "forever" in SC:
+ while True:
+ message(relay, SC["forever"])
+ q = next(queries, [{"text": "(no more scripted turns)"}])
+ err = None
+ for m in q:
+ if "error" in m:
+ err = m["error"]
+ break
+ message(relay, m)
+ emit({"type": "result", "subtype": "success", "is_error": err is not None,
+ "result": err or (q[-1].get("text") or "")})
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/test_agentic.py b/tests/test_agentic.py
new file mode 100644
index 0000000..91648b5
--- /dev/null
+++ b/tests/test_agentic.py
@@ -0,0 +1,557 @@
+"""Offline tests for the agentic instruments (bench.core.tools + agentic_* + multitask).
+
+Everything model-facing runs against bench.core.mockserver.MockServer — never a live
+endpoint. Run from llm-bench/: python3 -m unittest discover -s tests -v
+"""
+import contextlib
+import http.client
+import hashlib
+import io
+import json
+import os
+import shutil
+import sys
+import tempfile
+import time
+import unittest
+
+from _util import TMP as _TMP
+from bench.core import tools
+from bench.core.mockserver import MockServer, chat, tool_call # noqa: E402
+from bench.tasks import agentic_multitask as harness # noqa: E402
+from bench.tasks.multitask import rust_cli # noqa: E402
+
+WORK = os.path.join(_TMP, "work")
+
+
+def _read(path):
+ with open(path) as f:
+ return f.read()
+
+
+def _jload(path):
+ with open(path) as f:
+ return json.load(f)
+
+
+def quiet(*_a, **_k):
+ pass
+
+
+def fake_task(**kw):
+ """A tiny task: correct iff hello.txt == "hi" and big.txt was never written."""
+ def gates(ws, port=None):
+ p = os.path.join(ws.dir, "hello.txt")
+ hello = os.path.isfile(p) and _read(p) == "hi"
+ return {"hello": hello,
+ "no_big": not os.path.exists(os.path.join(ws.dir, "big.txt"))}, {"checked": True}
+ toolset = tools.build_toolset(
+ "fake", build_cmd="true", test_cmd="true", build_desc="noop build",
+ test_desc="noop test", shell_uses="anything", build_timeout=10, test_timeout=10,
+ shell_timeout=10)
+ args = dict(item_id="fake", category="fake", plan="Write hello.txt containing hi.",
+ starter={"README": "starter\n"}, toolset=toolset, gates=gates,
+ gate_names=("hello", "no_big"))
+ args.update(kw)
+ return harness.AgenticTask(**args)
+
+
+def rows_of(run_dir):
+ with open(os.path.join(run_dir, "items.jsonl")) as f:
+ return [json.loads(line) for line in f if line.strip()]
+
+
+def pid_dead(pid, timeout=3.0):
+ end = time.time() + timeout
+ while time.time() < end:
+ try:
+ os.kill(pid, 0)
+ except ProcessLookupError:
+ return True
+ time.sleep(0.05)
+ return False
+
+
+class Base(unittest.TestCase):
+ def setUp(self):
+ tools.WORK_ROOT = WORK
+ os.makedirs(WORK, exist_ok=True)
+
+ def run_fake(self, srv, task=None, lane=None, **kw):
+ kw.setdefault("max_turns", 6)
+ return harness.run_instrument("unit-agentic", "fake", [task or fake_task()],
+ lane=lane or srv.lane(), log=quiet, **kw)
+
+
+# ============================================================ the loop
+
+class Loop(Base):
+ def test_tools_cutoff_and_done(self):
+ os.environ["MAX_TOKENS"] = "7" # must be ignored: the lane/instrument own max_tokens
+ try:
+ with MockServer() as srv:
+ srv.script = [
+ chat("", tool_calls=[tool_call("write_file", {"path": "hello.txt",
+ "content": "hi"})]),
+ chat("", finish="length", tool_calls=[
+ tool_call("write_file", {"path": "a.txt", "content": "ok"}, "c1"),
+ tool_call("write_file", '{"path": "big.txt", "content": "unterminat',
+ "c2")]),
+ chat("All gates should pass now. DONE"),
+ ]
+ d = self.run_fake(srv)
+ reqs = [r["body"] for r in srv.requests]
+ finally:
+ os.environ.pop("MAX_TOKENS", None)
+ self.assertEqual(len(reqs), 3)
+ self.assertEqual(reqs[0]["max_tokens"], harness.MAX_TOKENS_DEFAULT)
+ self.assertEqual(reqs[0]["temperature"], 0.0)
+ self.assertEqual([t["function"]["name"] for t in reqs[0]["tools"]],
+ ["list_files", "read_file", "write_file", "edit_file", "search",
+ "run_build", "run_test", "run_shell"])
+ # the request after the cut-off turn: broken args repaired to "{}", cut call reported
+ msgs = reqs[2]["messages"]
+ a = [m for m in msgs if m["role"] == "assistant" and m.get("tool_calls")][-1]
+ self.assertEqual(json.loads(a["tool_calls"][0]["function"]["arguments"]),
+ {"path": "a.txt", "content": "ok"})
+ self.assertEqual(a["tool_calls"][1]["function"]["arguments"], "{}")
+ tool_msgs = {m["tool_call_id"]: m["content"] for m in msgs if m["role"] == "tool"}
+ self.assertTrue(tool_msgs["c1"].startswith("wrote a.txt"))
+ self.assertIn("max_tokens limit", tool_msgs["c2"])
+ self.assertIn("NOT executed", tool_msgs["c2"])
+ (row,) = rows_of(d)
+ self.assertEqual(row["status"], "ok")
+ self.assertEqual(row["stop_reason"], "done")
+ self.assertIs(row["correct"], True)
+ self.assertEqual(row["score"], 1.0)
+ self.assertEqual(row["cut_off_turns"], 1)
+ self.assertEqual(row["turns_used"], 3)
+ self.assertEqual(row["category"], "fake")
+ self.assertEqual(row["prompt_tokens"], 30)
+ self.assertIsNone(row["reasoning_tokens"]) # never reported: None, not 0
+ work = os.path.join(WORK, row["run_id"], "fake-0")
+ self.assertTrue(os.path.exists(os.path.join(work, "a.txt")))
+ self.assertFalse(os.path.exists(os.path.join(work, "big.txt")))
+ side = _jload((os.path.join(d, row["turn_log"])))
+ t2 = side["turns"][1]
+ self.assertTrue(t2["cut_off"])
+ self.assertEqual([t["executed"] for t in t2["tools"]], [True, False])
+ self.assertIn("unterminat", t2["tools"][1]["args_head"])
+ self.assertTrue(side["turns"][2]["done"])
+ run = _jload((os.path.join(d, "run.json")))
+ self.assertTrue(run["complete"])
+ self.assertTrue(run["item_set"].startswith("fake@"))
+
+ def test_call_error_mid_loop_records_label_and_gates(self):
+ with MockServer() as srv:
+ srv.script = [
+ chat("", tool_calls=[tool_call("write_file", {"path": "hello.txt",
+ "content": "hi"})]),
+ (500, {"error": "template raised"}),
+ ]
+ d = self.run_fake(srv)
+ self.assertEqual(len(srv.requests), 2) # 500 is not retried, loop stops
+ (row,) = rows_of(d)
+ self.assertEqual(row["status"], "http_500")
+ self.assertEqual(row["stop_reason"], "http_500")
+ self.assertIsNone(row["correct"])
+ self.assertIsNone(row["score"])
+ self.assertEqual(row["gates"], {"hello": True, "no_big": True}) # still graded, as info
+ self.assertEqual(row["turns_used"], 2)
+ self.assertIn("template raised", row["error"])
+ self.assertTrue(_jload((os.path.join(d, "run.json")))["complete"])
+
+ def test_budget_stop_stops_the_run(self):
+ cost = {"ledger": "unittest-agentic", "cap_usd": 1e-9, "in_per_m": 1.0, "out_per_m": 1.0}
+ with MockServer() as srv:
+ d = self.run_fake(srv, lane=srv.lane(lane_id="mock-budget", cost=cost), samples=3)
+ self.assertEqual(len(srv.requests), 0) # refused client-side
+ rows = rows_of(d)
+ self.assertEqual(len(rows), 1) # the run stopped after the first attempt
+ self.assertEqual(rows[0]["status"], "budget_stop")
+ self.assertIsNone(rows[0]["correct"])
+ run = _jload((os.path.join(d, "run.json")))
+ self.assertFalse(run["complete"])
+ self.assertEqual(_jload((os.path.join(d, "summary.json")))["stopped"], "budget_stop")
+
+ def test_give_up_rule_and_nudge(self):
+ with MockServer() as srv:
+ srv.script = [chat("", reasoning="I am DONE thinking"), chat("still planning")]
+ d = self.run_fake(srv, task=fake_task(give_up_after=2))
+ self.assertEqual(len(srv.requests), 2)
+ self.assertEqual(srv.requests[1]["body"]["messages"][-1],
+ {"role": "user", "content": harness.NUDGE})
+ (row,) = rows_of(d)
+ self.assertEqual(row["stop_reason"], "gave_up") # DONE in reasoning doesn't count
+ self.assertIs(row["correct"], False)
+ self.assertEqual(row["score"], 0.5)
+
+ def test_never_give_up_runs_to_cap_and_none_finish(self):
+ with MockServer() as srv:
+ srv.script = [chat("prose", finish=None), chat("more prose", finish=None),
+ chat("and more", finish=None)]
+ d = self.run_fake(srv, task=fake_task(give_up_after=None), max_turns=3)
+ self.assertEqual(len(srv.requests), 3)
+ (row,) = rows_of(d)
+ self.assertEqual(row["stop_reason"], "max_turns")
+ self.assertIsNone(row["finish"])
+ self.assertEqual(row["finish_counts"], {"None": 3})
+
+ def test_resume_retries_only_infra_failures(self):
+ with MockServer() as srv:
+ ok = [chat("", tool_calls=[tool_call("write_file", {"path": "hello.txt",
+ "content": "hi"})]),
+ chat("DONE")]
+ srv.script = [(500, {"error": "boom"})] + ok
+ d = self.run_fake(srv, samples=2)
+ self.assertEqual([r["status"] for r in rows_of(d)], ["http_500", "ok"])
+ srv.script = list(ok)
+ d2 = harness.run_instrument("unit-agentic", "fake", [fake_task()], resume=d,
+ lane=srv.lane(), log=quiet)
+ self.assertEqual(d2, d)
+ rows = rows_of(d)
+ self.assertEqual([(r["sample_idx"], r["status"]) for r in rows],
+ [(0, "http_500"), (1, "ok"), (0, "ok")])
+ self.assertTrue(_jload((os.path.join(d, "run.json")))["complete"])
+ with self.assertRaises(SystemExit): # changed definitions never resume silently
+ harness.run_instrument("unit-agentic", "fake", [fake_task(plan="other")],
+ resume=d, lane=srv.lane(), log=quiet)
+
+ def test_harness_error_keeps_turn_log(self):
+ weird = {"id": "x", "choices": [{"index": 0, "message": "not-a-dict",
+ "finish_reason": "stop"}], "usage": {}}
+ with MockServer() as srv:
+ srv.script = [chat("", tool_calls=[tool_call("write_file", {"path": "hello.txt",
+ "content": "hi"})]),
+ weird]
+ d = self.run_fake(srv)
+ (row,) = rows_of(d)
+ self.assertEqual(row["status"], "harness_error")
+ self.assertEqual(row["stop_reason"], "harness_error")
+ self.assertIsNone(row["correct"])
+ self.assertEqual(row["gates"], {"hello": True, "no_big": True})
+ side = _jload((os.path.join(d, row["turn_log"])))
+ self.assertEqual(side["turns"][0]["tools"][0]["name"], "write_file")
+ self.assertEqual(side["turns"][-1]["status"], "harness_error")
+
+ def test_concurrent_samples_are_isolated(self):
+ def respond(body):
+ last = body["messages"][-1]
+ if last["role"] == "tool":
+ return chat("DONE")
+ return chat("", tool_calls=[tool_call("write_file", {"path": "hello.txt",
+ "content": "hi"})])
+ with MockServer() as srv:
+ srv.default = respond
+ d = self.run_fake(srv, lane=srv.lane(max_concurrency=3), samples=3, concurrency=3)
+ self.assertEqual(len(srv.requests), 6)
+ rows = rows_of(d)
+ self.assertEqual(sorted(r["sample_idx"] for r in rows), [0, 1, 2])
+ self.assertTrue(all(r["correct"] for r in rows))
+ self.assertEqual(len({r["work_dir"] for r in rows}), 3)
+ self.assertEqual(_jload((os.path.join(d, "run.json")))["args"]["concurrency"], 3)
+
+ def test_port_substituted_and_released(self):
+ seen = {}
+
+ def start_server(body):
+ plan = body["messages"][0]["content"]
+ port = int(plan.rsplit(" ", 1)[1])
+ seen["port"], seen["plan"] = port, plan
+ cmd = (f"{sys.executable} -m http.server {port} --bind 127.0.0.1 "
+ f">/dev/null 2>&1 &")
+ return chat("", tool_calls=[tool_call("run_shell", {"cmd": cmd})])
+
+ def check_and_finish(body):
+ end = time.time() + 5
+ while time.time() < end and not tools._listening(seen["port"]):
+ time.sleep(0.05)
+ seen["listening"] = tools._listening(seen["port"])
+ return chat("DONE")
+
+ with MockServer() as srv:
+ srv.script = [start_server, check_and_finish]
+ task = fake_task(plan="Serve on port PORTX", port_token="PORTX")
+ d = self.run_fake(srv, task=task)
+ (row,) = rows_of(d)
+ self.assertNotIn("PORTX", seen["plan"])
+ self.assertEqual(row["port"], seen["port"])
+ self.assertTrue(seen["listening"], "the model's background server never came up")
+ self.assertIs(row["port_released"], True)
+ self.assertEqual(row["survivors"], 0)
+ self.assertTrue(tools.port_is_free(seen["port"]))
+
+
+# ============================================================ DONE detection
+
+class Done(unittest.TestCase):
+ def test_said_done(self):
+ yes = ["DONE", "done.", "Done!", "`DONE`", "All tests pass. DONE", "I'm done",
+ "DONE — all gates green", "Not quite yet... actually, DONE.",
+ "It's not done in Go style, but the app is DONE"]
+ no = ["", None, "abandoned", "undone", "not done", "I'm not done yet",
+ "isn't done", "haven't done the tests", "never done", "Not quite done",
+ "done_flag = true is set", "DONEness"]
+ for s in yes:
+ self.assertTrue(tools.said_done(s), s)
+ for s in no:
+ self.assertFalse(tools.said_done(s), s)
+
+
+# ============================================================ tool hygiene
+
+class Hygiene(Base):
+ def setUp(self):
+ super().setUp()
+ self.ws = tools.Workspace(tempfile.mkdtemp(dir=_TMP))
+ self.ts = tools.GO_TOOLSET
+
+ def tearDown(self):
+ self.assertEqual(self.ws.close(), [])
+
+ def call(self, name, args):
+ text, _stop = tools.run_tool(self.ws, self.ts, name, args)
+ return text
+
+ def test_parse_args(self):
+ self.assertEqual(tools.parse_args('{"a": 1}'), ({"a": 1}, None))
+ self.assertEqual(tools.parse_args({"a": 1}), ({"a": 1}, None))
+ self.assertEqual(tools.parse_args(""), ({}, None))
+ self.assertEqual(tools.parse_args(None), ({}, None))
+ for bad in ("[1, 2]", '"str"', "3", "{broken", ["x"], 7):
+ args, err = tools.parse_args(bad)
+ self.assertIsNone(args, bad)
+ self.assertTrue(err)
+
+ def test_bad_inputs_never_raise(self):
+ with open(os.path.join(self.ws.dir, "bin.dat"), "wb") as f:
+ f.write(b"\x00\x01\x02binary")
+ with open(os.path.join(self.ws.dir, "latin1.txt"), "wb") as f:
+ f.write(b"caf\xe9\n")
+ os.symlink("/", os.path.join(self.ws.dir, "root"))
+ cases = [
+ ("read_file", "path", "", "no such file"),
+ ("read_file", "path", "/etc/hosts", "absolute"),
+ ("read_file", "path", "../outside.txt", "outside the work dir"),
+ ("read_file", "path", "root/etc/hosts", "outside the work dir"),
+ ("read_file", "path", ["a"], "path must be"),
+ ("read_file", "path", "bin.dat", "binary file"),
+ ("write_file", "path", "", "path must be"),
+ ("write_file", "path", "/tmp/x", "absolute"),
+ ("edit_file", "path", "latin1.txt", "not a UTF-8 text file"),
+ ]
+ for tool, key, val, want in cases:
+ args = {key: val}
+ if tool == "edit_file":
+ args.update(old_str="caf", new_str="x")
+ out = self.call(tool, args)
+ self.assertTrue(out.startswith("ERROR"), (tool, val, out))
+ self.assertIn(want, out, (tool, val, out))
+ self.assertIn("must be a string", self.call("write_file", {"path": "a.txt", "content": {"x": 1}}))
+ self.assertIn("unknown tool", self.call("no_such_tool", {}))
+ self.assertIn("empty cmd", self.call("run_shell", {}))
+ self.assertIn("bad regex", self.call("search", {"pattern": "("}))
+ self.assertEqual(self.call("read_file", {"path": "latin1.txt"}), "caf�\n")
+ self.assertEqual(self.call("search", {"pattern": "binary"}), "(no matches)")
+ self.assertEqual(self.call("write_file", {"path": "sub/ok.txt", "content": "fine"}),
+ "wrote sub/ok.txt (4 bytes)")
+ self.assertIn("sub/ok.txt", self.call("list_files", {}))
+
+ def test_impl_exception_is_a_result(self):
+ def boom(ws, args):
+ raise KeyError("nope")
+ ts = tools.Toolset("t", [], {"boom": boom})
+ text, stop = tools.run_tool(self.ws, ts, "boom", {})
+ self.assertEqual(text, "ERROR: boom raised KeyError('nope')")
+ self.assertFalse(stop)
+
+ def test_loop_rejects_non_object_args(self):
+ with MockServer() as srv:
+ srv.script = [chat("", tool_calls=[tool_call("write_file", '["hello.txt", "hi"]', "c0"),
+ tool_call("write_file", "not json", "c1")]),
+ chat("DONE")]
+ out = tools.agent_loop(self.ws, [{"role": "user", "content": "go"}], self.ts,
+ max_turns=4, max_tokens=100, temperature=0.0,
+ lane=srv.lane(), log=quiet,
+ bad_json_fmt="ERROR: invalid JSON args ({e}); re-emit the {name} call.")
+ msgs = srv.requests[1]["body"]["messages"]
+ self.assertEqual(out["stop_reason"], "done")
+ tool_msgs = [m["content"] for m in msgs if m["role"] == "tool"]
+ self.assertEqual(len(tool_msgs), 2)
+ self.assertIn("must be a JSON object, got list", tool_msgs[0])
+ self.assertTrue(tool_msgs[1].startswith("ERROR: invalid JSON args"))
+ self.assertEqual(os.listdir(self.ws.dir), [])
+
+
+# ============================================================ isolation
+
+class Isolation(Base):
+ def test_timeout_kills_the_whole_group(self):
+ ws = tools.Workspace(tempfile.mkdtemp(dir=_TMP))
+ t0 = time.time()
+ r = ws.run("sleep 30 & echo $! > child.pid; sleep 30", timeout=1)
+ self.assertTrue(r.timed_out)
+ self.assertLess(time.time() - t0, 10)
+ self.assertEqual(r.text(), "TIMEOUT after 1s")
+ child = int(_read(os.path.join(ws.dir, "child.pid")))
+ self.assertTrue(pid_dead(child), "background child survived the timeout")
+ self.assertEqual(ws.close(), [])
+
+ def test_background_child_reaped_at_item_end(self):
+ ws = tools.Workspace(tempfile.mkdtemp(dir=_TMP))
+ t0 = time.time()
+ text, _ = tools.run_tool(ws, tools.GO_TOOLSET, "run_shell", {"cmd": "sleep 30 & echo $!"})
+ self.assertLess(time.time() - t0, 5, "a child holding stdout stalled the tool call")
+ self.assertTrue(text.startswith("exit=0"), text)
+ child = int(text.split("\n", 1)[1].strip())
+ os.kill(child, 0) # still alive between tool calls (servers may outlive the call)
+ self.assertEqual(ws.close(), [])
+ self.assertTrue(pid_dead(child), "background child survived the item")
+
+ @unittest.skipUnless(os.path.isdir("/proc/self") and shutil.which("setsid"), "needs Linux /proc + setsid")
+ def test_setsid_escapee_killed_at_item_end(self):
+ # What a real go_htmx run did (2026-10-06): `setsid /tmp/locsrv > log 2>&1 &` left the
+ # tool's process group, so the group kill missed it and it listened for 20 h.
+ ws = tools.Workspace(tempfile.mkdtemp(dir=_TMP))
+ text, _ = tools.run_tool(ws, tools.GO_TOOLSET, "run_shell",
+ {"cmd": "setsid sleep 300 > /dev/null 2>&1 & echo $!"})
+ self.assertTrue(text.startswith("exit=0"), text)
+ child = int(text.split("\n", 1)[1].strip())
+ time.sleep(0.2)
+ self.assertNotEqual(os.getpgid(child), os.getpgid(0))
+ self.assertIn(child, tools.marked_pids(ws.marker))
+ self.assertEqual(ws.close(), [])
+ self.assertTrue(pid_dead(child), "setsid'd child survived the item")
+
+ def test_popen_stop_kills_grandchildren(self):
+ ws = tools.Workspace(tempfile.mkdtemp(dir=_TMP))
+ proc = ws.popen(["sh", "-c", "sleep 30 & echo $! > gc.pid; wait"])
+ end = time.time() + 5
+ while not os.path.exists(os.path.join(ws.dir, "gc.pid")) and time.time() < end:
+ time.sleep(0.05)
+ time.sleep(0.1)
+ gc = int(_read(os.path.join(ws.dir, "gc.pid")))
+ ws.stop(proc, grace=1)
+ self.assertTrue(pid_dead(gc), "grandchild survived stop()")
+ self.assertEqual(ws.close(), [])
+
+
+# ============================================================ per-task toolsets + gates
+
+class Toolsets(Base):
+ def _fake_bin(self, names):
+ d = tempfile.mkdtemp(dir=_TMP)
+ for n in names:
+ p = os.path.join(d, n)
+ with open(p, "w") as f:
+ f.write(f'#!/bin/sh\necho "fake {n} $*"\n')
+ os.chmod(p, 0o755)
+ return d
+
+ def test_rust_and_ts_tools_run_their_own_toolchain(self):
+ fake = self._fake_bin(["cargo", "npx", "npm", "go"])
+ ws = tools.Workspace(tempfile.mkdtemp(dir=_TMP),
+ env={"PATH": fake + os.pathsep + os.environ["PATH"]})
+ try:
+ run = lambda ts, n: tools.run_tool(ws, ts, n, {})[0] # noqa: E731
+ self.assertEqual(run(tools.RUST_TOOLSET, "run_build"), "exit=0\nfake cargo build")
+ self.assertEqual(run(tools.RUST_TOOLSET, "run_test"), "exit=0\nfake cargo test")
+ self.assertEqual(run(tools.TS_TOOLSET, "run_build"), "exit=0\nfake npx tsc --noEmit")
+ self.assertEqual(run(tools.TS_TOOLSET, "run_test"), "exit=0\nfake npm test")
+ self.assertEqual(run(tools.GO_TOOLSET, "run_build"), "exit=0\nfake go build ./...")
+ finally:
+ ws.close()
+ desc = {t["function"]["name"]: t["function"]["description"] for t in tools.RUST_TOOLSET.schema}
+ self.assertIn("`cargo build`", desc["run_build"])
+ self.assertIn("`cargo test`", desc["run_test"])
+ self.assertNotRegex(desc["run_build"] + desc["run_test"] + desc["run_shell"], r"\bgo\b")
+ desc = {t["function"]["name"]: t["function"]["description"] for t in tools.TS_TOOLSET.schema}
+ self.assertIn("`npx tsc --noEmit`", desc["run_build"])
+ self.assertIn("`npm test`", desc["run_test"])
+ for name, ts in (("rust_cli", tools.RUST_TOOLSET), ("ts_next", tools.TS_TOOLSET),
+ ("go_htmx", tools.GO_TOOLSET)):
+ self.assertIs(harness.load_task(name).toolset, ts)
+
+ def test_test_count_parsers(self):
+ go_out = ("=== RUN TestA\n--- PASS: TestA (0.00s)\n=== RUN TestB\n"
+ " --- PASS: TestB/sub (0.00s)\n--- PASS: TestB (0.00s)\nPASS\n"
+ "ok \tx\t0.1s\n")
+ self.assertEqual(tools.go_tests_passed(go_out), 3)
+ self.assertEqual(tools.go_tests_passed("ok \tx\t0.1s [no tests to run]\n"), 0)
+ cargo_out = ("running 1 test\ntest tests::a ... ok\n\ntest result: ok. 1 passed; 0 failed; "
+ "0 ignored\n\nrunning 0 tests\n\ntest result: ok. 0 passed; 0 failed;\n"
+ " Doc-tests x\ntest result: ok. 2 passed; 0 failed;\n")
+ self.assertEqual(tools.cargo_tests_passed(cargo_out), 3)
+ self.assertEqual(tools.cargo_tests_passed("test result: ok. 0 passed; 0 failed;"), 0)
+
+ def test_plan_port_substitution(self):
+ t = harness.load_task("go_htmx")
+ self.assertIn("8080", t.plan)
+ plan = t.plan_for(45678)
+ self.assertNotIn("8080", plan)
+ self.assertIn("45678", plan)
+ for name in ("rust_cli", "ts_next"):
+ self.assertIsNone(harness.load_task(name).port_token)
+
+
+class DigestMock(unittest.TestCase):
+ def _get(self, port, auth=None, target="/"):
+ c = http.client.HTTPConnection("127.0.0.1", port, timeout=5)
+ c.request("GET", target, headers={"Authorization": auth} if auth else {})
+ r = c.getresponse()
+ body = r.read()
+ c.close()
+ return r.status, body, r.getheader("WWW-Authenticate")
+
+ @staticmethod
+ def _digest(user, password, uri, nc="00000001", cnonce="0a4f113b", method="GET"):
+ md5 = lambda s: hashlib.md5(s.encode()).hexdigest() # noqa: E731
+ ha1, ha2 = md5(f"{user}:test:{password}"), md5(f"{method}:{uri}")
+ resp = md5(f"{ha1}:abc123:{nc}:{cnonce}:auth:{ha2}")
+ return (f'Digest username="{user}", realm="test", nonce="abc123", uri="{uri}", '
+ f'qop=auth, nc={nc}, cnonce="{cnonce}", response="{resp}", opaque=""')
+
+ def test_mock_verifies_credentials(self):
+ srv = rust_cli._DigestMockServer()
+ srv.start()
+ try:
+ st, _, chal = self._get(srv.port)
+ self.assertEqual(st, 401)
+ self.assertIn('nonce="abc123"', chal)
+ self.assertEqual(self._get(srv.port, "Bearer whatever")[0], 401)
+ self.assertEqual(self._get(srv.port, "Digest junk")[0], 401)
+ self.assertEqual(self._get(srv.port, self._digest("admin", "wrong", "/"))[0], 401)
+ st, body, _ = self._get(srv.port, self._digest("admin", "secret", "/"))
+ self.assertEqual(st, 200)
+ self.assertIn(b"Camera-Front", body)
+ full = f"http://127.0.0.1:{srv.port}/" # digest_auth with the full URL as uri
+ self.assertEqual(self._get(srv.port, self._digest("admin", "secret", full))[0], 200)
+ self.assertEqual(self._get(srv.port, self._digest("admin", "secret", "/other"))[0], 401)
+ basic = "Basic " + __import__("base64").b64encode(b"admin:secret").decode()
+ self.assertEqual(self._get(srv.port, basic)[0], 200) # the PLAN promises Basic works
+ bad_basic = "Basic " + __import__("base64").b64encode(b"admin:nope").decode()
+ self.assertEqual(self._get(srv.port, bad_basic)[0], 401)
+ self.assertEqual(srv.served_xml, 3)
+ self.assertEqual([a["scheme"] for a in srv.auth_log if a["ok"]],
+ ["digest", "digest", "basic"])
+ finally:
+ srv.stop()
+ self.assertFalse(srv.thread.is_alive())
+
+
+# ============================================================ real reference solutions
+
+class Validate(Base):
+ def _validate(self, task):
+ buf = io.StringIO()
+ with contextlib.redirect_stdout(buf):
+ ok = harness.run_validate([task], log=quiet)
+ self.assertTrue(ok, buf.getvalue()[-3000:])
+
+ @unittest.skipUnless(shutil.which("go"), "go toolchain not installed")
+ def test_go_htmx_reference(self):
+ self._validate(harness.load_task("go_htmx"))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_claude_cli.py b/tests/test_claude_cli.py
new file mode 100644
index 0000000..4e910a9
--- /dev/null
+++ b/tests/test_claude_cli.py
@@ -0,0 +1,124 @@
+"""Offline tests for bench/core/claude_cli.py: tests/fake_claude.py stands in for `claude -p` and
+drives the real MCP relay and bridge, so no tokens are spent."""
+import json
+import os
+import unittest
+
+from _util import TMP
+from bench.core import claude_cli, client, lane as lane_mod, tools
+from bench.tasks import agentic_multitask as harness
+
+FAKE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fake_claude.py")
+ARGV = os.path.join(TMP, "fake-claude-argv.json")
+
+
+def _explode(ws, args):
+ raise tools.InfraError("container gone")
+
+
+def _submit(ws, args):
+ ws.state["submitted"] = True
+ return tools.ToolResult("received", stop=True)
+
+
+TOOLSET = tools.Toolset("fake-claude", [
+ {"type": "function", "function": {"name": n, "description": n + " tool",
+ "parameters": {"type": "object", "properties": {}}}}
+ for n in ("run", "submit", "explode")],
+ {"run": lambda ws, a: "ran: " + str(a.get("command")), "submit": _submit, "explode": _explode})
+
+
+def task(**kw):
+ args = dict(item_id="fake", category="fake", plan="", starter={}, toolset=TOOLSET,
+ gates=lambda ws, port=None: ({"submitted": ws.state.get("submitted", False)}, {}),
+ gate_names=("submitted",), system_tmpl="SYSTEM PROMPT", user="USER PROMPT",
+ nudge="NUDGE", done_word=False)
+ args.update(kw)
+ return harness.AgenticTask(**args)
+
+
+def lane(**kw):
+ raw = {"lane_id": "claude-fake", "endpoint": "claude-cli", "model": "claude-test",
+ "runner": "claude-cli", "effort": "low", "http_timeout": 30, "snapshot": "none"}
+ raw.update(kw)
+ return lane_mod.Lane(raw, "test")
+
+
+class ClaudeCli(unittest.TestCase):
+ def setUp(self):
+ tools.WORK_ROOT = os.path.join(TMP, "work")
+ self._bin, claude_cli.CLAUDE = claude_cli.CLAUDE, FAKE
+
+ def tearDown(self):
+ claude_cli.CLAUDE = self._bin
+ os.environ.pop("FAKE_CLAUDE", None)
+
+ def run_one(self, scenario, t=None, ln=None, max_turns=6):
+ os.environ["FAKE_CLAUDE"] = json.dumps(dict(scenario, argv_file=ARGV))
+ d = harness.run_instrument("unit-claude", "fake", [t or task()], lane=ln or lane(),
+ log=lambda *a, **k: None, max_turns=max_turns)
+ with open(os.path.join(d, "items.jsonl")) as f:
+ rows = [json.loads(x) for x in f if x.strip()]
+ with open(os.path.join(d, rows[-1]["turn_log"])) as f:
+ return rows[-1], json.load(f)
+
+ def test_tools_then_stop(self):
+ row, side = self.run_one({"queries": [[
+ {"tools": [["run", {"command": "echo hi"}]], "out": 10, "think": 3},
+ {"tools": [["submit", {}], ["run", {"command": "late"}]], "out": 20}]]})
+ self.assertEqual((row["status"], row["stop_reason"], row["correct"]), ("ok", "done", True))
+ self.assertEqual((row["turns_used"], row["tool_calls"]), (2, 3))
+ self.assertEqual((row["prompt_tokens"], row["completion_tokens"], row["reasoning_tokens"]),
+ (220, 30, 3))
+ self.assertEqual((row["claude_model"], row["claude_version"]), ("claude-test", "0.0-fake"))
+ t1, t2 = side["turns"]
+ self.assertEqual([(c["name"], c["executed"]) for c in t1["tools"] + t2["tools"]],
+ [("run", True), ("submit", True), ("run", False)])
+ self.assertEqual(t1["tools"][0]["result_head"], "ran: echo hi")
+ self.assertEqual(t2["tools"][1]["result_head"], claude_cli.ENDED) # after the stop tool
+ self.assertTrue(t2["done"])
+ with open(ARGV) as f:
+ argv = json.load(f)
+ i = argv.index("--allowedTools")
+ self.assertEqual(argv[i + 1:i + 4], ["mcp__bench__run", "mcp__bench__submit", "mcp__bench__explode"])
+ for flag, val in (("--tools", ""), ("--setting-sources", ""), ("--model", "claude-test"),
+ ("--effort", "low"), ("--permission-mode", "dontAsk")):
+ self.assertEqual(argv[argv.index(flag) + 1], val, flag)
+ with open(ARGV + ".system") as f:
+ self.assertEqual(f.read(), "SYSTEM PROMPT")
+ self.assertFalse(any("SYSTEM PROMPT" in a for a in argv)) # a `pkill -f <plan text>` can't hit claude
+ self.assertIn("--strict-mcp-config", argv)
+
+ def test_no_tool_turns_nudge_done_word_and_give_up(self):
+ row, side = self.run_one({"queries": [[{"text": "hmm"}], [{"tools": [["submit", {}]]}]]})
+ self.assertEqual((row["stop_reason"], row["turns_used"], row["correct"]), ("done", 2, True))
+ self.assertTrue(side["turns"][0]["nudged"])
+ row, _ = self.run_one({"queries": [[{"text": "a"}], [{"text": "b"}]]}, task(give_up_after=2))
+ self.assertEqual((row["stop_reason"], row["turns_used"], row["correct"]), ("gave_up", 2, False))
+ row, _ = self.run_one({"queries": [[{"text": "All finished. DONE"}]]}, task(done_word=True))
+ self.assertEqual((row["stop_reason"], row["turns_used"]), ("done", 1))
+
+ def test_turn_cap(self):
+ row, side = self.run_one({"forever": {"tools": [["run", {"command": "x"}]]}}, max_turns=3)
+ self.assertEqual((row["status"], row["stop_reason"], row["turns_used"]), ("ok", "max_turns", 3))
+ self.assertEqual(len(side["turns"]), 3)
+
+ def test_failures_are_infra(self):
+ cases = [({"queries": [[{"error": "Claude AI usage limit reached"}]]}, {}, "http_429"),
+ ({"connected": False, "queries": []}, {}, "conn_error"),
+ ({"sleep": 5, "queries": []}, {"http_timeout": 1}, "timeout"),
+ ({"queries": [[{"tools": [["explode", {}]]}]]}, {}, "harness_error")]
+ for scenario, lane_kw, status in cases:
+ with self.subTest(status=status):
+ row, _ = self.run_one(scenario, ln=lane(**lane_kw))
+ self.assertEqual(row["status"], status, row.get("error"))
+ self.assertIsNone(row["correct"])
+
+ def test_http_client_refuses_a_claude_lane(self):
+ with self.assertRaises(client.CallError) as cm:
+ client.call_model([{"role": "user", "content": "x"}], lane=lane())
+ self.assertEqual(cm.exception.label(), "guard_refused")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_conformance.py b/tests/test_conformance.py
new file mode 100644
index 0000000..52dd2c3
--- /dev/null
+++ b/tests/test_conformance.py
@@ -0,0 +1,329 @@
+"""Offline tests for bench/tasks/conformance.py (MockServer only; never touches a real endpoint)."""
+import contextlib
+import io
+import os
+import unittest
+from contextlib import redirect_stdout
+from unittest import mock
+
+import _util # noqa: F401
+from bench.core import lane as lane_mod, results
+from bench.core.mockserver import MockServer, chat, tool_call # noqa: E402
+from bench.tasks import conformance as cf # noqa: E402
+from bench.tasks import toolcall_probes as tp # noqa: E402
+
+OFF = {"thinking": "off", "nothink": {"mechanism": "reasoning_effort_none"}}
+OR = {"snapshot": "openrouter", "extra_body": {"provider": {"order": ["deepinfra"],
+ "allow_fallbacks": False}}}
+
+
+def responder(reasoning=None, reasoning_field="reasoning_content", reasoning_tokens=None,
+ provider=None, max_tokens_ct=None, tools_ok=True):
+ def fn(body):
+ kw = dict(reasoning=reasoning, reasoning_field=reasoning_field, reasoning_tokens=reasoning_tokens,
+ provider=provider)
+ mt = body.get("max_tokens")
+ if mt == cf.CAP_SMALL:
+ n = max_tokens_ct or mt
+ return chat("1\n2\n3", finish="length", completion_tokens=n, **kw)
+ msgs = body["messages"]
+ if body.get("tools"):
+ if msgs[-1]["role"] == "tool":
+ return chat("It is 18 C and cloudy in Paris.", **kw)
+ if tools_ok:
+ return chat("", tool_calls=[tool_call("get_weather", {"city": "Paris"})], **kw)
+ return chat("I do not know.", **kw)
+ return chat("391", **kw)
+ return fn
+
+
+def run(srv, lane_id, checks=None, **lane_kw):
+ lane = srv.lane(lane_id=lane_id, **lane_kw)
+ offline = (mock.patch.object(results, "server_snapshot", lambda ln: {"kind": ln.snapshot_kind})
+ if lane.snapshot_kind == "openrouter" else contextlib.nullcontext())
+ with offline: # an openrouter snapshot would call openrouter.ai
+ store = results.RunStore("conformance", lane=lane)
+ buf = io.StringIO()
+ res = cf.run_conformance(lane, store, checks, out=lambda s: buf.write(s + "\n"))
+ store.finish({}, complete=True)
+ return {r.name: r for r in res}, buf.getvalue(), store
+
+
+class Conformance(unittest.TestCase):
+ def test_healthy_thinking_off_lane_passes(self):
+ card = "Qwen/Qwen3.8-27B"
+ with MockServer() as srv:
+ srv.default = responder()
+ res, text, store = run(srv, "cf-ok", merge_system_messages=True, card=card,
+ request=cf.load_cards()[card]["non_thinking"], **OFF)
+ bodies = [q["body"] for q in srv.requests]
+ self.assertFalse([r for r in res.values() if r.verdict == "FAIL"], text)
+ self.assertEqual(res["no_reasoning"].verdict, "PASS")
+ self.assertEqual(res["system_messages"].verdict, "PASS")
+ self.assertEqual(res["tool_roundtrip"].verdict, "PASS")
+ self.assertEqual(res["determinism"].verdict, "INFO")
+ self.assertIn("n_ctx=65536", res["server_snapshot"].detail)
+ self.assertIn("total_slots=2", res["server_snapshot"].detail)
+ self.assertNotIn("provider_pin", res) # not an openrouter lane
+ # every request carries a small explicit cap; the system-message request was merged
+ self.assertTrue(all(b["max_tokens"] <= cf.CAP_TOOL_ON for b in bodies))
+ sysreq = [b for b in bodies if sum(m["role"] == "system" for m in b["messages"]) >= 1
+ and any("terse" in (m.get("content") or "") for m in b["messages"])][0]
+ self.assertEqual(sum(m["role"] == "system" for m in sysreq["messages"]), 1)
+ rows = results.load_rows("conformance", "cf-ok")
+ self.assertEqual({r["category"] for r in rows}, {"conformance"})
+ self.assertIn("basic_reply", {r["item_id"] for r in rows})
+
+ def test_thinking_off_lane_that_leaks_reasoning_fails(self):
+ with MockServer() as srv:
+ srv.default = responder(reasoning="Let me think about 17*23...", reasoning_tokens=40)
+ res, text, store = run(srv, "cf-leak", **OFF)
+ self.assertEqual(res["no_reasoning"].verdict, "FAIL")
+ self.assertIn("leaked", res["no_reasoning"].detail)
+ rows = {r["item_id"]: r for r in results.load_rows("conformance", "cf-leak")}
+ self.assertIs(rows["no_reasoning"]["correct"], False)
+ self.assertEqual(rows["no_reasoning"]["verdict"], "FAIL")
+
+ def test_single_check_verdicts(self):
+ cases = [ # checks, responder kwargs (or a raw reply), lane kwargs, check, verdict, detail
+ (["system"], {}, OFF, "system_messages", "PASS", "lacks merge_system_messages"),
+ (["basic", "thinking"], {"reasoning_tokens": 0}, OFF, "no_reasoning", "PASS", ""),
+ (["basic", "thinking"], {"reasoning": "step by step", "reasoning_field": "reasoning"}, {},
+ "reasoning_field", "PASS", "field=reasoning reasoning_chars=12 reasoning_tokens=None"),
+ (["basic", "thinking"], {}, {}, "reasoning_field", "FAIL", ""),
+ (["maxtok"], {"max_tokens_ct": 500}, OFF, "max_tokens", "FAIL", ""),
+ (["tools"], {"tools_ok": False}, OFF, "tool_roundtrip", "WARN", "model: no tool call"),
+ (["basic"], (500, {"error": "template raised"}), OFF, "basic_reply", "FAIL", "request failed"),
+ (["basic", "provider"], {"provider": "Together"}, OR, "provider_pin", "FAIL", "Together"),
+ (["basic", "provider"], {"provider": "DeepInfra", "reasoning": "x"}, OR, "provider_pin",
+ "PASS", ""),
+ (["basic", "provider"], {"reasoning": "x"}, OR, "provider_pin", "FAIL", ""),
+ ]
+ for i, (checks, reply, lane_kw, name, verdict, detail) in enumerate(cases):
+ with self.subTest(case=i, check=name, reply=reply):
+ with MockServer() as srv:
+ srv.default = responder(**reply) if isinstance(reply, dict) else reply
+ res, _, _ = run(srv, "cf-case-%d" % i, checks=checks, **lane_kw)
+ self.assertEqual(res[name].verdict, verdict, res[name].detail)
+ self.assertIn(detail, res[name].detail)
+
+ def test_main_exit_code(self):
+ with MockServer() as srv:
+ srv.default = responder(reasoning="leak")
+ lane_mod.set_current(srv.lane(lane_id="cf-main", **OFF))
+ with redirect_stdout(io.StringIO()):
+ with self.assertRaises(SystemExit) as cm:
+ cf.main(["--checks", "basic,thinking"])
+ self.assertEqual(cm.exception.code, 1)
+
+
+XML_OK = '<tool_call>{"name": "web_search", "arguments": {"query": "gemma benchmarks", "limit": 5}}'
+GOOD = { # probe id -> a correct reply
+ "tc-native": chat("", tool_calls=[tool_call("get_weather", {"location": "Paris", "unit": "celsius"})]),
+ "tc-xml": chat(XML_OK + "</tool_call>"),
+ "tc-json": chat('{"name": "Maria", "age": 34, "skills": ["Go", "Rust"]}'),
+ "tc-notool": chat("Paris"),
+ "tc-multi": chat("", tool_calls=[tool_call("get_weather", {"location": "Paris", "unit": "celsius"}, "a"),
+ tool_call("get_weather", {"location": "Tokyo", "unit": "celsius"}, "b")]),
+ "tc-select": chat("", tool_calls=[tool_call("calculator", {"expression": "47 * 89"})]),
+ "tc-nested-json": chat('{"service": {"name": "api", "port": 8080}, "replicas": 3, "env": "production"}'),
+ "tc-derived": chat("", tool_calls=[tool_call("set_timer", {"seconds": 150})]),
+}
+
+
+def probe_responder(override=None):
+ """Answers each probe correctly (by its user text) unless `override` maps its id to a reply."""
+ texts = {p["id"]: p["messages"][-1]["content"] for p in tp.TOOLCALL}
+
+ def fn(body):
+ user = body["messages"][-1]["content"]
+ pid = next((i for i, t in texts.items() if t == user), None)
+ if pid:
+ return (override or {}).get(pid, GOOD[pid])
+ return responder()(body)
+ return fn
+
+
+def probes(srv, lane_id, **lane_kw):
+ res, text, _ = run(srv, lane_id, checks=["toolcalls", "think_tags"], **dict(OFF, **lane_kw))
+ return res, text
+
+
+class Probes(unittest.TestCase):
+ def test_validators(self):
+ calc = lambda args: chat("", tool_calls=[tool_call("calculator", args)]) # noqa: E731
+ timer = lambda args: chat("", tool_calls=[tool_call("set_timer", args)]) # noqa: E731
+ maria = '{"name": "Maria", "age": 34, "skills": ["Go", "Rust"]}'
+ api = '{"service": {"name": "API", "port": 8080}, "replicas": 3, "env": "production"}'
+ cases = [ # validator, response, ok
+ (tp._v_select, calc({"expression": "47 * 89"}), True),
+ (tp._v_select, calc({"expression": "47 + 3"}), False),
+ (tp._v_select, calc("47 * 89"), False),
+ (tp._v_select, chat("", tool_calls=[tool_call("web_search", {"query": "47*89"})]), False),
+ (tp._v_derived, timer({"seconds": 150}), True),
+ (tp._v_derived, timer({"seconds": "150"}), False),
+ (tp._v_derived, timer("{broken"), False),
+ (tp._v_json, chat(maria), True),
+ (tp._v_json, chat("```json\n" + maria + "\n```"), True),
+ (tp._v_json, chat(maria.replace("34", '"34"')), False),
+ (tp._v_json, chat(maria + " and " + maria), False),
+ (tp._v_nested, chat("Here: " + api), True),
+ (tp._v_nested, chat(api.replace("8080", '"8080"')), False),
+ (tp._v_xml, chat(XML_OK + "</tool_call>"), True),
+ (tp._v_xml, chat(XML_OK), True), # servers may strip the closing special token
+ (tp._v_xml, chat("<tool_call>\n" + XML_OK[len("<tool_call>"):] + "\n</tool_call>"), True),
+ (tp._v_xml, chat('{"name": "web_search", "arguments": {"query": "gemma", "limit": 5}}'), False),
+ (tp._v_xml, chat(XML_OK + " and some prose"), False),
+ ]
+ for fn, resp, ok in cases:
+ with self.subTest(fn=fn.__name__, resp=str(resp["choices"][0]["message"])[:80]):
+ self.assertIs(fn(resp)[0], ok)
+ self.assertIn('<tool_call>{"name": "<tool>", "arguments": {...}}</tool_call>',
+ next(p for p in tp.TOOLCALL if p["id"] == "tc-xml")["messages"][0]["content"])
+
+ def test_model_miss_warns_pipeline_fault_fails(self):
+ with MockServer() as srv:
+ srv.default = probe_responder()
+ res, text = probes(srv, "cf-probes-ok")
+ self.assertEqual({r.verdict for n, r in res.items() if n.startswith("tc-")}, {"PASS"}, text)
+ self.assertEqual(res["think_tags"].verdict, "PASS")
+ cases = [ # probe, reply, verdict, detail
+ ("tc-derived", chat("", tool_calls=[tool_call("set_timer", {"seconds": 120})]), "WARN", "model:"),
+ ("tc-notool", chat("Lyon"), "WARN", "model:"),
+ ("tc-native", chat('<tool_call>{"name": "get_weather", "arguments": {"location": "Paris"}}</tool_call>'),
+ "FAIL", "came back as text"),
+ ("tc-native", chat("", reasoning='{"name": "get_weather", "arguments": {}}', reasoning_tokens=40,
+ completion_tokens=60), "FAIL", ""),
+ ("tc-xml", chat("", reasoning="I will search.", reasoning_tokens=10, completion_tokens=80),
+ "FAIL", "output swallowed: 70 answer tokens"),
+ ("tc-json", chat(""), "FAIL", "no answer and no tool call"),
+ ("tc-json", chat("", finish="length"), "WARN", "model:"),
+ ]
+ for i, (pid, reply, verdict, detail) in enumerate(cases):
+ with self.subTest(case=i, probe=pid), MockServer() as srv:
+ srv.default = probe_responder({pid: reply})
+ res, text = probes(srv, "cf-probe-%d" % i)
+ self.assertEqual(res[pid].verdict, verdict, res[pid].detail)
+ self.assertIn(detail, res[pid].detail)
+
+ def test_think_tags(self):
+ cases = [ # basic reply, verdict, detail
+ (chat("391"), "PASS", "clean"),
+ (chat("<think>17*23</think>391"), "PASS", "inline in the content on 1"),
+ (chat("391</think>"), "FAIL", "think tag left in the content"),
+ (chat("391", reasoning="<think>17*23=391"), "FAIL", "inside the reasoning field"),
+ (chat("<think>17*23 is"), "FAIL", "never closed"),
+ (chat("", reasoning="17*23 = 391"), "FAIL", "only in the reasoning"),
+ ]
+ for i, (reply, verdict, detail) in enumerate(cases):
+ with self.subTest(case=i), MockServer() as srv:
+ srv.default = reply
+ res, _, _ = run(srv, "cf-think-%d" % i, checks=["basic", "think_tags"])
+ self.assertEqual(res["think_tags"].verdict, verdict, res["think_tags"].detail)
+ self.assertIn(detail, res["think_tags"].detail)
+
+
+class Require(unittest.TestCase):
+ def setUp(self):
+ os.environ["BENCH_PREFLIGHT"] = "1"
+
+ def tearDown(self):
+ os.environ["BENCH_PREFLIGHT"] = "0"
+
+ def test_gate_caches_and_blocks(self):
+ card = "Qwen/Qwen3.8-27B"
+ good = dict(OFF, card=card, request=cf.load_cards()[card]["non_thinking"], merge_system_messages=True)
+ with MockServer() as srv:
+ srv.default = probe_responder()
+ ln = srv.lane(lane_id="cf-require", **good)
+ with redirect_stdout(io.StringIO()):
+ cf.require(ln)
+ n = len(srv.requests)
+ cf.require(ln) # cached: same lane settings, passed < 24 h ago
+ self.assertEqual(len(srv.requests), n)
+ self.assertGreater(n, 8)
+ srv.default = probe_responder({"tc-native": chat("<tool_call>get_weather</tool_call>")})
+ bad = srv.lane(lane_id="cf-require-bad", **good)
+ with redirect_stdout(io.StringIO()), self.assertRaises(SystemExit) as cm:
+ cf.require(bad)
+ self.assertIn("tc-native", str(cm.exception))
+ cf.require(srv.lane(lane_id="cf-runner", runner="claude-cli")) # runner lanes: no preflight
+ os.environ["BENCH_PREFLIGHT"] = "0"
+ cf.require(bad) # explicit override
+
+
+CARD = {"revision": "ab" * 20,
+ "thinking": {"temperature": 1.0, "top_p": 0.95, "min_p": 0.0},
+ "non_thinking": {"temperature": 0.7, "top_p": 0.8, "min_p": 0.0}}
+
+
+def lane(request, **kw):
+ raw = {"lane_id": "cf-card", "endpoint": "http://127.0.0.1:9/v1/chat/completions", "model": "m",
+ "card": "org/model", "request": request}
+ raw.update(kw)
+ return lane_mod.Lane(raw, "test")
+
+
+class SamplerCard(unittest.TestCase):
+ def test_verdicts(self):
+ ok = {"temperature": 1.0, "top_p": 0.95, "min_p": 0.0, "max_tokens": 100}
+ lo = dict(ok, min_p=0.05)
+ cases = [ # lane, verdict, detail
+ (lane(ok), "PASS", "org/model@abababa thinking: matches"),
+ (lane(dict(ok, top_p=0.95000000001)), "PASS", "matches"),
+ (lane({"temperature": 0.7, "top_p": 0.8, "min_p": 0}, **OFF), "PASS", "non_thinking"),
+ (lane(lo), "FAIL", "min_p=0.05 (card 0.0)"),
+ (lane(dict(ok, temperature=0.7), **OFF), "FAIL", "top_p=0.95 (card 0.8)"),
+ (lane({"temperature": 1.0, "top_p": 0.95}), "FAIL", "min_p not sent (card 0.0)"),
+ (lane(ok, extra_body={"min_p": 0.1}), "FAIL", "min_p=0.1 (card 0.0)"), # extra_body wins
+ (lane(lo, sampler_overrides={"min_p": {"value": 0.05, "reason": "llama.cpp default"}}),
+ "PASS", "min_p=0.05 overridden (card 0.0): llama.cpp default"),
+ (lane(lo, sampler_overrides={"min_p": {"value": 0.05}}), "FAIL", "override has no reason"),
+ (lane(dict(ok, min_p=0.1), sampler_overrides={"min_p": {"value": 0.05, "reason": "x"}}),
+ "FAIL", "min_p=0.1 but sampler_overrides pins 0.05"),
+ (lane(ok, card=None), "FAIL", "names no model card"),
+ (lane(ok, card="org/other"), "FAIL", "no thinking sampler for org/other"),
+ ]
+ for i, (ln, verdict, detail) in enumerate(cases):
+ with self.subTest(case=i):
+ r = cf.sampler_check(ln, {"org/model": CARD})
+ self.assertEqual(r.verdict, verdict, r.detail)
+ self.assertIn(detail, r.detail)
+
+ def test_every_lane_names_a_pinned_card(self):
+ cards = cf.load_cards()
+ for card_id, card in cards.items():
+ with self.subTest(card=card_id):
+ self.assertRegex(card["revision"], r"^[0-9a-f]{40}$")
+ self.assertTrue(card["source"])
+ if "non_thinking" in card: # thinking-only models publish no non-thinking sampler
+ self.assertEqual(set(card["thinking"]), set(card["non_thinking"]))
+ for name in sorted(os.listdir(lane_mod.LANES_DIR)):
+ ln = lane_mod.load(name[:-5]) if name.endswith(".json") and name != "cards.json" else None
+ if ln is not None and not ln.raw.get("runner"):
+ with self.subTest(lane=name):
+ self.assertIn(ln.raw.get("card"), cards)
+
+ def test_shipped_lanes_match_their_card(self):
+ cards = cf.load_cards()
+ for name in sorted(os.listdir(lane_mod.LANES_DIR)):
+ if not name.endswith(".json") or name == "cards.json":
+ continue
+ ln = lane_mod.load(name[:-5])
+ if ln.raw.get("runner") or not ln.raw.get("card"):
+ continue
+ with self.subTest(lane=name):
+ r = cf.sampler_check(ln, cards)
+ self.assertEqual(r.verdict, "PASS", r.detail)
+
+ def test_check_sends_nothing_and_stores_a_row(self):
+ with MockServer() as srv:
+ res, text, store = run(srv, "cf-sampler", checks=["sampler"], card="nope")
+ self.assertEqual(srv.requests, [])
+ self.assertEqual(list(res), ["sampler_card"])
+ row = results.load_rows("conformance", "cf-sampler")[0]
+ self.assertEqual((row["verdict"], row["correct"], row["card"]), ("FAIL", False, "nope"))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_core.py b/tests/test_core.py
new file mode 100644
index 0000000..e0061a7
--- /dev/null
+++ b/tests/test_core.py
@@ -0,0 +1,228 @@
+"""Offline tests for bench.core (lane, client, ledger, results) against MockServer.
+
+Run from llm-bench/: python3 -m unittest discover -s tests -v
+"""
+import json
+import os
+import unittest
+
+import _util # noqa: F401
+from bench.core import client, ledger, results
+from bench.core.lane import Lane, LaneError # noqa: E402
+from bench.core.mockserver import MockServer, chat, tool_call # noqa: E402
+
+
+class BodyMerge(unittest.TestCase):
+ def lane(self, **kw):
+ raw = {"lane_id": "t", "endpoint": "http://x/v1/chat/completions", "model": "m"}
+ raw.update(kw)
+ return Lane(raw, "test")
+
+ def test_lane_request_wins_over_instrument_defaults(self):
+ lane = self.lane(request={"temperature": 1.0, "top_k": 20, "max_tokens": 32768})
+ body = client.build_body([{"role": "user", "content": "q"}], max_tokens=2000,
+ temperature=0.0, lane=lane)
+ self.assertEqual(body["temperature"], 1.0)
+ self.assertEqual(body["max_tokens"], 32768)
+ self.assertEqual(body["top_k"], 20)
+
+ def test_override_wins_over_lane(self):
+ lane = self.lane(request={"temperature": 1.0})
+ body = client.build_body([{"role": "user", "content": "q"}], override={"temperature": 0},
+ lane=lane)
+ self.assertEqual(body["temperature"], 0)
+
+ def test_extra_body_deep_merges(self):
+ lane = self.lane(extra_body={"provider": {"order": ["deepinfra"]}, "usage": {"include": True}})
+ body = client.build_body([{"role": "user", "content": "q"}], lane=lane,
+ override={"provider": {"allow_fallbacks": False}})
+ self.assertEqual(body["provider"], {"allow_fallbacks": False, "order": ["deepinfra"]})
+
+ def test_nothink_mechanisms(self):
+ msgs = [{"role": "user", "content": "q"}]
+ b = client.build_body(msgs, lane=self.lane(thinking="off",
+ nothink={"mechanism": "reasoning_effort_none"}))
+ self.assertEqual(b["reasoning_effort"], "none")
+ b = client.build_body(msgs, lane=self.lane(thinking="off",
+ nothink={"mechanism": "openrouter_reasoning_off"}))
+ self.assertFalse(b["reasoning"]["enabled"])
+ b = client.build_body(msgs, lane=self.lane(thinking="off",
+ nothink={"mechanism": "template_kwargs"}))
+ self.assertFalse(b["chat_template_kwargs"]["enable_thinking"])
+ b = client.build_body(msgs, lane=self.lane(thinking="off",
+ nothink={"mechanism": "think_prefill"}))
+ self.assertEqual(b["messages"][-1]["role"], "assistant")
+ with self.assertRaises(LaneError):
+ self.lane(thinking="off") # no mechanism
+
+ def test_thinking_on_lane_never_gets_nothink(self):
+ b = client.build_body([{"role": "user", "content": "q"}], lane=self.lane())
+ self.assertNotIn("reasoning_effort", b)
+ self.assertEqual(len(b["messages"]), 1)
+
+ def test_forbid_guard(self):
+ lane = self.lane(request={"reasoning_effort": "high"}, forbid={"reasoning_effort": ["high"]})
+ with self.assertRaises(client.CallError) as cm:
+ client.build_body([{"role": "user", "content": "q"}], lane=lane)
+ self.assertEqual(cm.exception.label(), "guard_refused")
+
+ def test_history_sanitized(self):
+ hist = [{"role": "user", "content": "q"},
+ {"role": "assistant", "content": "", "reasoning_content": "long thoughts",
+ "tool_calls": [tool_call("write_file", '{"path": "a.go", "content": "unterm'),
+ tool_call("list_files", "", "c1"),
+ {"id": "c2", "type": "function",
+ "function": {"name": "x", "arguments": {"a": 1}}}]},
+ {"role": "tool", "tool_call_id": "call_0", "content": "ERROR"}]
+ b = client.build_body(hist, lane=self.lane())
+ a = b["messages"][1]
+ self.assertNotIn("reasoning_content", a)
+ self.assertEqual(a["tool_calls"][0]["function"]["arguments"], "{}")
+ self.assertEqual(a["tool_calls"][1]["function"]["arguments"], "{}")
+ self.assertEqual(json.loads(a["tool_calls"][2]["function"]["arguments"]), {"a": 1})
+ self.assertIn("unterm", hist[1]["tool_calls"][0]["function"]["arguments"]) # caller untouched
+ keep = client.build_body(hist, lane=self.lane(reasoning_echo=True))
+ self.assertIn("reasoning_content", keep["messages"][1])
+
+ def test_merge_system_messages(self):
+ msgs = [{"role": "user", "content": "q"}, {"role": "system", "content": "A"},
+ {"role": "system", "content": "B"}]
+ b = client.build_body(msgs, lane=self.lane(merge_system_messages=True))
+ self.assertEqual(b["messages"][0], {"role": "system", "content": "A\n\nB"})
+ self.assertEqual([m["role"] for m in b["messages"]], ["system", "user"])
+
+
+class Extraction(unittest.TestCase):
+ def test_reasoning_fields(self):
+ self.assertEqual(client.reasoning(chat("a", reasoning="r1")), "r1")
+ self.assertEqual(client.reasoning(chat("a", reasoning="r2", reasoning_field="reasoning")), "r2")
+ inline = chat("<think>hmm</think>\n\nANSWER: 4")
+ self.assertEqual(client.reasoning(inline), "hmm")
+ self.assertEqual(client.content(inline), "ANSWER: 4")
+ unclosed = chat("<think>still going", finish="length")
+ self.assertEqual(client.content(unclosed), "")
+ self.assertEqual(client.status(unclosed), "truncated")
+
+ def test_usage_none_is_not_zero(self):
+ u = client.usage(chat("a"))
+ self.assertIsNone(u["reasoning_tokens"])
+ self.assertIsNone(u["cost_usd"])
+ u = client.usage(chat("a", reasoning_tokens=0, cost=0.001))
+ self.assertEqual(u["reasoning_tokens"], 0)
+ self.assertEqual(u["cost_usd"], 0.001)
+
+ def test_status_empty(self):
+ self.assertEqual(client.status(chat("")), "empty")
+ self.assertEqual(client.status(chat("", tool_calls=[tool_call("f", "{}")])), "ok")
+
+
+class Transport(unittest.TestCase):
+ def test_retry_then_success_and_auth(self):
+ with MockServer() as srv:
+ srv.script = [(429, {"error": "slow"}), (503, {"error": "busy"}), chat("ok")]
+ os.environ["T_KEY"] = "sekrit"
+ lane = srv.lane(auth={"env": "T_KEY"})
+ resp, _ = client.call_model([{"role": "user", "content": "q"}], lane=lane)
+ self.assertEqual(client.content(resp), "ok")
+ self.assertEqual(resp["_bench"]["attempts"], 3)
+ self.assertEqual(srv.requests[-1]["auth"], "Bearer sekrit")
+ self.assertNotIn("sekrit", json.dumps(lane.record()))
+
+ def test_500_not_retried(self):
+ with MockServer() as srv:
+ srv.script = [(500, {"error": "template raised"}), chat("never")]
+ with self.assertRaises(client.CallError) as cm:
+ client.call_model([{"role": "user", "content": "q"}], lane=srv.lane())
+ self.assertEqual(cm.exception.label(), "http_500")
+ self.assertEqual(len(srv.requests), 1)
+
+ def test_oom_label(self):
+ with MockServer() as srv:
+ srv.script = [(507, {"error": "out of memory"})]
+ with self.assertRaises(client.CallError) as cm:
+ client.call_model([{"role": "user", "content": "q"}], lane=srv.lane())
+ self.assertEqual(cm.exception.label(), "oom")
+
+ def test_openrouter_200_with_error(self):
+ with MockServer() as srv:
+ srv.script = [{"error": {"code": 502, "message": "provider down"}}, chat("ok")]
+ resp, _ = client.call_model([{"role": "user", "content": "q"}], lane=srv.lane())
+ self.assertEqual(client.content(resp), "ok")
+
+ def test_timeout_label(self):
+ import time as _t
+ with MockServer() as srv:
+ srv.script = [lambda body: (_t.sleep(1.5), chat("late"))[1]]
+ with self.assertRaises(client.CallError) as cm:
+ client.call_model([{"role": "user", "content": "q"}], lane=srv.lane(http_timeout=1))
+ self.assertEqual(cm.exception.label(), "timeout")
+
+
+class Budget(unittest.TestCase):
+ def test_cap_stops_before_overspend(self):
+ cost = {"ledger": "unittest-cap", "cap_usd": 0.05, "in_per_m": 1.0, "out_per_m": 10.0}
+ with MockServer() as srv:
+ srv.default = chat("ok", cost=0.008) # actual <= worst case, as with real pricing
+ lane = srv.lane(cost=cost, request={"max_tokens": 1000}) # worst case ~$0.01/call
+ n_ok = 0
+ for i in range(10):
+ try:
+ client.call_model([{"role": "user", "content": "q"}], lane=lane, item_id=f"i{i}")
+ n_ok += 1
+ except client.CallError as e:
+ self.assertEqual(e.label(), "budget_stop")
+ break
+ # spent 0.008*k; call k+1 allowed while spent + ~0.01 <= 0.05 -> 5 calls, then stop
+ self.assertEqual(n_ok, 5)
+ self.assertLessEqual(ledger.spent("unittest-cap"), 0.05)
+
+ def test_missing_provider_cost_is_estimated(self):
+ cost = {"ledger": "unittest-est", "cap_usd": 1.0, "in_per_m": 1.0, "out_per_m": 2.0}
+ with MockServer() as srv:
+ srv.default = chat("ok", prompt_tokens=1000, completion_tokens=500)
+ resp, _ = client.call_model([{"role": "user", "content": "q"}], lane=srv.lane(cost=cost))
+ self.assertAlmostEqual(resp["_bench"]["cost_usd"], 0.002)
+ self.assertTrue(resp["_bench"]["cost_estimated"])
+
+
+class Store(unittest.TestCase):
+ def test_run_layout_and_rows(self):
+ with MockServer() as srv:
+ lane = srv.lane(lane_id="store-test", auth={"env": "T_KEY"})
+ st = results.RunStore("unit", item_set="set@1", args={"k": 1}, lane=lane)
+ resp, dt = client.call_model([{"role": "user", "content": "q"}], lane=lane)
+ st.add(item_id="a", category="go", correct=True, **client.meta(resp, dt))
+ st.add(item_id="b", category="go", correct=False, status="http_500")
+ d = st.finish({"n": 2})
+ run = json.load(open(os.path.join(d, "run.json")))
+ self.assertTrue(run["complete"])
+ self.assertEqual(run["lane"]["lane_id"], "store-test")
+ self.assertNotIn("auth", run["lane"])
+ self.assertIn("chat_template_sha256", run["server"]["props"])
+ rows = results.load_rows("unit", "store-test")
+ self.assertEqual({r["item_id"]: r["correct"] for r in rows}, {"a": True, "b": None})
+ st2 = results.RunStore("unit", lane=lane)
+ self.assertNotEqual(st2.run_id, st.run_id)
+ self.assertEqual(len(results.load_rows("unit", "store-test")), 2) # st2 incomplete
+
+ def test_resume_and_sidecar(self):
+ with MockServer() as srv:
+ lane = srv.lane(lane_id="resume-test")
+ st = results.RunStore("unit-resume", lane=lane)
+ st.add(item_id="a", sample_idx=0, correct=True)
+ st.add(item_id="a", sample_idx=1, status="timeout")
+ name = st.sidecar("a-0.turns", {"turns": [1, 2]})
+ self.assertTrue(os.path.exists(os.path.join(st.dir, name)))
+ again = results.RunStore.resume(st.dir, lane=lane)
+ self.assertEqual(again.run_id, st.run_id)
+ self.assertEqual(again.done_keys(), {("a", 0)}) # the timeout gets retried
+ again.add(item_id="a", sample_idx=1, correct=False)
+ again.finish()
+ rows = results.load_rows("unit-resume", "resume-test") # the retry replaces the timeout
+ self.assertEqual([(r["sample_idx"], r["status"]) for r in rows], [(0, "ok"), (1, "ok")])
+ with self.assertRaises(ValueError):
+ results.RunStore.resume(st.dir, lane=srv.lane(lane_id="other"))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_fix.py b/tests/test_fix.py
new file mode 100644
index 0000000..282a599
--- /dev/null
+++ b/tests/test_fix.py
@@ -0,0 +1,177 @@
+"""Offline tests for bench/tasks/agentic_fix.py (both tiers) + bench/core/runners.py (MockServer only)."""
+import contextlib
+import io
+import os
+import shutil
+import tempfile
+import time
+import unittest
+
+from _util import TMP, run_dir, run_main
+from bench.core import lane as lane_mod, results, runners, tools
+from bench.core.mockserver import MockServer, chat, tool_call
+from bench.tasks import agentic_fix as af
+from bench.tasks import agentic_multitask as harness
+from bench.tasks import fix_easy, fix_hard
+from bench.tasks.fix_hard import go_kvstore
+
+EASY = {t["id"]: t for t in fix_easy.load()}
+
+
+def quiet(*_a, **_k):
+ pass
+
+
+def rows(lane_id):
+ return sorted(results.load_rows("agentic-fix", lane_id), key=lambda r: (r["item_id"], r["sample_idx"]))
+
+
+def run_easy(srv, lane_id, ids, samples=1, **lane_kw):
+ lane_mod.set_current(srv.lane(lane_id=lane_id, **lane_kw))
+ rc = run_main(af, ["run", "--tier", "easy", *ids, "--samples", str(samples)])
+ return rc, rows(lane_id)
+
+
+class Content(unittest.TestCase):
+ def test_ids_unique_and_runnable(self):
+ ids = [t["id"] for t in EASY.values()] + [m.ITEM_ID for m in fix_hard.load()]
+ self.assertEqual(len(set(ids)), len(ids))
+ for t in EASY.values():
+ self.assertIn(t["lang"], runners.RUNNERS, t["id"])
+ for m in fix_hard.load():
+ self.assertEqual(len(m.FIX), 1, m.ITEM_ID)
+ self.assertTrue(set(m.HIDDEN) <= set(m.PROJECT), m.ITEM_ID)
+ self.assertNotRegex("".join(m.PROJECT.values()), r"\bBUG\b|FIXME", m.ITEM_ID)
+
+ def test_easy_item_set_is_the_whole_tier(self):
+ whole = af.easy_item_set(list(EASY.values()))
+ self.assertTrue(whole.startswith("fix-easy@"))
+ msgs = af.easy_messages(EASY["go-average"])
+ self.assertIn("expert Go developer", msgs[0]["content"])
+ changed = dict(EASY["go-average"], symptom="different")
+ self.assertNotEqual(af.easy_item_set([changed] + [t for i, t in EASY.items() if i != "go-average"]),
+ whole)
+
+
+@unittest.skipUnless(shutil.which("go"), "go missing")
+class EasyTier(unittest.TestCase):
+ def test_passing_go_task(self):
+ with MockServer() as srv:
+ srv.default = chat("```go\n" + EASY["go-average"]["fix"] + "```", reasoning="think",
+ prompt_tokens=100, completion_tokens=40)
+ rc, (r,) = run_easy(srv, "fx-pass", ["go-average"])
+ self.assertEqual(rc, 0)
+ self.assertTrue(r["correct"])
+ self.assertEqual((r["category"], r["status"], r["item_id"]), ("easy/go", "ok", "go-average"))
+ self.assertIn("package solution", r["code_head"])
+ self.assertEqual(r["prompt_tokens"], 100)
+ run = results.RunStore.resume(run_dir("agentic-fix", "fx-pass")).run
+ self.assertEqual(run["item_set"], af.easy_item_set(list(EASY.values())))
+ self.assertEqual(run["args"]["tier"], "easy")
+
+ def test_wrong_and_truncated_answers(self):
+ with MockServer() as srv:
+ srv.script = [chat("```go\n" + EASY["go-average"]["buggy"] + "```"),
+ chat("```go\npackage solution\n\nfunc Average(xs []int) float64 {", finish="length")]
+ _, (a, b) = run_easy(srv, "fx-wrong", ["go-average"], samples=2)
+ self.assertEqual((a["correct"], a["status"]), (False, "ok"))
+ self.assertEqual((b["correct"], b["status"]), (False, "truncated"))
+
+ def test_swift_skipped_without_toolchain(self):
+ saved = runners._SWIFT_SDK
+ runners._SWIFT_SDK = ""
+ try:
+ with MockServer() as srv:
+ srv.default = chat("```swift\nfunc parseAge(_ s: String) -> Int? { return Int(s) }\n```")
+ _, (r,) = run_easy(srv, "fx-swift", ["swift-parseage"])
+ finally:
+ runners._SWIFT_SDK = saved
+ self.assertEqual((r["status"], r["correct"], r["category"]), ("skipped", None, "easy/swift"))
+
+ def test_resume_retries_only_infra(self):
+ with MockServer() as srv:
+ srv.script = [(500, {"error": "x"}), chat("no code at all")]
+ lane_mod.set_current(srv.lane(lane_id="fx-resume"))
+ run_main(af, ["run", "--tier", "easy", "go-average", "--samples", "2"])
+ self.assertEqual([r["status"] for r in rows("fx-resume")], ["http_500", "ok"])
+ srv.default = chat("still no code")
+ run_main(af, ["run", "--tier", "easy", "--resume", run_dir("agentic-fix", "fx-resume")])
+ self.assertEqual(len(srv.requests), 3) # only the infra-failed sample was retried
+
+
+@unittest.skipUnless(shutil.which("go"), "go missing")
+class HardTier(unittest.TestCase):
+ def setUp(self):
+ tools.WORK_ROOT = os.path.join(TMP, "work")
+
+ def test_end_to_end_with_mock(self):
+ fixed = go_kvstore.FIX["store.go"]
+ with MockServer() as srv:
+ srv.script = [
+ chat("", tool_calls=[tool_call("read_file", {"path": "ttl.go"})]),
+ chat("Reading done; submitting."), # prose is nudged
+ chat("", tool_calls=[tool_call("submit_fix", {"path": "/etc/store.go", "content": fixed}, "c0")]),
+ chat("", tool_calls=[tool_call("submit_fix", {"path": "store.go", "content": fixed}, "c1")]),
+ ]
+ d = harness.run_instrument("unit-fix-hard", "fix-hard", [af.hard_task(go_kvstore)],
+ lane=srv.lane(), log=quiet, max_turns=6)
+ first_user = srv.requests[0]["body"]["messages"][1]["content"]
+ third = srv.requests[3]["body"]["messages"]
+ self.assertIn("--- FAIL: TestSetThenGetWithinTTL", first_user)
+ self.assertIn("`go test -v ./...` fails", first_user)
+ self.assertIn("not a file inside the project", third[-1]["content"])
+ (row,) = results.load_rows("unit-fix-hard", "mock")
+ self.assertEqual((row["stop_reason"], row["correct"], row["category"]), ("done", True, "hard/go"))
+ self.assertEqual((row["reads"], row["submitted_path"], row["fixed_file"]), (["ttl.go"], "store.go", True))
+ self.assertEqual(row["turns_used"], 4)
+
+ def test_validate_and_gate(self):
+ with contextlib.redirect_stdout(io.StringIO()):
+ self.assertTrue(harness.run_validate([af.hard_task(go_kvstore)], log=quiet))
+ with tools.Workspace(tempfile.mkdtemp(dir=TMP)) as ws:
+ ok, d = af.score(ws, go_kvstore, "store_test.go", "package kvstore\n")
+ self.assertFalse(ok) # rewriting the test cannot pass: it is restored
+ self.assertIn("TestSetThenGetWithinTTL", d["tests_not_passed"])
+
+
+class Runners(unittest.TestCase):
+ def test_python_sh_sql(self):
+ py = {"id": "t-py", "test": "import solution\nassert solution.f(2) == 4\n"}
+ sh = {"id": "t-sh", "test": '. ./solution.sh\n[ "$(greet "a b")" = "hi a b" ] || exit 1\n'}
+ sql = {"id": "t-sql", "fixture": "create table t(a int); insert into t values (2),(1);", "expect": "1\n2"}
+ self.assertEqual(runners.run_python(py, "def f(x):\n return x * 2\n")[0], True)
+ self.assertEqual(runners.run_python(py, "def f(x):\n return x + 1\n")[0], False)
+ self.assertEqual(runners.run_sh(sh, 'greet() { echo "hi $1"; }\n')[0], True)
+ self.assertEqual(runners.run_sh(sh, 'greet() { echo "hi" $1; }\n')[0], True)
+ self.assertEqual(runners.run_sh(sh, 'greet() { echo "hey $1"; }\n')[0], False)
+ self.assertEqual(runners.run_sql(sql, "select a from t;")[0], True) # unordered: sorted compare
+ self.assertEqual(runners.run_sql(dict(sql, ordered=True), "select a from t;")[0], False)
+ self.assertEqual(runners.run_sql(dict(sql, ordered=True), "select a from t order by a;")[0], True)
+ ok, detail = runners.run_sql(sql, "select nope from t;")
+ self.assertEqual((ok, detail.startswith("SQL ERROR")), (False, True))
+
+ def test_agent_markers_never_reach_graded_tools(self):
+ os.environ["CLAUDECODE"] = "1"
+ try:
+ self.assertEqual(runners._sh(["sh", "-c", "echo ${CLAUDECODE:-unset}"], tempfile.gettempdir())[1], "unset")
+ with tools.Workspace(tempfile.mkdtemp(dir=TMP)) as ws:
+ self.assertEqual(ws.run("echo ${CLAUDECODE:-unset}", 10).out.strip(), "unset")
+ finally:
+ del os.environ["CLAUDECODE"]
+
+ def test_timeout_kills_process_group(self):
+ t0 = time.time()
+ marker = os.path.join(tempfile.mkdtemp(), "alive")
+ cmd = ["sh", "-c", "(sleep 3; touch %s) & sleep 30" % marker] # marker after 3 s unless killed
+ with self.assertRaises(runners.subprocess.TimeoutExpired):
+ runners._sh(cmd, tempfile.gettempdir(), timeout=1)
+ self.assertLess(time.time() - t0, 10)
+ time.sleep(3.5)
+ self.assertFalse(os.path.exists(marker))
+
+ def test_work_dir_layout(self):
+ self.assertEqual(runners.work_dir("RUN1", "go-average", 2), os.path.join(runners.WORK, "RUN1", "go-average-2"))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_loop.py b/tests/test_loop.py
new file mode 100644
index 0000000..6662818
--- /dev/null
+++ b/tests/test_loop.py
@@ -0,0 +1,91 @@
+"""Offline tests for bench/tasks/loop_battery.py (MockServer only)."""
+import os
+import unittest
+
+from _util import run_dir, run_main
+from bench.core import lane as lane_mod, results
+from bench.core.mockserver import MockServer, chat # noqa: E402
+from bench.tasks import loop_battery as lb # noqa: E402
+
+
+class Scoring(unittest.TestCase):
+ def test_ngram_detects_loop(self):
+ loop = ("so the answer is forty two and we check it again " * 30)
+ rep, uniq = lb.rep_score(loop)
+ self.assertGreaterEqual(rep, 25)
+ self.assertLess(uniq, 0.1)
+ varied = " ".join("w%d" % i for i in range(300))
+ self.assertEqual(lb.rep_score(varied)[0], 1)
+ self.assertEqual(lb.rep_score("short text")[0], 0)
+
+ def test_markers(self):
+ n, per = lb.marker_counts("Wait, hmm. Hmm... but wait, actually, no.")
+ self.assertEqual(per["hmm"], 2)
+ self.assertEqual(per["wait"], 2)
+ self.assertEqual(n, sum(per.values()))
+
+ def test_analyze_cap_hit_means_incorrect_even_with_acceptable_answer(self):
+ a = lb.analyze("conflicting-opt", "hmm " * 50, "There is no single best language.", "length")
+ self.assertTrue(a["answer_ok"])
+ self.assertTrue(a["cap_hit"])
+ self.assertFalse(a["correct"])
+ b = lb.analyze("conflicting-opt", "short", "There is no single best language.", "stop")
+ self.assertTrue(b["correct"])
+
+ def test_scanned_content_flag_when_no_reasoning(self):
+ a = lb.analyze("prove-false", "", "wait wait wait", "stop")
+ self.assertTrue(a["scanned_content"])
+ self.assertEqual(a["markers"], 3)
+
+ def test_wordcount_rule(self):
+ self.assertFalse(lb.answer_ok("self-ref-wordcount", "My final answer contains exactly seven words here.")) # 8 words
+ self.assertTrue(lb.answer_ok("self-ref-wordcount", "This answer has 5 words."))
+ self.assertFalse(lb.answer_ok("self-ref-wordcount", "This answer has 12 words."))
+ self.assertTrue(lb.answer_ok("self-ref-wordcount", "This answer has five words."))
+
+ def test_other_rules(self):
+ self.assertTrue(lb.answer_ok("underdetermined-ages", "The ages are 2, 2 and 9."))
+ self.assertTrue(lb.answer_ok("underdetermined-ages", "You never told me the sum, so it is underdetermined."))
+ self.assertFalse(lb.answer_ok("underdetermined-ages", "The ages are 1, 6 and 6."))
+ self.assertTrue(lb.answer_ok("prove-false", "The claim is false: 9 = 3 x 3 is a counterexample."))
+ self.assertFalse(lb.answer_ok("prove-false", "Proof: let n be odd... therefore n is prime. QED"))
+ self.assertTrue(lb.answer_ok("conflicting-opt", "No single language wins on every axis; it depends."))
+ self.assertFalse(lb.answer_ok("conflicting-opt", "Rust."))
+ self.assertTrue(lb.answer_ok("ambiguous-pronoun-math", "The statements contradict each other."))
+ self.assertTrue(lb.answer_ok("ambiguous-pronoun-math", "Each fruit costs $1.40."))
+ self.assertFalse(lb.answer_ok("ambiguous-pronoun-math", "Apples cost $1 and oranges cost $2."))
+
+
+class Run(unittest.TestCase):
+ def test_run_rows_cap_hit_and_loop(self):
+ def reply(body):
+ q = body["messages"][-1]["content"]
+ if q.startswith("What is the single best"):
+ # runaway: hits the cap in a repeating loop
+ return chat("", reasoning="let me double-check that again and again " * 60, finish="length",
+ completion_tokens=16000)
+ return chat("No single option; it depends.", reasoning="short thought", completion_tokens=40)
+
+ with MockServer() as srv:
+ srv.default = reply
+ lane_mod.set_current(srv.lane(lane_id="lb-run"))
+ rc = run_main(lb, ["run", "--samples", "2", "--items", "conflicting-opt,prove-false"])
+ self.assertEqual(rc, 0)
+ rows = results.load_rows("loop-battery", "lb-run")
+ self.assertEqual(len(rows), 4)
+ by = {}
+ for r in rows:
+ by.setdefault(r["category"], []).append(r)
+ runaway = by["loop/conflicting-opt"]
+ self.assertTrue(all(r["cap_hit"] and r["correct"] is False and r["status"] == "truncated" for r in runaway))
+ self.assertTrue(all(r["max_ngram_rep"] > 10 for r in runaway))
+ self.assertTrue(all(r["markers"] > 0 for r in runaway))
+ # prove-false answer lacks a counterexample -> not acceptable, but not a cap hit
+ pf = by["loop/prove-false"]
+ self.assertTrue(all(r["cap_hit"] is False and r["answer_ok"] is False and r["correct"] is False for r in pf))
+ self.assertTrue(os.path.exists(os.path.join(run_dir("loop-battery", "lb-run"),
+ runaway[0]["sidecar"])))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_needle.py b/tests/test_needle.py
new file mode 100644
index 0000000..730978f
--- /dev/null
+++ b/tests/test_needle.py
@@ -0,0 +1,138 @@
+"""Offline tests for bench/tasks/needle.py (MockServer only)."""
+import io
+import re
+import unittest
+from contextlib import redirect_stdout
+
+from _util import run_dir, run_main
+from bench.core import lane as lane_mod, results
+from bench.core.mockserver import MockServer, chat # noqa: E402
+from bench.tasks import needle as nd # noqa: E402
+
+
+class Generator(unittest.TestCase):
+ def test_deterministic(self):
+ for v in nd.VARIANTS:
+ self.assertEqual(nd.build_item(1000, 0.5, 3, v), nd.build_item(1000, 0.5, 3, v))
+ self.assertNotEqual(nd.build_item(1000, 0.5, 0, "plain")["prompt"],
+ nd.build_item(1000, 0.5, 1, "plain")["prompt"])
+
+ def test_item_id_stable_across_depth_order_and_position_subset(self):
+ a = {nd.item_id(*k) for k in nd.grid([1000, 4000, 16000], nd.POSITION_GRID, nd.VARIANTS, 1)}
+ b = {nd.item_id(*k) for k in nd.grid([16000, 1000, 4000], nd.POSITION_GRID[::-1], nd.VARIANTS[::-1], 1)}
+ self.assertEqual(a, b)
+ sub = {nd.item_id(*k) for k in nd.grid([4000], [0.5], ["decoy"], 1)}
+ self.assertTrue(sub <= a)
+ self.assertEqual(len(a), 3 * 5 * 3) # no collisions
+ # id does not depend on the chars-per-token estimate
+ self.assertEqual(nd.build_item(1000, 0.5, 0, "plain", cpt=3.0)["item_id"],
+ nd.build_item(1000, 0.5, 0, "plain", cpt=5.0)["item_id"])
+
+ def test_decoy_same_place_and_both_codes_present(self):
+ for seed in range(6):
+ it = nd.build_item(4000, 0.5, seed, "decoy")
+ p = it["prompt"]
+ old = it["others"][0]
+ cur_s = [m for m in re.findall(r"[^\n]*Maintenance note[^\n]*", p) if it["gold"] in m][0]
+ old_s = [m for m in re.findall(r"[^\n]*Maintenance note[^\n]*", p) if old in m][0]
+ self.assertIn("for the %s " % it["place"], cur_s)
+ self.assertIn("for the %s " % it["place"], old_s)
+ self.assertIn("rotated out", old_s)
+ self.assertNotIn("rotated", cur_s)
+ self.assertIn("CURRENT", p.split("QUESTION:")[1])
+ self.assertEqual(sorted(nd.CODE_RE.findall(p)), sorted([it["gold"], old]))
+ orders = {nd.build_item(4000, 0.5, s, "decoy")["decoy_order"] for s in range(12)}
+ self.assertEqual(orders, {"old_first", "old_last"})
+
+ def test_multikey_has_k_keys_and_asks_one(self):
+ it = nd.build_item(4000, 0.7, 0, "multikey")
+ codes = nd.CODE_RE.findall(it["prompt"])
+ self.assertEqual(len(codes), nd.MULTIKEY_K)
+ self.assertGreaterEqual(nd.MULTIKEY_K, 4)
+ self.assertIn(it["gold"], codes)
+ self.assertEqual(len(it["others"]), nd.MULTIKEY_K - 1)
+ self.assertEqual(it["prompt"].count(it["place"]), 2) # the key line + the question
+
+ def test_filler_has_no_code_like_tokens_and_size_tracks_depth(self):
+ it = nd.build_item(16000, 0.5, 0, "plain")
+ self.assertEqual(nd.CODE_RE.findall(it["prompt"]), [it["gold"]])
+ self.assertAlmostEqual(it["est_tokens"], 16000, delta=800)
+
+ def test_validate_passes(self):
+ with redirect_stdout(io.StringIO()):
+ self.assertTrue(nd.validate())
+
+
+class Scoring(unittest.TestCase):
+ def test_rejects_answer_listing_both_codes(self):
+ self.assertTrue(nd.score_answer("EMERALD-1111", "EMERALD-1111", ["COPPER-2222"])["correct"])
+ self.assertFalse(nd.score_answer("EMERALD-1111 or COPPER-2222", "EMERALD-1111", ["COPPER-2222"])["correct"])
+ self.assertFalse(nd.score_answer("COPPER-2222", "EMERALD-1111", ["COPPER-2222"])["correct"])
+ self.assertFalse(nd.score_answer("", "EMERALD-1111", [])["correct"])
+ # a longer number is a different token, not a substring hit
+ self.assertFalse(nd.score_answer("EMERALD-11112", "EMERALD-1111", [])["correct"])
+
+
+def run_nd(srv, lane_id, argv, **lane_kw):
+ lane_mod.set_current(srv.lane(lane_id=lane_id, **lane_kw))
+ rc = run_main(nd, ["run"] + argv)
+ return rc, sorted(results.load_rows("needle", lane_id), key=lambda r: r["item_id"])
+
+
+class Run(unittest.TestCase):
+ def test_correct_wrong_and_decoy_rows_and_cache_override(self):
+ def answer(body):
+ q = body["messages"][-1]["content"]
+ # mock model: always returns the FIRST code in the document (the old one when old_first)
+ return chat(nd.CODE_RE.findall(q)[0], prompt_tokens=4100, completion_tokens=6,
+ timings={"prompt_per_second": 900.0, "cache_n": 0})
+
+ with MockServer() as srv:
+ srv.default = answer
+ rc, rows = run_nd(srv, "nd-run", ["--depths", "1000", "--positions", "0.5", "--seeds", "4",
+ "--variants", "decoy"])
+ self.assertEqual(rc, 0)
+ self.assertEqual(len(srv.requests), 4)
+ self.assertTrue(all(q["body"].get("cache_prompt") is False for q in srv.requests))
+ self.assertEqual(len(rows), 4)
+ for r in rows:
+ first_is_old = r["decoy_order"] == "old_first"
+ self.assertEqual(r["correct"], not first_is_old, r["decoy_order"])
+ self.assertEqual(r["category"], "needle/1k/decoy")
+ self.assertEqual(r["prompt_tokens"], 4100)
+ self.assertIn("cached_tokens", r)
+ self.assertTrue(r["cache_prompt_off"])
+
+ def test_no_cache_override_for_non_llama_lane(self):
+ with MockServer() as srv:
+ srv.default = chat("nothing", prompt_tokens=1000)
+ run_nd(srv, "nd-or", ["--depths", "1000", "--positions", "0.5", "--variants", "plain"],
+ snapshot="none")
+ self.assertNotIn("cache_prompt", srv.requests[0]["body"])
+
+ def test_cached_rows_excluded_from_speed(self):
+ rows = [{"category": "needle/1k/plain", "status": "ok", "correct": True, "prompt_tokens": 1000,
+ "prefill_ps": 500.0, "cached_prefill": False},
+ {"category": "needle/1k/plain", "status": "ok", "correct": True, "prompt_tokens": 1000,
+ "prefill_ps": 9000.0, "cached_prefill": True}]
+ s = results.summarize(rows, nd.SUMMARY)["by_category"]["needle/1k/plain"]
+ self.assertEqual(s["mean_prefill_ps_uncached"], 500.0)
+ self.assertEqual(s["n_uncached_speed_rows"], 1)
+
+ def test_resume_restores_args_from_run_json(self):
+ args = ["--depths", "1000", "--positions", "0.5", "--variants", "plain", "--seeds", "2"]
+ with MockServer() as srv:
+ srv.script = [(500, {"error": "boom"})]
+ srv.default = chat("nothing")
+ run_nd(srv, "nd-resume", args)
+ srv.requests.clear()
+ # CLI defaults differ (all depths/positions/variants, 1 seed): run.json must win
+ self.assertEqual(run_main(nd, ["run", "--resume", run_dir("needle", "nd-resume")]), 0)
+ self.assertEqual(len(srv.requests), 1) # only the infra-failed attempt
+ rows = results.load_rows("needle", "nd-resume")
+ self.assertEqual(sorted(r["seed"] for r in rows), [0, 1])
+ self.assertEqual({r["status"] for r in rows}, {"ok"})
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_oracle.py b/tests/test_oracle.py
new file mode 100644
index 0000000..9fc2c12
--- /dev/null
+++ b/tests/test_oracle.py
@@ -0,0 +1,113 @@
+"""Tests for bench.tasks.oracle."""
+import json
+import os
+import unittest
+
+from _util import TMP
+from test_report import R, make_run, uniq
+from bench.tasks import oracle, report
+
+ORDER = ["lane-a", "lane-b", "lane-c"]
+
+
+class Oracle(unittest.TestCase):
+ def labels(self, inst, **kw):
+ data = report.collect({inst})
+ rows, warns = oracle.derive(data, ORDER, **kw)
+ return {r["item_id"]: r for r in rows}, warns
+
+ def test_labels_order_and_ctx_overflow(self):
+ inst = uniq("or")
+ make_run(inst, "lane-a", [
+ R("easy", True), R("mid", False), R("long", None, status="ctx_overflow"),
+ R("flaky", None, status="timeout")])
+ make_run(inst, "lane-b", [
+ R("easy", True), R("mid", True), R("long", True), R("flaky", True), R("hard", False)])
+ make_run(inst, "lane-c", [
+ R("easy", True), R("mid", True), R("long", True), R("flaky", False), R("hard", False)])
+ rows, _ = self.labels(inst, theta=0.67)
+ self.assertEqual(rows["easy"]["label"], "lane-a")
+ self.assertEqual(rows["easy"]["difficulty"], 3)
+ self.assertEqual(rows["mid"]["label"], "lane-b")
+ self.assertEqual(rows["long"]["pass_rate"]["lane-a"], 0.0) # ctx_overflow -> infeasible
+ self.assertEqual(rows["long"]["label"], "lane-b")
+ self.assertIsNone(rows["flaky"]["pass_rate"]["lane-a"]) # other infra -> unknown
+ self.assertIn("lane-a", rows["flaky"]["unknown_lanes"])
+ self.assertEqual(rows["flaky"]["label"], "lane-b")
+ self.assertEqual(rows["hard"]["label"], "none")
+ self.assertEqual(rows["hard"]["difficulty"], 0)
+
+ def test_theta_with_samples(self):
+ inst = uniq("th")
+ make_run(inst, "lane-a", [R("x", True, sample=0), R("x", False, sample=1), R("x", True, sample=2)])
+ make_run(inst, "lane-c", [R("x", True)])
+ r, _ = self.labels(inst, theta=0.67)
+ self.assertAlmostEqual(r["x"]["pass_rate"]["lane-a"], 2 / 3)
+ self.assertEqual(r["x"]["label"], "lane-c") # 0.667 < 0.67
+ r, _ = self.labels(inst, theta=0.6)
+ self.assertEqual(r["x"]["label"], "lane-a")
+
+ def test_lambda_picks_by_measured_cost(self):
+ inst = uniq("lam")
+ make_run(inst, "lane-a", [R("x", True, wall_s=100, cost_usd=0.0)])
+ make_run(inst, "lane-b", [R("x", True, wall_s=10, cost_usd=0.0)])
+ r, _ = self.labels(inst)
+ self.assertEqual(r["x"]["label"], "lane-a") # by order
+ r, _ = self.labels(inst, lambda_usd=1.0)
+ self.assertEqual(r["x"]["label"], "lane-b") # faster wins
+
+ def test_item_set_mismatch_warns(self):
+ inst = uniq("ois")
+ make_run(inst, "lane-a", [R("x", True)], item_set="s@1")
+ make_run(inst, "lane-b", [R("x", True)], item_set="s@1")
+ make_run(inst, "lane-c", [R("x", False)], item_set="s@2")
+ r, warns = self.labels(inst)
+ self.assertTrue(any("s@2" in w for w in warns))
+ self.assertIsNone(r["x"]["pass_rate"]["lane-c"]) # wrong item_set -> not used
+ self.assertEqual(r["x"]["item_set"], "s@1")
+
+ def test_differently_named_sets_all_labelled(self):
+ # reasoning stores one run per suite (aime26@.., musr@..); every suite must yield labels,
+ # and a shared item id in two suites stays two items
+ inst = uniq("osn")
+ for lane, ok in (("lane-a", False), ("lane-c", True)):
+ make_run(inst, lane, [R("q1", ok, cat="aime")], item_set="aime26@a.p1")
+ make_run(inst, lane, [R("q1", True, cat="musr/x"), R("q2", ok, cat="musr/x")],
+ item_set="musr@b.p1")
+ rows, warns = oracle.derive(report.collect({inst}), ORDER)
+ self.assertEqual(warns, [])
+ got = sorted((r["item_set"], r["item_id"], r["label"]) for r in rows)
+ self.assertEqual(got, [("aime26@a.p1", "q1", "lane-c"), ("musr@b.p1", "q1", "lane-a"),
+ ("musr@b.p1", "q2", "lane-c")])
+
+ def test_cascade_arithmetic_hand_computed(self):
+ # lane a: p=.5, 10s, $0.1 ; lane b: p=1, 20s, $1.0
+ row = {"pass_rate": {"a": 0.5, "b": 1.0}, "feasible": ["b"],
+ "median_wall_s": {"a": 10.0, "b": 20.0}, "mean_cost_usd": {"a": 0.1, "b": 1.0}}
+ s, lat, cost = oracle.cascade_eval([row], ["a", "b"])
+ self.assertAlmostEqual(s, 1.0)
+ self.assertAlmostEqual(lat, 10 + 0.5 * 20)
+ self.assertAlmostEqual(cost, 0.1 + 0.5 * 1.0)
+ sim = oracle.simulate([row, dict(row, pass_rate={"a": 1.0, "b": 1.0}, feasible=["a", "b"])],
+ order=["a", "b"])
+ pol = {p["policy"]: p for p in sim["policies"]}
+ self.assertAlmostEqual(pol["always-a"]["success"], 0.75)
+ self.assertAlmostEqual(pol["oracle"]["success"], 1.0)
+ self.assertAlmostEqual(pol["oracle"]["cost_usd"], 1.0 + 0.1) # item1 -> b, item2 -> a
+ casc = [p for p in sim["policies"] if p["policy"].startswith("cascade")][0]
+ self.assertAlmostEqual(casc["success"], 1.0)
+ self.assertAlmostEqual(casc["cost_usd"], (0.1 + 0.5) + 0.1)
+ self.assertAlmostEqual(casc["latency_s"], (20 + 10) / 2)
+
+ def test_cli_writes_jsonl_and_simulates(self):
+ inst = uniq("ocli")
+ make_run(inst, "lane-a", [R("x", True, wall_s=5), R("y", False, wall_s=5)])
+ make_run(inst, "lane-c", [R("x", True, wall_s=50), R("y", True, wall_s=50)])
+ out = os.path.join(TMP, inst + ".jsonl")
+ oracle.main(["--instruments", inst, "--out", out, "--simulate", "--order", ",".join(ORDER)])
+ lines = [json.loads(l) for l in open(out)]
+ self.assertEqual({l["item_id"]: l["label"] for l in lines}, {"x": "lane-a", "y": "lane-c"})
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_reasoning.py b/tests/test_reasoning.py
new file mode 100644
index 0000000..4d6abb0
--- /dev/null
+++ b/tests/test_reasoning.py
@@ -0,0 +1,167 @@
+"""Offline tests for bench.tasks.reasoning. Run: python3 -m unittest discover -s tests"""
+import gzip
+import json
+import os
+import tempfile
+import unittest
+
+import _util # noqa: F401
+from bench.core import results
+from bench.core.mockserver import MockServer, chat # noqa: E402
+from bench.tasks import reasoning as R # noqa: E402
+
+
+class LetterExtraction(unittest.TestCase):
+ def test_cases(self):
+ f = R.extract_letter
+ self.assertEqual(f("blah\nANSWER: C"), "C")
+ self.assertEqual(f("ANSWER: (C)"), "C")
+ self.assertEqual(f("ANSWER:(J)"), "J")
+ self.assertEqual(f("answer: c"), "C")
+ self.assertEqual(f("**ANSWER: B**"), "B")
+ self.assertEqual(f("ANSWER: A\nmore\nANSWER: D"), "D") # last wins
+ self.assertEqual(f("ANSWER: B\n\n(D)\n"), "B") # explicit ANSWER beats a stray lone letter
+ self.assertIsNone(f("I could not decide."))
+ self.assertIsNone(f(""))
+ self.assertIsNone(f("The reasoning is long and gets cut off in the mid")) # truncated
+ self.assertEqual(f("so the answer is\nc"), "C") # lone-letter fallback
+ self.assertIsNone(f("ANSWER: a long story about it")) # lowercase word, not a letter
+ self.assertIsNone(f("ANSWER: K")) # out of A-J
+
+ def test_grade(self):
+ item = {"item_id": "mmlu-pro-cs/1", "answer_index": 8}
+ self.assertTrue(R.grade(item, "ANSWER: I")["correct"])
+ self.assertEqual(R.grade(item, "ANSWER: I")["gold"], "I")
+ self.assertFalse(R.grade(item, "nothing")["correct"])
+
+
+def fake_rows():
+ """Fixed fake raw rows for selection tests."""
+ return {"test": [{"question_id": i, "question": f"q{i}", "options": ["a", "b"],
+ "answer": "A", "answer_index": 0, "category": "computer science" if i % 2 else "law",
+ "src": "s"} for i in range(40)]}
+
+
+class Selection(unittest.TestCase):
+ def setUp(self):
+ self._n, R.MMLU_CS_N = R.MMLU_CS_N, 3
+
+ def tearDown(self):
+ R.MMLU_CS_N = self._n
+
+ def test_deterministic_hash_ordered_cs_only(self):
+ a = R.build_items("mmlu-pro-cs", fake_rows())
+ rows = fake_rows()
+ rows["test"].reverse()
+ b = R.build_items("mmlu-pro-cs", rows)
+ self.assertEqual(sorted(i["item_id"] for i in a), sorted(i["item_id"] for i in b))
+ self.assertEqual({i["category"] for i in a}, {"cs"})
+ want = sorted((str(i) for i in range(40) if i % 2), key=lambda n: R.sel_key("mmlu-pro-cs", n))[:3]
+ self.assertEqual(sorted(i["native_id"] for i in a), sorted(want))
+ with self.assertRaises(ValueError):
+ R.build_items("aime26", fake_rows())
+
+ def test_manifest_and_validate(self):
+ old = (R.DATA_DIR, R.CACHE_DIR)
+ R.DATA_DIR = tempfile.mkdtemp()
+ R.CACHE_DIR = os.path.join(R.DATA_DIR, "cache")
+ try:
+ items = R.build_items("mmlu-pro-cs", fake_rows())
+ m = R.write_set("mmlu-pro-cs", items)
+ self.assertEqual(m["n"], 3)
+ self.assertEqual(m["items"][0]["sha256"], R.item_sha(items[0]))
+ loaded, m2 = R.load_items("mmlu-pro-cs")
+ self.assertEqual(len(loaded), 3)
+ self.assertEqual(R.cmd_validate(["mmlu-pro-cs"]), 0)
+ # tamper
+ p = os.path.join(R.CACHE_DIR, "mmlu-pro-cs.jsonl")
+ with open(p) as fh:
+ lines = fh.read().splitlines()
+ d = json.loads(lines[0])
+ d["question"] = "changed"
+ lines[0] = json.dumps(d)
+ with open(p, "w") as fh:
+ fh.write("\n".join(lines) + "\n")
+ with self.assertRaises(ValueError):
+ R.load_items("mmlu-pro-cs")
+ self.assertEqual(R.cmd_validate(["mmlu-pro-cs"]), 1)
+ finally:
+ R.DATA_DIR, R.CACHE_DIR = old
+
+
+ITEMS = [
+ {"item_id": "mmlu-pro-cs/1", "native_id": "1", "category": "cs", "question": "q1",
+ "options": ["x", "y", "z"], "answer": "B", "answer_index": 1},
+ {"item_id": "mmlu-pro-cs/2", "native_id": "2", "category": "cs", "question": "q2",
+ "options": ["x", "y", "z"], "answer": "C", "answer_index": 2},
+ {"item_id": "mmlu-pro-cs/3", "native_id": "3", "category": "cs", "question": "q3",
+ "options": ["x", "y", "z"], "answer": "A", "answer_index": 0},
+]
+MANIFEST = {"manifest_hash": "abc123def456"}
+
+
+class EndToEnd(unittest.TestCase):
+ def test_run_http500_and_resume(self):
+ def responder(body):
+ q = body["messages"][-1]["content"]
+ if q.startswith("q1"):
+ return (500, {"error": "template raised"})
+ if q.startswith("q2"):
+ return chat("hmm\nANSWER: C", reasoning="thinking " * 100)
+ return chat("it is probably ANSWER: B", finish="length", reasoning="r")
+ with MockServer() as srv:
+ srv.default = responder
+ lane = srv.lane(lane_id="reasoning-e2e", max_concurrency=2)
+ store, summary = R.run_set("mmlu-pro-cs-test", ITEMS, MANIFEST, lane=lane, samples=2,
+ concurrency=4, keep_reasoning=True)
+ self.assertEqual(len(srv.requests), 6)
+ rows = [json.loads(l) for l in open(store.items_path)]
+ self.assertEqual(len(rows), 6)
+ by = {}
+ for r in rows:
+ by.setdefault(r["item_id"], []).append(r)
+ self.assertTrue(all(r["status"] == "http_500" and r["correct"] is None for r in by["mmlu-pro-cs/1"]))
+ q2 = by["mmlu-pro-cs/2"][0]
+ self.assertTrue(q2["correct"])
+ self.assertEqual((q2["extracted"], q2["gold"]), ("C", "C"))
+ self.assertEqual(len(q2["reasoning_head"]), 400)
+ self.assertTrue(os.path.exists(os.path.join(store.dir, q2["reasoning_file"])))
+ with gzip.open(os.path.join(store.dir, q2["reasoning_file"]), "rt") as f:
+ self.assertTrue(f.read().startswith("thinking"))
+ a = by["mmlu-pro-cs/3"][0]
+ self.assertEqual(a["status"], "truncated")
+ self.assertIs(a["correct"], False) # B != A, still graded
+ self.assertIn("ANSWER", a["content_tail"])
+ cat = summary["by_category"]["cs"]
+ self.assertEqual((cat["infra"], cat["graded"], cat["truncated"]), (2, 4, 2))
+ self.assertIsNone(summary["stopped"])
+ # resume: only the two http_500 attempts re-run
+ srv.requests.clear()
+ srv.default = lambda body: chat("ANSWER: B")
+ store2, summary2 = R.run_set("mmlu-pro-cs-test", ITEMS, MANIFEST, lane=lane, samples=2,
+ concurrency=2, resume_dir=store.dir)
+ self.assertEqual(len(srv.requests), 2)
+ self.assertEqual(store2.run_id, store.run_id)
+ rows = [json.loads(l) for l in open(store.items_path)]
+ ok = [r for r in rows if r["item_id"] == "mmlu-pro-cs/1" and r["status"] == "ok"]
+ self.assertEqual(len(ok), 2)
+ self.assertTrue(all(r["correct"] for r in ok))
+ # the summary counts each (item, sample) once: retried rows replace the http_500s
+ cs = summary2["by_category"]["cs"]
+ self.assertEqual((cs["n"], cs["graded"], cs["infra"]), (6, 6, 0))
+
+ def test_budget_stop(self):
+ cost = {"ledger": "reasoning-unittest-cap", "cap_usd": 0.001, "in_per_m": 1.0, "out_per_m": 10.0}
+ with MockServer() as srv:
+ srv.default = chat("ANSWER: B", cost=0.0005)
+ lane = srv.lane(lane_id="reasoning-budget", cost=cost, request={"max_tokens": 5000})
+ store, summary = R.run_set("mmlu-pro-cs-test", ITEMS[:2], MANIFEST, lane=lane, samples=1,
+ concurrency=1)
+ self.assertEqual(summary["stopped"], "budget_stop")
+ self.assertEqual(len(results.load_rows(INSTR, "reasoning-budget")), 0) # incomplete
+
+
+INSTR = "reasoning"
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_report.py b/tests/test_report.py
new file mode 100644
index 0000000..2b7c22b
--- /dev/null
+++ b/tests/test_report.py
@@ -0,0 +1,216 @@
+"""Tests for bench.tasks.report using synthetic rows written through results.RunStore."""
+import csv
+import io
+import json
+import os
+import unittest
+import uuid
+from contextlib import redirect_stdout
+
+from _util import TMP as _TMP
+from bench.core import results
+from bench.core.lane import Lane # noqa: E402
+from bench.tasks import report # noqa: E402
+
+
+def mklane(lane_id, **kw):
+ raw = {"lane_id": lane_id, "endpoint": "http://x/v1/chat/completions", "model": "m",
+ "weights": {"quant": "Q4"}, "runtime": {"engine": "llama.cpp", "build": "abc"},
+ "context": {"n_ctx": 4096}}
+ raw.update(kw)
+ return Lane(raw, "test")
+
+
+def uniq(prefix):
+ return f"{prefix}-{uuid.uuid4().hex[:6]}"
+
+
+def make_run(inst, lane_id, rows, item_set="set@1", complete=True, **lane_kw):
+ """rows: list of dicts for store.add (item_id, correct, category, status, ...)."""
+ st = results.RunStore(inst, item_set=item_set, lane=mklane(lane_id, **lane_kw))
+ for r in rows:
+ st.add(**r)
+ st.finish({}, complete=complete)
+ return st
+
+
+def R(item, correct, cat="go", sample=0, **kw):
+ return dict(item_id=item, sample_idx=sample, category=cat, correct=correct, **kw)
+
+
+class Report(unittest.TestCase):
+ def collect(self, inst, **kw):
+ return report.collect({inst}, **kw)
+
+ def test_resume_dedupe_keeps_last_non_infra(self):
+ inst = uniq("dd")
+ st = results.RunStore(inst, item_set="s@1", lane=mklane("A"))
+ st.add(**R("i1", None, status="timeout"))
+ st.add(**R("i1", True, status="ok")) # resumed, graded
+ st.add(**R("i2", False, status="ok"))
+ st.add(**R("i2", None, status="timeout")) # later infra must not replace the grade
+ st.add(**R("i3", None, status="timeout"))
+ st.add(**R("i3", None, status="oom")) # all infra: last row kept, still ungraded
+ st.finish({})
+ g = self.collect(inst).groups[("A", inst, "s@1")]
+ self.assertEqual(len(g["rows"]), 3)
+ self.assertEqual(g["items"]["i1"]["value"], 1.0)
+ self.assertEqual(g["items"]["i2"]["value"], 0.0)
+ self.assertIsNone(g["items"]["i3"]["value"])
+
+ def test_pooling_across_runs_and_incomplete_skipped(self):
+ inst = uniq("pool")
+ make_run(inst, "A", [R("i1", True), R("i2", False)])
+ make_run(inst, "A", [R("i1", False), R("i2", False)])
+ make_run(inst, "A", [R("i1", False)], complete=False)
+ d = self.collect(inst)
+ g = d.groups[("A", inst, "set@1")]
+ self.assertEqual(len(g["runs"]), 2)
+ self.assertAlmostEqual(g["items"]["i1"]["value"], 0.5)
+ self.assertEqual(g["items"]["i1"]["n_graded"], 2)
+ d2 = self.collect(inst, include_incomplete=True)
+ self.assertEqual(d2.groups[("A", inst, "set@1")]["items"]["i1"]["n_graded"], 3)
+
+ def test_item_set_mismatch_not_pooled_and_warned(self):
+ inst = uniq("is")
+ make_run(inst, "A", [R("i1", True)], item_set="s@1")
+ make_run(inst, "A", [R("i1", False)], item_set="s@2")
+ d = self.collect(inst)
+ self.assertEqual(len(d.groups), 2)
+ self.assertTrue(any("item_set" in w for w in d.warnings))
+ prof = report.profile(d)
+ self.assertEqual(sorted(prof["cols"]), ["A[s@1]", "A[s@2]"])
+
+ def test_differently_named_sets_share_column_and_pair(self):
+ inst = uniq("sn")
+ for lane, ok in (("ref", True), ("B", False)):
+ make_run(inst, lane, [R("a1", ok, cat="aime")], item_set="aime26@x.p1")
+ make_run(inst, lane, [R("m1", ok, cat="musr/m")], item_set="musr@y.p1")
+ d = self.collect(inst)
+ self.assertEqual(d.warnings, [])
+ prof = report.profile(d, ref="ref", n_boot=50)
+ self.assertEqual(prof["cols"], ["B", "ref"])
+ for cat in ("aime", "musr/m"):
+ self.assertEqual(prof["deltas"][(inst, cat)]["B"]["n"], 1)
+
+ def test_category_shared_by_two_set_names_kept_apart(self):
+ inst = uniq("sc2")
+ make_run(inst, "A", [R("i1", True)], item_set="s@1")
+ make_run(inst, "A", [R("i2", False)], item_set="t@1")
+ d = self.collect(inst)
+ self.assertTrue(any("category" in w for w in d.warnings))
+ self.assertEqual(sorted(report.profile(d)["cols"]), ["A[s@1]", "A[t@1]"])
+
+ def test_stripped_output_is_infra_on_write_and_on_read(self):
+ inst = uniq("st")
+ st = results.RunStore(inst, item_set="s@1", lane=mklane("A"))
+ # write path: 29 answer tokens generated, none returned -> stripped, never a grade
+ st.add(**R("w", False, cat="tool-call", status="empty", completion_tokens=76, reasoning_tokens=47))
+ # stays empty: llama-server doesn't report reasoning tokens / only end-of-turn tokens
+ st.add(**R("n", False, cat="tool-call", status="empty", completion_tokens=76, reasoning_tokens=None))
+ st.add(**R("e", False, cat="tool-call", status="empty", completion_tokens=50, reasoning_tokens=45))
+ with open(st.items_path, "a") as f: # a row stored before the rule existed
+ f.write(json.dumps({"run_id": st.run_id, "lane_id": "A", "instrument": inst, "item_id": "old",
+ "sample_idx": 0, "category": "tool-call", "correct": False,
+ "status": "empty", "completion_tokens": 76, "reasoning_tokens": 47}) + "\n")
+ st.finish({})
+ with open(st.items_path) as f:
+ written = {r["item_id"]: r for r in map(json.loads, f)}
+ self.assertEqual((written["w"]["status"], written["w"]["correct"]), ("stripped", None))
+ self.assertEqual(written["n"]["status"], "empty")
+ self.assertEqual(written["e"]["status"], "empty")
+ d = self.collect(inst)
+ items = d.groups[("A", inst, "s@1")]["items"]
+ self.assertIsNone(items["w"]["value"])
+ self.assertIsNone(items["old"]["value"])
+ self.assertEqual((items["n"]["value"], items["e"]["value"]), (0.0, 0.0))
+ self.assertEqual(report.status_table(d)["A"]["infra"]["stripped"], 2)
+
+ def test_score_preferred_and_truncated_graded(self):
+ inst = uniq("sc")
+ make_run(inst, "A", [R("i1", False, cat="zebra", score=0.75),
+ R("i2", False, cat="zebra", status="truncated"),
+ R("i3", None, cat="zebra", status="ctx_overflow")])
+ d = self.collect(inst)
+ items = d.groups[("A", inst, "set@1")]["items"]
+ self.assertEqual(items["i1"]["value"], 0.75)
+ self.assertEqual(items["i2"]["value"], 0.0)
+ self.assertIsNone(items["i3"]["value"])
+ st = report.status_table(d)["A"]
+ self.assertEqual((st["n"], st["truncated"], st["ctx_overflow"]), (3, 1, 1))
+
+ def test_delta_on_intersection_only_and_marker(self):
+ inst = uniq("dl")
+ ids = [f"i{k}" for k in range(12)]
+ make_run(inst, "ref", [R(i, True) for i in ids] + [R("refonly", True)])
+ make_run(inst, "B", [R(i, False) for i in ids] + [R("bonly", False)])
+ prof = report.profile(self.collect(inst), ref="ref", n_boot=200)
+ d = prof["deltas"][(inst, "go")]["B"]
+ self.assertEqual(d["n"], 12)
+ self.assertAlmostEqual(d["mean_delta"], -1.0)
+ self.assertTrue(d["sig"])
+ self.assertAlmostEqual(d["mcnemar_p"], 2 * 1 / 4096) # b=0,c=12 -> 2*(1/4096)
+ self.assertEqual(prof["cells"][(inst, "go")]["B"]["n_items"], 13)
+
+ def test_delta_skipped_when_item_set_differs(self):
+ inst = uniq("sk")
+ make_run(inst, "ref", [R("i1", True)], item_set="s@1")
+ make_run(inst, "B", [R("i1", False)], item_set="s@2")
+ prof = report.profile(self.collect(inst), ref="ref")
+ self.assertIn("skipped", prof["deltas"][(inst, "go")]["B"])
+
+ def test_speed_prefill_excludes_cached_and_none_aware(self):
+ inst = uniq("sp")
+ make_run(inst, "A", [
+ R("a", True, wall_s=10, decode_ps=20, prefill_ps=100, prompt_tokens=1000, cached_tokens=0,
+ completion_tokens=100, reasoning_tokens=40, cost_usd=0.5),
+ R("b", True, wall_s=30, decode_ps=40, prefill_ps=9999, prompt_tokens=1000, cached_tokens=900,
+ completion_tokens=300, reasoning_tokens=None, cost_usd=None),
+ R("c", None, status="timeout", wall_s=999, cost_usd=0.25)])
+ sp = report.speed_table(self.collect(inst))["A"]
+ self.assertEqual(sp["wall_s_median"], 20)
+ self.assertEqual(sp["prefill_ps_median"], 100)
+ self.assertEqual(sp["decode_ps_median"], 30)
+ self.assertEqual(sp["completion_tokens_mean"], 200)
+ self.assertEqual(sp["reasoning_tokens_mean"], 40)
+ self.assertAlmostEqual(sp["cost_usd"], 0.75)
+
+ def test_conformance_is_preflight_not_profile(self):
+ a, b, inst = uniq("pfA"), uniq("pfB"), uniq("pf")
+ older = make_run("conformance", a, [R("basic_reply", True, cat="conformance", verdict="PASS"),
+ R("tc-xml", False, cat="conformance", verdict="FAIL")])
+ older.run["started_at"] = "2000-01-01T00:00:00"
+ older._write_run()
+ make_run("conformance", a, [R("basic_reply", True, cat="conformance", verdict="PASS"),
+ R("tc-select", None, cat="conformance", verdict="WARN")])
+ make_run("conformance", b, [R("basic_reply", True, cat="conformance", verdict="PASS")])
+ make_run(inst, a, [R("i1", True)])
+ d = report.collect({inst, "conformance"}, lanes={a, b})
+ self.assertEqual(set(d.groups), {(a, inst, "set@1")})
+ self.assertEqual(report.preflight_table(d)[a]["checks"], {"basic_reply": "PASS", "tc-select": "WARN"})
+ md = report.render_markdown(d, report.profile(d, "claude-opus"), "claude-opus", {}, {}, [])
+ self.assertIn("| 1 | 1 | 0 | tc-select (WARN) |", md)
+ self.assertIn("No category has runs of both `claude-opus` and another lane.", md)
+
+ def test_cli_outputs(self):
+ inst = uniq("cli")
+ make_run(inst, "claude-opus", [R("i1", True), R("i2", True, cat="rust")])
+ make_run(inst, "B", [R("i1", False), R("i2", True, cat="rust")])
+ out = os.path.join(_TMP, inst)
+ buf = io.StringIO()
+ with redirect_stdout(buf):
+ report.main(["--instruments", inst, "--out", out + ".md", "--json", out + ".json",
+ "--csv", out + ".csv"])
+ self.assertIn("Capability profile", buf.getvalue())
+ md = open(out + ".md").read()
+ self.assertIn("| go |", md)
+ self.assertIn("Delta vs `claude-opus`", md)
+ js = json.load(open(out + ".json"))
+ self.assertEqual(sorted(js["columns"]), ["B", "claude-opus"])
+ rows = list(csv.DictReader(open(out + ".csv")))
+ self.assertEqual(len(rows), 4)
+ self.assertEqual(set(rows[0]), {"lane", "instrument", "category", "item_id", "value", "n_samples"})
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_router.py b/tests/test_router.py
new file mode 100644
index 0000000..e57f872
--- /dev/null
+++ b/tests/test_router.py
@@ -0,0 +1,128 @@
+"""Offline tests for bench/tasks/router.py scoring."""
+import unittest
+
+import _util # noqa: F401
+from bench.core.mockserver import chat
+from bench.tasks import router
+
+ITEMS = {it["id"]: it for it in router.ROUTE + router.ORCH}
+
+
+def step(n, kind, worker, deps=()):
+ return '{"step": %d, "kind": "%s", "worker": "%s", "depends_on": %s}' % (n, kind, worker, list(deps))
+
+
+class Scoring(unittest.TestCase):
+ def test_score_route(self):
+ keys = ("format_ok", "target", "exact", "acceptable", "priv_violation", "esc_err")
+ cases = [ # item, answer, expected (format_ok, target, exact, acceptable, priv, esc)
+ ("r-greet", '{"target": "local_small", "reason": "x", "confidence": 0.9}',
+ (True, "local_small", True, True, False, 0)),
+ ("r-greet", '{"target": "cloud_claude"}', (True, "cloud_claude", False, False, False, 9)),
+ ("r-priv-secret", '{"target": "cloud_claude"}', (True, "cloud_claude", False, False, True, 7)),
+ ("r-amb-vague", '{"target": "local_small"}', (True, "local_small", False, False, False, 0)),
+ ("r-greet", "I would pick local_small", (False, None, False, False, None, None)),
+ ("r-greet", '{"target": "gpt5"}', (False, "gpt5", False, False, False, 0)),
+ ("r-greet", 'Sure. <think>{"target": "cloud_claude"}</think> {"target": "local_small"}',
+ (True, "local_small", True, True, False, 0)),
+ ("r-greet", '{"reason": "x"} {"target": "local_small"}', (False, None, False, False, None, None)),
+ ("r-code-fn", '```json\n{"target": "local_large"}\n```', (True, "local_large", True, True, False, 0)),
+ ("r-greet", '{ oops {"target": "local_small"}', (False, None, False, False, None, None)),
+ ("r-greet", '{"target": "local_small", "reason": "a } in a string"}',
+ (True, "local_small", True, True, False, 0)),
+ ]
+ for item, answer, want in cases:
+ with self.subTest(item=item, answer=answer):
+ rec = router.score_route(ITEMS[item], chat(answer))
+ self.assertEqual(tuple(rec.get(k) for k in keys), want)
+
+ def test_score_orch(self):
+ keys = ("format_ok", "coverage", "assign_ok", "ordering_ok", "priv_violation", "passed")
+ good = [step(1, "extract", "local_small"), step(2, "math", "local_small", [1]),
+ step(3, "draft_message", "local_small", [2])]
+ cases = [ # item, answer, expected (format_ok, coverage, assign_ok, ordering_ok, priv, passed)
+ ("o-extract-analyze-report", "[" + ",".join(good) + "]", (True, True, 1.0, True, False, True)),
+ ("o-extract-analyze-report", "plan:\n[" + ",".join(good[:2] + [step(3, "draft_message", "local_small", [1])]) + "]",
+ (True, True, 1.0, False, False, False)),
+ ("o-extract-analyze-report", "[" + ",".join(good[:1] + [step(2, "math", "cloud_claude", [1])] + good[2:]) + "]",
+ (True, True, 0.67, True, False, False)),
+ ("o-extract-analyze-report", "[" + ",".join(good[:2]) + "]", (True, False, 1.0, False, False, False)),
+ ("o-privacy-chain", "[" + step(1, "math", "cloud_ollama") + "," + step(2, "draft_message", "local_small", [1]) + "]",
+ (True, True, 0.5, True, True, False)),
+ ("o-simple-two", '{"plan": [' + step(1, "extract", "local_small") + "]}", (True, True, 1.0, True, False, True)),
+ ("o-simple-two", "[1, " + step(1, "extract", "local_small") + "]", (True, True, 1.0, True, False, True)),
+ ("o-simple-two", "no plan", (False, False, 0.0, False, None, False)),
+ ("o-simple-two", "[]", (False, False, 0.0, False, None, False)),
+ ]
+ for item, answer, want in cases:
+ with self.subTest(item=item, answer=answer):
+ rec = router.score_orch(ITEMS[item], chat(answer))
+ self.assertEqual(tuple(rec.get(k) for k in keys), want)
+
+
+class JudgeRerank(unittest.TestCase):
+ def test_score_judge(self):
+ v = {"id": "j-x", "kind": "verdict", "cat": "code", "task": "t", "candidate": "c", "gold": "fail"}
+ self.assertTrue(router.score_judge(v, chat('{"verdict": "FAIL", "reason": "off by one"}'))["correct"])
+ self.assertFalse(router.score_judge(v, chat('{"verdict": "pass"}'))["correct"])
+ bad = router.score_judge(v, chat("It fails."))
+ self.assertEqual((bad["correct"], bad["format_ok"]), (False, False))
+
+ def test_pairwise_runs_both_orders(self):
+ pairs = [(i, p) for i, p in router.judge_attempts() if p["kind"] == "pairwise"]
+ self.assertEqual(len(pairs), 2 * sum(1 for it in router.JUDGE if it["kind"] == "pairwise"))
+ (i1, ab), (i2, ba) = pairs[:2]
+ self.assertEqual((i1[-3:], i2[-3:]), ("/ab", "/ba"))
+ self.assertEqual((ab["a"], ab["b"]), (ba["b"], ba["a"]))
+ self.assertNotEqual(ab["gold"], ba["gold"])
+ msg = router.judge_messages(ba)[1]["content"]
+ self.assertLess(msg.index(ba["a"]), msg.index(ba["b"]))
+ right = "A" if ba["gold"] == "a" else "B"
+ self.assertTrue(router.score_judge(ba, chat('{"better": "%s"}' % right))["correct"])
+
+ def test_score_rerank(self):
+ it = {"id": "k-x", "cat": "logs", "query": "q", "candidates": {"c%d" % i: "t" for i in range(1, 7)},
+ "relevance": {"c4": 3, "c2": 2, "c6": 1}}
+ best = router.score_rerank(it, chat('{"ranking": ["c4", "c2", "c6", "c1", "c3", "c5"]}'))
+ self.assertEqual((best["top1"], best["mrr"], best["ndcg5"], best["complete"]), (True, 1.0, 1.0, True))
+ second = router.score_rerank(it, chat('{"ranking": ["c2", "[c4]"]}')) # partial, bracketed id
+ self.assertEqual((second["top1"], second["mrr"], second["complete"]), (False, 0.5, False))
+ self.assertLess(second["ndcg5"], 1.0)
+ none = router.score_rerank(it, chat("c4 is best"))
+ self.assertEqual((none["format_ok"], none["correct"], none["ndcg5"]), (False, False, 0.0))
+
+ def test_families_have_their_own_item_sets(self):
+ sets = {f: router.item_set(f) for f in router.FAMILIES}
+ self.assertEqual(len(set(sets.values())), 4)
+ self.assertTrue(all(v.startswith("router-%s@" % f) for f, v in sets.items()))
+
+ def test_run_judge_and_rerank_with_mock(self):
+ import io
+ from contextlib import redirect_stdout
+ from _util import run_main
+ from bench.core import lane as lane_mod, results
+ from bench.core.mockserver import MockServer
+
+ def fn(body):
+ sysmsg = body["messages"][0]["content"]
+ if sysmsg.startswith("You rank"):
+ return chat('{"ranking": ["c1"]}')
+ if "pick the one" in sysmsg:
+ return chat('{"better": "A"}')
+ return chat('{"verdict": "pass"}')
+ with MockServer() as srv:
+ srv.default = fn
+ lane_mod.set_current(srv.lane(lane_id="router-jr"))
+ buf = io.StringIO()
+ with redirect_stdout(buf):
+ rc = run_main(router, ["run", "--families", "judge,rerank"])
+ self.assertEqual(rc, 0)
+ rows = results.load_rows("router", "router-jr")
+ cats = {r["category"].split("/")[0] for r in rows}
+ self.assertEqual(cats, {"judge", "pairwise", "rerank"})
+ self.assertEqual(len(rows), len(router.judge_attempts()) + len(router.RERANK))
+ pair = [r for r in rows if r["category"].startswith("pairwise/")]
+ self.assertEqual(sum(1 for r in pair if r["correct"]), len(pair) // 2) # always "A": right once per pair
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_sleuth.py b/tests/test_sleuth.py
new file mode 100644
index 0000000..00a2384
--- /dev/null
+++ b/tests/test_sleuth.py
@@ -0,0 +1,134 @@
+"""Offline tests for the sleuth instrument. Docker-backed tests skip when no daemon answers."""
+import contextlib
+import io
+import json
+import os
+import subprocess
+import unittest
+
+from _util import TMP
+from bench.core import tools
+from bench.core.mockserver import MockServer, chat, tool_call
+from bench.tasks import agentic_multitask as harness
+from bench.tasks import sleuth
+
+
+def _docker_up():
+ try:
+ return subprocess.run(["docker", "info"], capture_output=True, timeout=20).returncode == 0
+ except (OSError, subprocess.TimeoutExpired):
+ return False
+
+
+DOCKER = _docker_up()
+
+
+def case(**kw):
+ args = dict(case_id="t", category="sleuth/t", complaint="", context=dict, culprit=[r"pstate"],
+ reject=[r"thermal"], fix=[r"=y"], key=["k"], expert=[], reference={},
+ wrong=[{"culprit": "x"}])
+ args.update(kw)
+ return sleuth.Case(**args)
+
+
+class Grade(unittest.TestCase):
+ def test_grade_table(self):
+ snap, live = case(), case(check="true")
+ for c, f, want in [
+ (snap, ("intel_pstate missing", "", "CONFIG_X86_INTEL_PSTATE=y"), {"culprit": True, "fix": True}),
+ (snap, ("kernel config", "the pstate driver is gone", "rebuild"), {"culprit": True, "fix": False}),
+ (snap, ("pstate, or thermal", "", "=y"), {"culprit": False, "fix": True}),
+ (snap, ("pstate", "not thermal", "=y"), {"culprit": True, "fix": True}),
+ (live, ("pstate", "", "anything"), {"culprit": True}),
+ ]:
+ self.assertEqual(sleuth.grade(c, dict(zip(sleuth.FINDINGS, f))), want, f)
+
+ def test_ramsleuth_channel_needs_the_directory_read(self):
+ """Offhand "raw" mentions no longer pass (Opus 2026-10-12, samples 0 and 1); answers
+ naming the directory read still do."""
+ c = [x for x in sleuth.load_cases() if x.case_id == "ramsleuth-channel"][0]
+ offsets = "intel_smbios.rs parse_type17() reads the Device Locator from 0x06/0x0C, not 0x10"
+ for f, want in [
+ ((offsets, "string_at assumes an empty first string, which the kernel's raw file does not have",
+ "use offset 0x10"), {"culprit": False, "fix": False}),
+ ((offsets, "", "add a test using this board's real Type 17 bytes from "
+ "/sys/firmware/dmi/entries/17-{0,1}/raw"), {"culprit": False, "fix": False}),
+ (("collect_from() calls std::fs::read() on each dmi/entries/17-N path, but the kernel exposes "
+ "each of those as a directory", "", 'read path.join("raw") for each 17-* entry'),
+ {"culprit": True, "fix": True}),
+ (("collect_from does fs::read on /sys/firmware/dmi/entries/17-0, which fails with EISDIR", "",
+ "read 17-0/raw instead of 17-0"), {"culprit": True, "fix": True}),
+ ]:
+ self.assertEqual(sleuth.grade(c, dict(zip(sleuth.FINDINGS, f))), want, f)
+
+ def test_snapshot_needs_bare_command_keys(self):
+ with self.assertRaises(ValueError):
+ sleuth.snapshot({}, {"uname -r": "7.3.0\n"})
+
+
+@unittest.skipUnless(DOCKER, "no Docker daemon")
+class Docker(unittest.TestCase):
+ def setUp(self):
+ tools.WORK_ROOT = os.path.join(TMP, "work")
+
+ def run_case(self, script, case_id="cpufreq-driver"):
+ (c,) = [c for c in sleuth.load_cases() if c.case_id == case_id]
+ with MockServer() as srv:
+ srv.script = script
+ d = harness.run_instrument("unit-sleuth", "sleuth", [sleuth.task(c)], lane=srv.lane(),
+ log=lambda *a, **k: None, max_turns=6)
+ reqs = [r["body"] for r in srv.requests]
+ with open(os.path.join(d, "items.jsonl")) as f:
+ rows = [json.loads(line) for line in f]
+ return rows[-1], reqs
+
+ def test_end_to_end_with_mock(self):
+ (c,) = [c for c in sleuth.load_cases() if c.case_id == "cpufreq-driver"]
+ drv = "cat /sys/devices/system/cpu/cpufreq/policy0/scaling_driver"
+ row, reqs = self.run_case([
+ chat("", tool_calls=[tool_call("run", {"command": "uptime"})]),
+ chat("", tool_calls=[tool_call("run", {"command": drv})]),
+ chat("", tool_calls=[tool_call("submit_findings", {"culprit": "x"})]),
+ chat("", tool_calls=[tool_call("submit_findings", c.reference, "c9")]),
+ ])
+ self.assertEqual(reqs[0]["temperature"], sleuth.TEMPERATURE)
+ self.assertEqual(reqs[0]["messages"][1]["content"], c.complaint)
+ tool_out = [m["content"] for m in reqs[2]["messages"] if m["role"] == "tool"]
+ self.assertTrue(tool_out[1].startswith("exit=0\nacpi-cpufreq"), tool_out[1])
+ self.assertIn("needs `root_cause`", reqs[3]["messages"][-1]["content"])
+ self.assertEqual(row["gates"], {"culprit": True, "fix": True, "seen": True})
+ self.assertIs(row["correct"], True)
+ self.assertEqual((row["checks"], row["first_key_check"], row["expert_checks"]), (2, 2, 2))
+ self.assertEqual(row["findings"], c.reference)
+ self.assertIsNotNone(row["investigate_s"])
+ names = subprocess.run(["docker", "ps", "-a", "--format", "{{.Names}}"], capture_output=True,
+ text=True).stdout
+ self.assertNotIn("llm-bench-sleuth-", names)
+
+ def test_unseen_evidence_fails_seen(self):
+ (c,) = [c for c in sleuth.load_cases() if c.case_id == "cpufreq-driver"]
+ row, _ = self.run_case([chat("", tool_calls=[tool_call("submit_findings", c.reference)])])
+ self.assertEqual(row["gates"], {"culprit": True, "fix": True, "seen": False})
+ self.assertIs(row["correct"], False)
+ self.assertEqual((row["checks"], row["first_key_check"]), (0, None))
+
+ def test_lost_container_is_infra_not_a_grade(self):
+ def kill_then_run(_body):
+ for n in subprocess.run(["docker", "ps", "--format", "{{.Names}}"], capture_output=True,
+ text=True).stdout.split():
+ if n.startswith("llm-bench-sleuth-"):
+ subprocess.run(["docker", "rm", "-f", n], capture_output=True)
+ return chat("", tool_calls=[tool_call("run", {"command": "uptime"})])
+ row, _ = self.run_case([kill_then_run])
+ self.assertEqual((row["status"], row["correct"]), ("harness_error", None))
+ self.assertIn("docker exec failed", row["error"])
+
+ def test_cases_validate(self):
+ buf = io.StringIO()
+ with contextlib.redirect_stdout(buf):
+ ok = harness.run_validate([sleuth.task(c) for c in sleuth.load_cases()], log=print)
+ self.assertTrue(ok, buf.getvalue()[-3000:])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_stats.py b/tests/test_stats.py
new file mode 100644
index 0000000..70e8e83
--- /dev/null
+++ b/tests/test_stats.py
@@ -0,0 +1,50 @@
+"""Tests for bench.core.stats (pure functions)."""
+import unittest
+
+import _util # noqa: F401
+from bench.core import stats
+
+
+class Stats(unittest.TestCase):
+ def test_bootstrap_deterministic_and_bounded(self):
+ v = [1, 0, 1, 1, 0, 1, 0, 1]
+ a = stats.bootstrap_ci(v, n_boot=500, seed=7)
+ b = stats.bootstrap_ci(v, n_boot=500, seed=7)
+ c = stats.bootstrap_ci(v, n_boot=500, seed=8)
+ self.assertEqual(a, b)
+ self.assertNotEqual(a, c)
+ self.assertTrue(0 <= a[0] <= 0.625 <= a[1] <= 1)
+ self.assertEqual(stats.bootstrap_ci([0.3]), (0.3, 0.3))
+ self.assertIsNone(stats.bootstrap_ci([]))
+
+ def test_wilson(self):
+ lo, hi = stats.wilson(8, 10)
+ self.assertAlmostEqual(lo, 0.4902, places=3)
+ self.assertAlmostEqual(hi, 0.9433, places=3)
+ self.assertEqual(stats.wilson(0, 5)[0], 0.0)
+ self.assertIsNone(stats.wilson(0, 0))
+
+ def test_mcnemar_known_table(self):
+ self.assertAlmostEqual(stats.mcnemar_exact(1, 9), 2 * 11 / 1024)
+ self.assertEqual(stats.mcnemar_exact(5, 5), 1.0)
+ self.assertEqual(stats.mcnemar_exact(0, 0), 1.0)
+ self.assertAlmostEqual(stats.mcnemar_exact(0, 6), 2 / 64)
+
+ def test_mcnemar_items_pairing_and_ties(self):
+ a = {"i1": 1.0, "i2": 1.0, "i3": 0.0, "i4": 0.5, "i5": 1.0, "only_a": 1.0}
+ b = {"i1": 0.0, "i2": 1.0, "i3": 1.0, "i4": 1.0, "i5": 0.0, "only_b": 0.0}
+ m = stats.mcnemar_items(a, b)
+ self.assertEqual((m["b"], m["c"], m["n_both_pass"], m["n_tied_dropped"]), (2, 1, 1, 1))
+ self.assertAlmostEqual(m["p"], 1.0)
+
+ def test_paired_delta_intersection(self):
+ a = {"x": 1.0, "y": 1.0, "z": 0.0}
+ b = {"y": 0.0, "z": 0.0, "w": 1.0}
+ d = stats.paired_delta(a, b, n_boot=100)
+ self.assertEqual(d["n"], 2)
+ self.assertAlmostEqual(d["mean_delta"], 0.5)
+ self.assertEqual(stats.paired_delta({"a": 1}, {"b": 1})["n"], 0)
+
+
+if __name__ == "__main__":
+ unittest.main()
port the lane harness + suite v3 from the toolbox copy
- core: lane profiles, typed client, append-only results, stats, ledger, claude-cli runner, mockserver; bench.py is now an instrument registry (LANE=<id>) - instruments: fix_easy/fix_hard (absorb coding-suite + agentic-fix), agentic-multitask (absorbs agentic-build), reasoning, sleuth, conformance (replaces no-think, which is now a lane mechanism), oracle, report, router judge/rerank sets, tool-call probes - tests/ (offline, MockServer) + CONTRACT.md + README rewrite; retired files removed - anonymized: usernames, hostnames and DIMM serials in sleuth/log fixtures replaced with synthetic ones; personal lanes dropped in favor of example-lmstudio + cards.json 134 tests pass (5 skipped: language toolchains).
6ff8f34666af0f9d72d40cf40cee5c98ad090dc0
Joshua Calhoon <josh@bar-all.com> · 2026-11-03T23:15 ·
browse files at this commit
parents:
6ad8974