Skip to content

Commit e34890d

Browse files
isPANNclaude
andauthored
feat(runner): add whole-repo agent mode alongside per-rule (#38)
A second, opt-in run mode for comparison. per-rule (default, unchanged) runs one isolated agent session per rule with the budget split evenly. whole-repo runs ONE session over the whole library: the agent enumerates the rules with `pred list`, triages them by suspicion, and emits a certificate per bug under a single budget (its cost_limit). Both modes produce the same submission.json and are scored by the same zero-trust pred re-verification, so results are directly comparable. Select with AGENT_MODE=whole-repo (or --mode whole-repo). - benchmark/config_repo.yaml: whole-repo prompt (enumerate + triage by suspicion, emit many certificates, don't stop at the first). - run_mini.py: parse_all_certificates (multi-cert, de-duped) and run_repo_session (single session → one row per cert, shared trajectory). - run_submission.py: --mode/AGENT_MODE, whole-repo branch, and a total_tokens_k override on build_submission (session totals don't live on per-rule rows). - verify_submission.py: provenance now matches ANY certificate block in the trajectory, not just the last — a whole-repo run emits many in one trajectory. - config.yaml: per-rule prompt gives a qualitative budget hint instead of the literal dollar figure (the agent can't meter its own spend). - submission.env.example + run-benchmark skill: document AGENT_MODE; the skill now confirms experiment parameters (mode/budget) with the user before a run. - tests: test_whole_repo.py + a multi-cert provenance test. Claude-Session: https://claude.ai/code/session_018xw6L5yUrz33UrQpanbwnH Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
1 parent 86ffa1b commit e34890d

11 files changed

Lines changed: 496 additions & 89 deletions

File tree

‎.claude/skills/run-benchmark/SKILL.md‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,18 @@ PRICE_OUT=15.0 # USD / 1M output tokens — REQUIRED
8585
For a cheap smoke run (don't spend the full $20) add `MAX_RULES=1`. A **ranked** submission
8686
must keep `BUDGET_USD=20` and omit `MAX_RULES`.
8787

88+
**Agent mode** (`AGENT_MODE`, default `per-rule`): `per-rule` runs one isolated agent session
89+
per rule with the budget split evenly; `whole-repo` runs ONE session over the whole library
90+
and lets the agent enumerate and triage the rules itself under a single budget. Both produce
91+
the same `out/submission.json` and are scored identically — set `AGENT_MODE=whole-repo` to try
92+
it. (`MAX_RULES` only applies to `per-rule`.)
93+
94+
**Confirm the experiment parameters with the user — don't silently default them.** These
95+
shape the result and the spend, so state the resolved set and get an explicit OK before
96+
running: **mode** (`AGENT_MODE`), **budget** (a full ranked run at `BUDGET_USD=20`, or a
97+
cheap smoke run via `MAX_RULES=1` / a smaller budget), and — only if they care —
98+
`PER_RULE_BUDGET` and `MAX_TOKENS`. Ranked runs require `BUDGET_USD=20` and no `MAX_RULES`.
99+
88100
## Step 4 — Preflight (one tiny real API call, ~a fraction of a cent)
89101

90102
Always run this before the full run; it validates key/endpoint/price + pred/rules through the
@@ -99,6 +111,9 @@ name / pricing). Decode table in `references/env-and-troubleshoot.md`. Do not pr
99111

100112
## Step 5 — Full run → out/submission.json
101113

114+
**Gate**: a full run spends real money and takes a while. Restate the resolved parameters
115+
(model, mode, budget, any smoke caps) and get an explicit OK before you launch it.
116+
102117
- **docker**: `make run`
103118
- **podman/raw**: use the `RUN_FLAGS` from Step 1, e.g.
104119
```bash

‎benchmark/config.yaml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ agent:
6767
Library repo: {{repo_dir}} (commit {{commit_hash}})
6868
Rule source: {{rule_file}}
6969
70-
Use pred commands to test the round-trip correctness. Budget: ${{cost_limit}}.
70+
Use pred commands to test the round-trip correctness. You have a limited budget — be efficient and don't over-explore.
7171
If you find a bug, emit the CERTIFICATE_START...CERTIFICATE_END block.
7272
If no bug found, run: echo COMPLETE_TASK_AND_SUBMIT_FINAL_OUTPUT
7373
</task>

‎benchmark/config_repo.yaml‎

Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
agent:
2+
system_template: |
3+
You are an expert at finding bugs in problem reduction rules using the `pred` CLI. You
4+
are given the WHOLE library and one budget; you decide which rules to probe and in what
5+
order, and report every bug you find.
6+
7+
Each rule implements two functions:
8+
- reduce_to(): transforms source problem A into target problem B
9+
- extract_solution(): maps a target solution back to source space
10+
11+
A rule is BUGGY if the round-trip fails:
12+
given A → reduce to B → solve B to get s → extract s → A', but A' is not a valid solution to A.
13+
14+
Your tool is `pred`. Key commands:
15+
pred list --rules --json # enumerate every reduction rule
16+
pred create <PROBLEM> [options] --json # create a problem instance
17+
pred reduce <file.json> --to <TARGET> --json # reduce source to target (produces a bundle)
18+
pred solve <bundle.json> --json # solve (finds optimal solution)
19+
pred evaluate <file.json> --config <vals> --json # check if a config is valid
20+
pred extract <bundle.json> --config <vals> --json # map target config back to source
21+
22+
On Windows, pred cannot read from stdin. Always write JSON to a file first, then pass the filename.
23+
24+
The single test for a bug (round-trip): solving the source directly must agree with
25+
solving it THROUGH the reduction, compared by VALUE (optimization) or feasibility
26+
(decision). `pred solve <bundle>` already does the whole round-trip, so you just compare
27+
it against `pred solve <source>`:
28+
pred solve source.json --json # direct answer, e.g. {"evaluation": "Max(7)"}
29+
pred reduce source.json --to <TARGET> --json -o bundle.json
30+
pred solve bundle.json --json # round-trip answer, e.g. {"evaluation": "Max(3)"}
31+
Different evaluations (Max(7) vs Max(3), or Or(true) vs Or(false), or one infeasible) =
32+
a genuine bug in the reduction.
33+
34+
{{strategy}}
35+
36+
How to work the whole repo:
37+
1. `pred list --rules --json` to see every rule. Rule sources are under
38+
{{repo_dir}}/src/rules/<rule>.rs — read the ones you probe.
39+
2. Prioritize by SUSPICION — spend your budget where a bug is most likely first.
40+
Good signals: rules touching weights/costs, offsets or constant shifts, min↔max or
41+
feasibility flips, empty/degenerate inputs, or extraction code that drops information.
42+
Don't sweep alphabetically; triage.
43+
3. For each rule you pick, construct a small source instance with `pred create` (tiny —
44+
minimal witnesses only) and compare `pred solve source` with `pred solve bundle`.
45+
4. (Optional, stronger) If a SPECIFIC valid target solution extracts to an invalid or
46+
worse source solution, note its config as `target_config`.
47+
48+
Report EVERY bug you find (you will likely find several). The moment a round-trip
49+
disagrees for a rule, emit a certificate in this format and then MOVE ON to the next
50+
rule — do NOT stop after the first:
51+
52+
CERTIFICATE_START
53+
{
54+
"rule": "<rule_name>",
55+
"source": <paste the source JSON from pred create>,
56+
"bundle": <paste the bundle JSON from pred reduce>,
57+
"target_config": "<optional: comma-separated target solution that mis-extracts>",
58+
"note": "<one sentence: source solves to X but the round-trip yields Y>"
59+
}
60+
CERTIFICATE_END
61+
62+
Only `rule`, `source`, and the target type (from `bundle`) are required; `target_config`
63+
is optional. The verifier re-derives everything from `source` with pred and never trusts
64+
your claim — a wrong or non-minimal certificate is simply rejected, so report only what
65+
you have actually reproduced. Keep going until you run out of budget or have covered the
66+
rules that look worth checking, then run: echo COMPLETE_TASK_AND_SUBMIT_FINAL_OUTPUT
67+
68+
instance_template: |
69+
<task>
70+
Find as many bugs as you can across the reduction rules in the library.
71+
72+
Library repo: {{repo_dir}} (commit {{commit_hash}})
73+
Rule sources: {{repo_dir}}/src/rules/
74+
75+
Enumerate the rules with `pred list --rules --json`, triage by suspicion, and test the
76+
round-trip correctness of each with pred. Emit a CERTIFICATE_START...CERTIFICATE_END
77+
block for every bug — many are expected; do not stop after the first. You have a limited
78+
budget — be efficient and spend it on the most suspicious rules first. When done, run:
79+
echo COMPLETE_TASK_AND_SUBMIT_FINAL_OUTPUT
80+
</task>
81+
82+
step_limit: 300
83+
cost_limit: 20.0
84+
85+
environment:
86+
timeout: 120
87+
env:
88+
PAGER: cat
89+
MANPAGER: cat
90+
LESS: -R
91+
92+
model:
93+
observation_template: |
94+
{% if output.exception_info -%}
95+
<exception>{{output.exception_info}}</exception>
96+
{% endif -%}
97+
<returncode>{{output.returncode}}</returncode>
98+
<output>
99+
{{ output.output[:8000] -}}
100+
</output>
101+
format_error_template: |
102+
Format error: {{error}}
103+
Provide exactly ONE bash command in triple backticks.

‎benchmark/run_mini.py‎

Lines changed: 126 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import argparse
88
import json
99
import os
10+
import re
1011
from pathlib import Path
1112

1213
import yaml
@@ -17,6 +18,7 @@
1718
from benchmark.verify import count_bugs, verify
1819

1920
CONFIG_FILE = Path(__file__).parent / "config.yaml"
21+
REPO_CONFIG_FILE = Path(__file__).parent / "config_repo.yaml"
2022
SKIP_RULES = {"mod", "traits", "graph_helpers", "analysis", "cost", "registry", "graph"}
2123

2224
# Rough average cost per 1K tokens (used as fallback when model doesn't report usage)
@@ -31,12 +33,13 @@ def list_rules(repo_dir: str) -> list[str]:
3133
return [f.stem for f in sorted(rules_dir.glob("*.rs")) if f.stem not in SKIP_RULES]
3234

3335

36+
_CERT_RE = re.compile(r"CERTIFICATE_START\s*\n(.*?)CERTIFICATE_END", re.DOTALL)
37+
38+
3439
def parse_certificate(messages: list) -> dict | None:
35-
"""Extract structured certificate JSON from agent message history."""
36-
import re
40+
"""Extract the last structured certificate JSON from agent message history."""
3741
for msg in reversed(messages):
38-
content = msg.get("content", "")
39-
block = re.search(r"CERTIFICATE_START\s*\n(.*?)CERTIFICATE_END", content, re.DOTALL)
42+
block = _CERT_RE.search(msg.get("content", "") or "")
4043
if block:
4144
try:
4245
return json.loads(block.group(1).strip())
@@ -45,6 +48,24 @@ def parse_certificate(messages: list) -> dict | None:
4548
return None
4649

4750

51+
def parse_all_certificates(messages: list) -> list[dict]:
52+
"""Every certificate block in the trajectory (a whole-repo run emits many), de-duplicated
53+
by (rule, source) in first-seen order. Unparseable blocks are skipped."""
54+
seen, out = set(), []
55+
for msg in messages:
56+
for block in _CERT_RE.finditer(msg.get("content", "") or ""):
57+
try:
58+
cert = json.loads(block.group(1).strip())
59+
except json.JSONDecodeError:
60+
continue
61+
key = (cert.get("rule"), json.dumps(cert.get("source"), sort_keys=True))
62+
if key in seen:
63+
continue
64+
seen.add(key)
65+
out.append(cert)
66+
return out
67+
68+
4869
def extract_total_tokens(messages: list) -> int:
4970
total = 0
5071
for msg in messages:
@@ -62,6 +83,22 @@ def save_trajectory(messages: list, path: Path) -> None:
6283
f.write(json.dumps({"role": msg.get("role", ""), "content": msg.get("content", "")}) + "\n")
6384

6485

86+
def _session_cost(agent, price):
87+
"""Authoritative session spend from the trajectory. ``agent.cost`` is already our
88+
token×price figure (see _build_model); cross-check against a fresh recompute and take
89+
the max — never under-count for the budget guard. Returns (cost, tokens_k, usage)."""
90+
usage = extract_usage(agent.messages)
91+
cost = max(agent.cost, price.cost(usage) if price is not None else 0.0)
92+
total_tokens = usage.total_tokens or extract_total_tokens(agent.messages)
93+
tokens_k = round(total_tokens / 1000, 2) if total_tokens else round(cost / AVG_COST_PER_KTOK * 1000, 2)
94+
return cost, tokens_k, usage
95+
96+
97+
def _trajectory(agent) -> list[dict]:
98+
"""The agent's own message history — provenance proof carried on cert-bearing rows."""
99+
return [{"role": m.get("role", ""), "content": m.get("content", "")} for m in agent.messages]
100+
101+
65102
def _build_model(model_name: str, api_base: str | None, max_tokens: int, price: Price | None,
66103
model_kwargs: dict | None = None, api_key: str | None = None):
67104
"""A LitellmModel whose cost is OUR token×price figure, so mini-swe-agent's own
@@ -148,23 +185,11 @@ def run_one(
148185
cert = None
149186
try:
150187
agent.run(task=rule_name)
151-
# agent.cost is already our token×price figure (see _build_model), which is what
152-
# mini-swe-agent's per-step cost_limit enforced. Cross-check it against a fresh
153-
# recompute over the whole trajectory and take the max — never under-count.
154-
usage = extract_usage(agent.messages)
155-
agent_cost = agent.cost
156-
recomputed = price.cost(usage) if price is not None else 0.0
157-
cost = max(agent_cost, recomputed)
158-
total_tokens = usage.total_tokens or extract_total_tokens(agent.messages)
159-
tokens_k = round(total_tokens / 1000, 2) if total_tokens else round(cost / AVG_COST_PER_KTOK * 1000, 2)
188+
cost, tokens_k, usage = _session_cost(agent, price)
160189
usage_row = {"input": usage.input_tokens, "output": usage.output_tokens,
161190
"cache_read": usage.cache_read_tokens, "cache_write": usage.cache_write_tokens,
162-
"accounted_cost_usd": round(agent_cost, 6)}
163-
# Provenance record: the agent's own message history. The backend requires this on a
164-
# bug_found row and checks the certificate was emitted here (not pasted from a public
165-
# answer key), so we carry it on every cert-bearing row.
166-
trajectory = [{"role": m.get("role", ""), "content": m.get("content", "")}
167-
for m in agent.messages]
191+
"accounted_cost_usd": round(agent.cost, 6)}
192+
trajectory = _trajectory(agent)
168193
cert = parse_certificate(agent.messages)
169194
if trajectory_dir is not None:
170195
safe_model = model_name.replace("/", "_").replace(":", "_")
@@ -221,6 +246,88 @@ def run_one(
221246
}
222247

223248

249+
def run_repo_session(
250+
model_name: str,
251+
ctx: EnvContext,
252+
cost_limit: float,
253+
*,
254+
api_base: str | None = None,
255+
trajectory_dir: Path | None = None,
256+
price: Price | None = None,
257+
max_tokens: int = DEFAULT_MAX_TOKENS,
258+
step_limit: int | None = None,
259+
config_path: str | Path | None = None,
260+
strategy: str | None = None,
261+
model_kwargs: dict | None = None,
262+
api_key: str | None = None,
263+
) -> dict:
264+
"""One WHOLE-REPO bug-hunting session: the agent gets the entire library + pred and the
265+
full budget as its ``cost_limit``, chooses which rules to probe, and emits a certificate
266+
per bug. Returns ``{"rows": [...], "cost": float, "tokens_k": float}`` — one result row
267+
per distinct emitted certificate, each re-verified with pred and carrying the shared
268+
session trajectory for provenance. Contrast with ``run_one`` (one isolated rule/session).
269+
"""
270+
from minisweagent.agents.default import DefaultAgent
271+
from minisweagent.environments.local import LocalEnvironment
272+
273+
cfg_file = Path(config_path) if config_path else REPO_CONFIG_FILE
274+
config = yaml.safe_load(cfg_file.read_text(encoding="utf-8"))
275+
if strategy is None:
276+
strat_file = os.environ.get("AGENT_STRATEGY_FILE")
277+
strategy = Path(strat_file).read_text(encoding="utf-8") if strat_file else ""
278+
agent_cfg = config.get("agent", {})
279+
agent_cfg["cost_limit"] = cost_limit
280+
if step_limit is not None:
281+
agent_cfg["step_limit"] = step_limit
282+
283+
agent = DefaultAgent(
284+
_build_model(model_name, api_base, max_tokens, price,
285+
model_kwargs=model_kwargs, api_key=api_key),
286+
LocalEnvironment(),
287+
**agent_cfg,
288+
)
289+
agent.extra_template_vars = {
290+
"repo_dir": str(ctx.repo_path),
291+
"commit_hash": ctx.commit_hash[:7],
292+
"cost_limit": cost_limit,
293+
"strategy": strategy,
294+
}
295+
296+
agent.run(task="find-bugs")
297+
cost, tokens_k, _usage = _session_cost(agent, price)
298+
trajectory = _trajectory(agent)
299+
if trajectory_dir is not None:
300+
safe_model = model_name.replace("/", "_").replace(":", "_")
301+
save_trajectory(agent.messages, Path(trajectory_dir) / f"{safe_model}_whole-repo.jsonl")
302+
303+
rows = _rows_from_certificates(parse_all_certificates(agent.messages))
304+
# The whole session is ONE trajectory shared by every bug — return it once for the
305+
# envelope (build_submission) instead of copying it onto each row.
306+
return {"rows": rows, "cost": cost, "tokens_k": tokens_k, "trajectory": trajectory}
307+
308+
309+
def _rows_from_certificates(certs: list[dict]) -> list[dict]:
310+
"""Verify each certificate with pred and build one result row per cert. bug_found when
311+
pred confirms, else rejected. No per-row trajectory — a whole-repo run's provenance
312+
trajectory lives once at the envelope level (submission["trajectory"])."""
313+
rows = []
314+
for cert in certs:
315+
verdict = verify(cert)
316+
row = {
317+
"rule": cert.get("rule"),
318+
"result": "bug_found" if verdict.accepted else "rejected",
319+
"cost": 0.0, # session cost/tokens live on the submission envelope, not per row
320+
"tokens_k": 0.0,
321+
"certificate": cert,
322+
}
323+
if verdict.accepted:
324+
row["verify_details"] = verdict.details
325+
else:
326+
row["reject_reason"] = verdict.reason
327+
rows.append(row)
328+
return rows
329+
330+
224331
def main() -> None:
225332
parser = argparse.ArgumentParser(description="pred-based bug-finding benchmark")
226333
parser.add_argument("--model", default="anthropic/claude-sonnet-4-6", help="LiteLLM model name")

0 commit comments

Comments
 (0)