aien-dev has reached the 50-credit limit for trial accounts. To continue receiving code reviews, upgrade your plan.
interplane-mv
INTERPLANE: open interoperability protocol between AI models and agent runtimes. Models express intent. Runtimes retain authority.
Brought by drakestapleton
GitHub aien-dev/interplane-mv#27 (code only)
Apply it
git checkout -b patch-e8aaf6e9f671a708 ed92ea7dcb64144d8cd046afa306703816bd4173 curl -fsSL https://interplane.io/drakestapleton/interplane-mv/patches/e8aaf6e9f671a708.patch | git am
Provenance
github-import 1
aien-dev/interplane-mv
27
fa6461e6ffdc2473b9ff81c3328bf5c791044e45
{"kind":"github-import","owner":"aien-dev","repo":"interplane-mv","number":27,"url":"https://github.com/aien-dev/interplane-mv/pull/27","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:40:01Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/STATUS.md b/STATUS.md index 1e23730..bae9687 100644 --- a/STATUS.md +++ b/STATUS.md @@ -28,7 +28,7 @@ byte-identical) ยท `qualified` (measured against a real model/backend). | AIEN adapter | tested (on the real EffectAuthority path, pinned sovereign-core 6554aac; was 10 pipeline tests in 0.1) | - | - | ADR 0003; real aien-mcp SpeculativeLane + aegis gate; aien-cli SafetyEngine not linkable (private); AGPL | | Odysseus adapter | - | tested (55 tests vs odysseus@2992bf6) | - | executes read_file/ls/glob/grep via Odysseus handlers; AGPL | | Before/after receipt (0.1 goal) | - | qualified | 2 runs, reproduced | examples/receipt | -| CrossAxis gate, 0.2 pre-registered (37 pairs, qwen3.5:9b on Ollama) | - | qualified: FAIL | bench/runs/qual-20261004T2207Z | T 0.877 PASS, S PASS (B 0.730 vs A 0.676), O1 0.865 FAIL, O2 0/5 FAIL; model did not use the discovery tool. See docs/REPORT-0.2.md | +| CrossAxis gate, 0.2 pre-registered (37 pairs, qwen3.5:9b on Ollama) | - | qualified: FAIL | bench/runs/qual-20261004T2207Z | T 0.877 PASS, S PASS (B 0.730 vs A 0.676), O1 0.865 FAIL, O2 0/5 FAIL; model did not use the discovery tool. See docs/REPORT-0.2.md. 0.2x held-out campaign (bench/PROTOCOL-0.2x.md) not run: runner prepared; arm 3 negative controls N1 and N2 (denied and approval-pending calls cause no expansion and no execution) tested offline in bench/tools/test_runner_offline.py | | Qwen3.5-9B on llama.cpp b11398 | - | qualified | probes 14/14 (Rust and Python, aligned) | qualification/captures/qwen35-llamacpp | | Qwen3.5-9B on SGLang 0.5.20 (bf16, qwen3_coder parser) | - | qualified | probes 14/14 (Rust and Python, aligned) | earlier 12/14 kept as pre-alignment | | AIEN authority path (sovereign-core #203, #204) | tested | - | adapter approval tests (6) | single-use approvals; grants in memory, spent at mint, host clock | diff --git a/bench/PROTOCOL-0.2x.md b/bench/PROTOCOL-0.2x.md index 58469a0..0e1a1fd 100644 --- a/bench/PROTOCOL-0.2x.md +++ b/bench/PROTOCOL-0.2x.md @@ -322,3 +322,11 @@ digests differ from the frozen ones does not count. checking the 0.2 qual receipts: condition B produced 0 `unknown_capability` and 0 `capability_not_found` results, so a gate change toward what arm 3 can reach was rejected; O1 and O2 are unchanged. No held-out run exists. +- 2026-10-04: section 10 still lists arm 3 as not yet built. It is built: the arm 3 policy + (`runtime-v1`, section 5) merged as #25 at ed92ea7, and its negative controls N1 and N2 (denied + and approval-pending calls cause no expansion and no execution) are tested offline in + `bench/tools/test_runner_offline.py`. The runner preparation of section 10 (`--corpus 0.2x`, + the seven condition ids, the addendum, the reasoning-off field, seeds 42, 43 and 44, and the + campaign analyzer with O2a, O2b, per-kind figures and the fragile label) is built in the PR that + adds this line. Section 10 is left as written. No gate, threshold, task or input changed. No + held-out run exists. diff --git a/bench/README.md b/bench/README.md index 95cbefb..4dab0dc 100644 --- a/bench/README.md +++ b/bench/README.md @@ -176,3 +176,38 @@ exist. - Corpus digests: adding `stubs/backends.json` and `stubs/stores/` changed `inputs_digest` in `CORPUS-DIGEST.txt`. `tasks_digest` and `protocol_sha256` are unchanged. The 0.2 runs carry the digests they ran against in their own `manifest.json`, which is unchanged. + +## Running the 0.2x campaign (PROTOCOL-0.2x.md, section 10) + +Nothing here has been run on the held-out set. The runner switches, all required with `--backends sim-1`: + +| Switch | What it does | +|---|---| +| `--corpus 0.2x` | Task root `bench/heldout-0.2x` (fixtures, stubs and stores resolve there), `--tasks` defaults to `qual` (all 120), the three frozen digests are checked and the run is refused if one differs. Seeds other than 42, 43, 44 are refused. | +| `--condition A\|A2\|A4\|B1\|B2\|B3\|B4` or `all` | The seven conditions of section 4. The id fixes everything else: `B3` runs `runtime-v1` (arm 3), `B1`, `B2` and `B4` run the 0.2 mechanism, `A2` and `B2` append `heldout-0.2x/prompts/discovery-addendum.md` to `system.md` after one blank line, `A4` and `B4` turn reasoning off. `all` runs the seven in the order A, A2, A4, B1, B2, B3, B4, rotated left by (task index mod 7). `--expansion-policy` must stay at its default. | +| `--reasoning-field reasoning_effort\|chat_template_kwargs` | The request field that turns reasoning off: `reasoning_effort: "none"` (Ollama, the default) or `chat_template_kwargs.enable_thinking = false` (SGLang, llama.cpp). Sent on every request of an A4 or B4 run, including the `max_tokens = 1` token measurements. Receipts record `reasoning.invalid_for_arm4` when any round shows reasoning. | +| `--seed 42\|43\|44` | One seed block per run. Every receipt carries the seed in `generation` and the condition id in `condition` and `condition_spec`. | + +Each seed block also writes `gpu_at_start.txt`, `gpu_at_end.txt` and `latency_validity` in its manifest (section 8), runs one untimed dev-task warm-up from `bench/tasks`, and re-runs an infrastructure failure once. + +**Pilot on dev tasks only, all seven conditions** (about 0.9 h, 44 tasks x 7 conditions): + +``` +ODYSSEUS_SRC=<odysseus@2992bf6> <odysseus-venv>/bin/python bench/tools/run_bench.py \ + --corpus 0.2 --tasks all --condition all --backends sim-1 --seed 42 --out bench/runs/pilot-0.2x-<ts> +``` + +**Campaign** (120 tasks x 7 conditions x 3 seeds = 2520 runs, about 7.6 h at the 0.2 median of 10.8 s per run, plus the token measurements; reasoning-off runs should be shorter). Needs an uncontended GPU. Write the manifests first, commit them, then run the three seed blocks one after another: + +``` +export ODYSSEUS_SRC=<odysseus@2992bf6> +PY=<odysseus-venv>/bin/python +RUN=bench/runs/heldout-0.2x-$(date -u +%Y%m%dT%H%MZ) +for s in 42 43 44; do $PY bench/tools/run_bench.py --corpus 0.2x --condition all --backends sim-1 --seed $s --out $RUN/seed-$s --prepare; done +for s in 42 43 44; do $PY bench/tools/run_bench.py --corpus 0.2x --condition all --backends sim-1 --seed $s --out $RUN/seed-$s --resume; done +python3 bench/tools/analyze.py $RUN/seed-42 --campaign --stability $RUN/seed-43,$RUN/seed-44 --out $RUN/analysis +``` + +Run the loop detached (`setsid nohup ... &`), and never kill a GPU process. `--resume` continues after an interruption. The analyzer writes `campaign-summary.json` and `.md`: per arm the gates T, S, O1, O2 (seed 42 only), O2a and O2b, O1 and O2 per expansion kind (named, path, nopath), trigger counts, refusals, the negative controls (must be zero for arm 3), results per category and per template, the secondary comparisons against B1, and the label `fragile` when a gate criterion flips under seed 43 or 44. + +Offline tests for every switch: `tools/test_runner_offline.py` (conditions, addendum, reasoning field, seeds, corpus switch) and `tools/test_analyze.py` (campaign analyzer on synthetic seed blocks). diff --git a/bench/heldout-0.2x/CORPUS-DIGEST.txt b/bench/heldout-0.2x/CORPUS-DIGEST.txt index 8eb4be8..5ae927f 100644 --- a/bench/heldout-0.2x/CORPUS-DIGEST.txt +++ b/bench/heldout-0.2x/CORPUS-DIGEST.txt @@ -3,5 +3,5 @@ # each = sha256 over `sha256sum` lines in LC_ALL=C path order, paths relative to bench/. tasks_digest sha256:89996c0bbdced1ff119635fce95376514ca3a2de9b2a2b9047c8e8b499f4e6e7 inputs_digest sha256:060ae80194c41a535cf9d573ac705f35f0f8b90d02f531927a65f2826726c6e6 -protocol_sha256 sha256:827ef5fd638b3015d9d89a2484af664c08e7be26314558e7bc6ffee961bed4b3 +protocol_sha256 sha256:89fe9ec2da2c26c83cbe462e70216b9ae3ae53af4e4c51d92945b6224a8d0f6d tasks 120 dev 0 qual 120 diff --git a/bench/tools/analyze.py b/bench/tools/analyze.py index 9949852..6e0c7c2 100644 --- a/bench/tools/analyze.py +++ b/bench/tools/analyze.py @@ -13,6 +13,16 @@ qual task is dropped after results are seen). Deterministic: the same input gives byte-identical output (fixed bootstrap seed, fixed float rounding, sorted keys, no timestamps, no environment data). + +Campaign mode (PROTOCOL-0.2x.md sections 4, 6, 8, 11): + + python3 bench/tools/analyze.py <seed-42 run dir> --campaign [--stability <seed-43 dir>,<seed-44 dir>] [--out DIR] + +reads the seven-condition run of the held-out set (receipts ``<task>.<A|A2|A4|B1|B2|B3|B4>.json``) +and writes campaign-summary.json and campaign-summary.md: per arm (1 to 4) the gate T, S, O1, O2 on +seed 42 against its matched baseline, the diagnostics O2a and O2b, O1 and O2 per expansion kind, +trigger counts, refusals, the negative controls, and the label ``fragile`` when a gate criterion +of the arm flips under seed 43 or 44. The 0.2 outputs above are unchanged. """ from __future__ import annotations @@ -25,6 +35,7 @@ import math import random import statistics import sys +from collections import Counter from pathlib import Path HERE = Path(__file__).resolve().parent @@ -37,6 +48,10 @@ BOOT_SEED = 20261004 BOOT_N = 10000 ROUND = 6 GATE_T, GATE_O1, GATE_O2 = 0.70, 0.95, 0.90 +# PROTOCOL-0.2x.md section 4: arm -> (matched baseline condition, arm condition) +ARMS = {"1": ("A", "B1"), "2": ("A2", "B2"), "3": ("A", "B3"), "4": ("A4", "B4")} +CRITERIA = ("T", "S", "O1", "O2") +HELDOUT_TASKS = BENCH / "heldout-0.2x" / "tasks" def rnd(x): @@ -454,16 +469,236 @@ def write_outputs(summary: dict, out_dir: Path) -> None: (out_dir / "tasks.csv").write_text(buf.getvalue(), encoding="utf-8") +# ------------------------------------------------------------------------------- 0.2x campaign + +def expansion_kind(task: dict): + import re + m = re.search(r"expansion_kind: ([a-z]+)", task.get("notes") or "") + return m.group(1) if m else None + + +def template_of(task: dict): + import re + m = re.search(r"template: ([a-z0-9_.-]+)", task.get("notes") or "") + return m.group(1) if m else None + + +def trigger_fired(rec: dict) -> bool: + """O2a: a runtime trigger (T1, T2, T3), an attempted expansion, or a model discovery call.""" + return bool(rec.get("runtime_triggers")) or bool(rec.get("expansions")) or rec["metrics"]["discovery_calls"] > 0 + + +def recovered_in_one(m: dict) -> bool: + return m["covered_after_effective_expansions"] is not None and m["covered_after_effective_expansions"] <= 1 + + +def expansion_figures(rows: list) -> dict: + """O1, O2, O2a and O2b over the expansion tasks of ``rows`` (rows hold the arm receipt under "B").""" + o1 = sum(1 for r in rows if not r["B"]["metrics"]["missing_required_final"]) + o2 = sum(1 for r in rows if recovered_in_one(r["B"]["metrics"])) + fired = [r for r in rows if trigger_fired(r["B"])] + return {"tasks": len(rows), "O1_covered_final": o1, "O2_recovered_within_1": o2, + "O2a_trigger_fired": len(fired), "O2b_recovered_given_trigger": sum(1 for r in fired if recovered_in_one(r["B"]["metrics"]))} + + +def negative_controls(recs: list) -> dict: + """Counts that must be zero for arm 3 (section 5, N1 and N2, section 10).""" + unauth = fired = 0 + for r in recs: + by_call = {(c["round"], c["index"]): c for c in r["calls"]} + unauth += sum(1 for c in r["calls"] if c["decision"] in ("denied", "requires_approval") and c.get("executed")) + for e in r["expansions"]: + c = by_call.get((e.get("round"), e.get("call_index"))) + if c is not None and c["decision"] in ("denied", "requires_approval") and e.get("added"): + fired += 1 + return {"executions_of_denied_or_pending_calls": unauth, "expansions_fired_by_denied_or_pending_call": fired} + + +def arm_extras(rows: list, recs: list) -> dict: + exp = [r for r in rows if r["_task"]["category"] == "expansion"] + kinds = sorted({expansion_kind(r["_task"]) for r in exp} - {None}) + trig, outcome, refused, notes = Counter(), Counter(), Counter(), 0 + for r in recs: + for t in r.get("runtime_triggers") or []: + trig[t["trigger"]] += 1 + outcome[t.get("outcome", "none")] += 1 + for e in r["expansions"]: + for x in e.get("refused") or []: + refused[x["reason"] if isinstance(x, dict) else str(x)] += 1 + notes += 1 if e.get("exhausted_note") else 0 + cats = sorted({r["_task"]["category"] for r in rows}) + tmpl: dict = {} + for r in rows: + t = template_of(r["_task"]) or r["_id"] + d = tmpl.setdefault(t, {"tasks": 0, "baseline_success": 0, "arm_success": 0}) + d["tasks"] += 1 + d["baseline_success"] += int(r["A"]["judge"]["success"]) + d["arm_success"] += int(r["B"]["judge"]["success"]) + return { + "expansion_tasks": expansion_figures(exp), + "by_expansion_kind": {k: expansion_figures([r for r in exp if expansion_kind(r["_task"]) == k]) for k in kinds}, + "trigger_counts": dict(sorted(trig.items())), "trigger_outcomes": dict(sorted(outcome.items())), + "refusals_by_reason": dict(sorted(refused.items())), + "duplicate_triggers": outcome.get("duplicate_trigger", 0), + "suppressed_n1_n2": outcome.get("N1_policy_denied", 0) + outcome.get("N2_approval_required", 0), + "cap_exhausted_notes": notes, + "negative_controls": negative_controls(recs), + "success_by_category": {c: {"baseline": sum(1 for r in rows if r["_task"]["category"] == c and r["A"]["judge"]["success"]), + "arm": sum(1 for r in rows if r["_task"]["category"] == c and r["B"]["judge"]["success"]), + "n": sum(1 for r in rows if r["_task"]["category"] == c)} for c in cats}, + "success_by_template": dict(sorted(tmpl.items())), + "infra_failures": sum(1 for r in recs if r["metrics"]["infra_failure"]), + } + + +def campaign_rows(run: dict, arm: str) -> tuple: + base, cond = ARMS[arm] + rows, recs = [], [] + for tid in sorted(run["receipts"]): + rc = run["receipts"][tid] + t = run["tasks"].get(tid) + if t is None or base not in rc or cond not in rc: + continue + row = {"A": rc[base], "B": rc[cond], "_task": t, "_id": tid} + for c in (row["A"], row["B"]): + c["task_def"] = t + rows.append(row) + recs.append(rc[cond]) + return rows, recs + + +def campaign_arm(run: dict, arm: str) -> dict: + rows, recs = campaign_rows(run, arm) + expected = len(run["tasks"]) + g = gates(rows, expected) + out = {"baseline": ARMS[arm][0], "condition": ARMS[arm][1], "gates": g, **arm_extras(rows, recs)} + if arm == "4": + bad = sorted(r["_id"] for r in rows for c in ("A", "B") if r[c].get("reasoning", {}).get("invalid_for_arm4")) + out["reasoning_present_in_arm4_runs"] = bad + if bad: # section 4: such a run is invalid for arm 4 + g["overall"] = "INVALID" + return out + + +def flags_of(gates_: dict) -> dict: + return {k: gates_[k]["pass"] for k in CRITERIA} + + +def build_campaign(gate_dir: Path, stab_dirs: list, tasks_dir: Path) -> dict: + runs = {"gate": load_run(gate_dir, tasks_dir)} + labels = {"gate": gate_dir.name} + for i, d in enumerate(stab_dirs): + runs[f"stability{i + 1}"] = load_run(d, tasks_dir) + labels[f"stability{i + 1}"] = d.name + out: dict = {"kind": "interplane_bench_campaign_summary", "gate_seed_dir": labels["gate"], + "stability_dirs": [labels[k] for k in labels if k != "gate"], "arms": {}} + out["blocks"] = {k: {"seed": (r["manifest"].get("campaign") or {}).get("seed"), + "frozen_digests_match": (r["manifest"].get("corpus") or {}).get("match"), + "latency_valid": (r["manifest"].get("latency_validity") or {}).get("valid"), + "latency_invalid_reasons": (r["manifest"].get("latency_validity") or {}).get("reasons"), + "identity_digest": (r["manifest"].get("deterministic_identity") or {}).get("identity_digest")} + for k, r in runs.items()} + for arm in sorted(ARMS): + a = campaign_arm(runs["gate"], arm) + base_flags = flags_of(a["gates"]) + stab, flips = {}, [] + for k in runs: + if k == "gate": + continue + ga = campaign_arm(runs[k], arm)["gates"] + f = flags_of(ga) + changed = sorted(c for c in CRITERIA if f[c] != base_flags[c]) + stab[k] = {"flags": f, "overall": ga["overall"], "flipped": changed} + flips += changed + a["gate_flags"] = base_flags + a["stability"] = stab + a["fragile"] = (bool(flips) if stab else None) + a["verdict"] = a["gates"]["overall"] + (" (fragile)" if a["fragile"] else "") + out["arms"][arm] = a + # secondary comparisons (reported, not gated): B2, B3 and B4 against B1, seed 42 + sec = {} + rc = runs["gate"]["receipts"] + for arm in ("2", "3", "4"): + cond = ARMS[arm][1] + tids = sorted(t for t in rc if "B1" in rc[t] and cond in rc[t] and t in runs["gate"]["tasks"]) + exp = [t for t in tids if runs["gate"]["tasks"][t]["category"] == "expansion"] + sec[f"{cond}_vs_B1"] = { + "tasks": len(tids), "success_B1": sum(1 for t in tids if rc[t]["B1"]["judge"]["success"]), + f"success_{cond}": sum(1 for t in tids if rc[t][cond]["judge"]["success"]), + "expansion_tasks_covered_final_B1": sum(1 for t in exp if not rc[t]["B1"]["metrics"]["missing_required_final"]), + f"expansion_tasks_covered_final_{cond}": sum(1 for t in exp if not rc[t][cond]["metrics"]["missing_required_final"])} + out["secondary_vs_B1"] = sec + return out + + +def campaign_md(summary: dict) -> str: + L = ["# 0.2x campaign summary", "", + f"Gate seed block `{summary['gate_seed_dir']}`; stability blocks {', '.join('`' + d + '`' for d in summary['stability_dirs']) or 'none'}. " + "The gate verdict uses seed 42 only; a gate criterion that flips under seed 43 or 44 labels the arm fragile (PROTOCOL-0.2x.md section 8).", "", + "## Blocks", "", "| block | seed | frozen digests match | latency valid |", "|---|---|---|---|"] + for k, b in summary["blocks"].items(): + L.append(f"| {k} | {fmt(b['seed'])} | {fmt(b['frozen_digests_match'])} | {fmt(b['latency_valid'])} |") + L += ["", "## Gates (seed 42)", "", "| arm | pair | T | S | O1 | O2 | O2a | O2b | verdict |", "|---|---|---|---|---|---|---|---|---|"] + for arm, a in summary["arms"].items(): + g, e = a["gates"], a["expansion_tasks"] + s = g["S"] + L.append(f"| {arm} | {a['baseline']} vs {a['condition']} | {fmt(g['T']['value'])} ({fmt(g['T']['pass'])}) | " + f"theta {fmt(s.get('theta'))}, CI low {fmt(s['ci95'][0]) if 'ci95' in s else 'n/a'} ({fmt(s['pass'])}) | " + f"{fmt(g['O1']['rate_covered'])} ({fmt(g['O1']['pass'])}) | {e['O2_recovered_within_1']} of {e['tasks']} ({fmt(g['O2']['pass'])}) | " + f"{e['O2a_trigger_fired']} of {e['tasks']} | {e['O2b_recovered_given_trigger']} of {e['O2a_trigger_fired']} | **{a['verdict']}** |") + L += ["", "T is the median of 1 - arm/baseline per-round tool-schema tokens (threshold 0.70). S is the paired success delta with its Newcombe " + "method-10 lower bound (threshold -0.10). O1 needs 0.95. O2, O2a and O2b are counts over the 24 expansion tasks (O2 needs 22).", ""] + for arm, a in summary["arms"].items(): + L += [f"## Arm {arm}: {a['baseline']} vs {a['condition']}", "", + f"Pairs {a['gates']['n_pairs']} of {a['gates']['expected_qual_pairs']}. Infra failures on the arm side: {a['infra_failures']}.", ""] + if a["stability"]: + L.append("Stability: " + "; ".join(f"{k} flipped {', '.join(v['flipped']) or 'nothing'}" for k, v in a["stability"].items()) + f". Fragile: {fmt(a['fragile'])}.") + else: + L.append("Stability blocks not supplied: fragile label not evaluated.") + L += ["", "| expansion kind | tasks | O1 covered | O2 within 1 | O2a | O2b |", "|---|---|---|---|---|---|"] + for k, f in a["by_expansion_kind"].items(): + L.append(f"| {k} | {f['tasks']} | {f['O1_covered_final']} | {f['O2_recovered_within_1']} | {f['O2a_trigger_fired']} | {f['O2b_recovered_given_trigger']} |") + nc = a["negative_controls"] + L += ["", f"Triggers {a['trigger_counts'] or 'none'}; outcomes {a['trigger_outcomes'] or 'none'}; refusals {a['refusals_by_reason'] or 'none'}; " + f"duplicates {a['duplicate_triggers']}; suppressed N1/N2 {a['suppressed_n1_n2']}; cap-exhausted notes {a['cap_exhausted_notes']}.", + f"Negative controls (must be zero for arm 3): executions of denied or pending calls {nc['executions_of_denied_or_pending_calls']}, " + f"expansions fired by a denied or pending call {nc['expansions_fired_by_denied_or_pending_call']}."] + if "reasoning_present_in_arm4_runs" in a: + L.append(f"Arm 4 runs with reasoning present (invalid): {len(a['reasoning_present_in_arm4_runs'])}.") + L += ["", "| category | baseline | arm | n |", "|---|---|---|---|"] + for c, v in a["success_by_category"].items(): + L.append(f"| {c} | {v['baseline']} | {v['arm']} | {v['n']} |") + L.append("") + L += ["## Secondary comparisons against B1 (reported, not gated)", ""] + for k, v in summary["secondary_vs_B1"].items(): + L.append(f"- {k}: " + ", ".join(f"{a} {b}" for a, b in v.items())) + L += ["", "Results per template are in `campaign-summary.json` (`success_by_template`).", ""] + return "\n".join(L) + + +def write_campaign(summary: dict, out_dir: Path) -> None: + out_dir.mkdir(parents=True, exist_ok=True) + (out_dir / "campaign-summary.json").write_text(json.dumps(rnd(summary), indent=2, sort_keys=True, ensure_ascii=False) + "\n", encoding="utf-8") + (out_dir / "campaign-summary.md").write_text(campaign_md(rnd(summary)), encoding="utf-8") + + def main(argv=None) -> int: ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) ap.add_argument("run_dir") ap.add_argument("--out", help="output directory (default: the run directory)") - ap.add_argument("--tasks-dir", default=str(BENCH / "tasks")) + ap.add_argument("--tasks-dir", default=None, help="default: bench/tasks, or bench/heldout-0.2x/tasks with --campaign") + ap.add_argument("--campaign", action="store_true", help="0.2x seven-condition analysis; run_dir is the seed 42 block") + ap.add_argument("--stability", default="", help="with --campaign: comma-separated seed 43 and 44 block directories") ap.add_argument("--exclude", default="", help="comma-separated qual task ids for a labelled sensitivity section") ap.add_argument("--exclude-reason", default="") args = ap.parse_args(argv) run_dir = Path(args.run_dir) - summary = build(run_dir, Path(args.tasks_dir), args.exclude.split(","), args.exclude_reason) + if args.campaign: + tdir = Path(args.tasks_dir) if args.tasks_dir else HELDOUT_TASKS + summary = build_campaign(run_dir, [Path(x) for x in args.stability.split(",") if x], tdir) + write_campaign(summary, Path(args.out) if args.out else run_dir) + return 0 + summary = build(run_dir, Path(args.tasks_dir or BENCH / "tasks"), args.exclude.split(","), args.exclude_reason) write_outputs(summary, Path(args.out) if args.out else run_dir) return 0 diff --git a/bench/tools/run_bench.py b/bench/tools/run_bench.py index 2935535..61878c2 100644 --- a/bench/tools/run_bench.py +++ b/bench/tools/run_bench.py @@ -127,11 +127,19 @@ def write_json(path: Path, obj) -> None: # ------------------------------------------------------------------------------- backend client class Client: - def __init__(self, endpoint: str, model: str, timeout: float, seed: int, temperature: float, max_tokens: int): + def __init__(self, endpoint: str, model: str, timeout: float, seed: int, temperature: float, max_tokens: int, + reasoning_field: str = "reasoning_effort"): self.endpoint, self.model, self.timeout = endpoint.rstrip("/"), model, timeout self.seed, self.temperature, self.max_tokens = seed, temperature, max_tokens + self.reasoning_field = reasoning_field - def chat(self, messages: list, tools, max_tokens=None) -> tuple: + def reasoning_off_fields(self) -> dict: + """The request-body field that turns reasoning off (PROTOCOL-0.2x.md section 4, arm 4).""" + if self.reasoning_field == "chat_template_kwargs": + return {"chat_template_kwargs": {"enable_thinking": False}} + return {"reasoning_effort": "none"} + + def chat(self, messages: list, tools, max_tokens=None, reasoning_off: bool = False) -> tuple: body = { "model": self.model, "messages": messages, @@ -141,6 +149,8 @@ class Client: } if tools is not None: body["tools"] = tools + if reasoning_off: + body.update(self.reasoning_off_fields()) data = jcs(body).encode("utf-8") headers = {"Content-Type": "application/json"} key = os.environ.get("INTERPLANE_PROBE_API_KEY") @@ -168,10 +178,10 @@ class LiveCounter: def __init__(self, client: Client): self.client, self.cache, self.requests = client, {}, 0 - def count_prompt(self, messages: list, tools) -> int: - key = digest_of([messages, tools]) + def count_prompt(self, messages: list, tools, reasoning_off: bool = False) -> int: + key = digest_of([messages, tools, reasoning_off] if reasoning_off else [messages, tools]) if key not in self.cache: - resp, _, _ = self.client.chat(messages, tools, max_tokens=1) + resp, _, _ = self.client.chat(messages, tools, max_tokens=1, reasoning_off=reasoning_off) self.requests += 1 n = (resp.get("usage") or {}).get("prompt_tokens") if not isinstance(n, int): @@ -266,6 +276,33 @@ def raw_ok(raw: dict) -> bool: RUNTIME_POLICY = "runtime-v1" EXPANSION_POLICIES = ("0.2", RUNTIME_POLICY) +# PROTOCOL-0.2x.md section 4: one id per condition. The id fixes family (judge, rendering), prompt +# addendum, reasoning switch and expansion policy. "B" is the 0.2 id (policy from --expansion-policy). +CAMPAIGN_CONDITIONS = ("A", "A2", "A4", "B1", "B2", "B3", "B4") # canonical order, section 8 +CONDITION_IDS = ("A", "B") + CAMPAIGN_CONDITIONS[1:] +_SPECS = { + "A": (False, False, None), "A2": (True, False, None), "A4": (False, True, None), + "B": (False, False, "flag"), "B1": (False, False, "0.2"), "B2": (True, False, "0.2"), + "B3": (False, False, RUNTIME_POLICY), "B4": (False, True, "0.2"), +} +REASONING_FIELDS = ("reasoning_effort", "chat_template_kwargs") +ADDENDUM_REL = Path("prompts") / "discovery-addendum.md" # under the held-out root +HELDOUT_SEEDS = (42, 43, 44) +CAMPAIGN_CORPUS = "0.2x" + + +def condition_spec(cx: dict, cond: str) -> dict: + addendum, off, policy = _SPECS[cond] + if policy == "flag": + policy = cx["expansion_policy"] + return {"id": cond, "family": cond[0], "addendum": addendum, "reasoning_off": off, + "expansion_policy": policy if cond[0] == "B" else None} + + +def rotated(conds: list, idx: int) -> list: + """Section 8: canonical order rotated left by (task index mod len). Two conditions give the 0.2 rule.""" + k = idx % len(conds) + return list(conds[k:]) + list(conds[:k]) SCHEMA_BUDGET_RATIO = 0.30 DISCOVER_LIMIT = 8 MISSING_CODES = ("capability_not_found", "stale_capability") @@ -372,7 +409,7 @@ class RuntimeExpansion: def render(by_name: dict, names: list, cond: str) -> list: tools = openai_tools_renderer([by_name[n] for n in names]) - return tools + [DISCOVERY_SPEC] if cond == "B" else tools + return tools + [DISCOVERY_SPEC] if cond[0] == "B" else tools def parse_args_of(tc) -> tuple: @@ -406,19 +443,22 @@ def run_condition(cx: dict, task: dict, cond: str, run_id: str) -> dict: def _run(cx: dict, task: dict, cond: str, run_id: str, ws: str) -> dict: client, catalog, by_name = cx["client"], cx["catalog"], cx["by_name"] + spec = condition_spec(cx, cond) + fam, reasoning_off = spec["family"], spec["reasoning_off"] + system_prompt = cx["system_prompt_addendum"] if spec["addendum"] else cx["system_prompt"] stubs = {cap: json.loads((cx["bench"] / s["path"]).read_text(encoding="utf-8")) for cap, s in task["stub_results"].items()} - sim = sim_backends.SimSession(ws, task["workspace_fixture"], cx["backend_registry"]) if cx["backends"] == "sim-1" else None + sim = sim_backends.SimSession(ws, task["workspace_fixture"], cx["backend_registry"], stores_dir=cx["stores_dir"]) if cx["backends"] == "sim-1" else None authority = BenchAuthority(ws, task, stubs, sim=sim) if not authority.available: raise SystemExit("Odysseus is not importable: set ODYSSEUS_SRC") pipe = Pipeline(make_registry(), mapping_table(), authority) trace_id = f"bench-{run_id}-{task['id']}-{cond}" - base_messages = [{"role": "system", "content": cx["system_prompt"]}, {"role": "user", "content": task["user_request"]}] + base_messages = [{"role": "system", "content": system_prompt}, {"role": "user", "content": task["user_request"]}] messages = copy.deepcopy(base_messages) all_names = [c.name for c in catalog.capabilities] selection = None - if cond == "B": + if fam == "B": selection, _ = select(catalog, task["requested_domains"], always_include=ALWAYS_INCLUDE, renderer=openai_tools_renderer) @@ -426,7 +466,7 @@ def _run(cx: dict, task: dict, cond: str, run_id: str, ws: str) -> dict: return all_names if selection is None else [e["name"] for e in selection.selected] rt = None - if cond == "B" and cx.get("expansion_policy") == RUNTIME_POLICY: + if fam == "B" and spec["expansion_policy"] == RUNTIME_POLICY: rt = RuntimeExpansion(catalog, by_name, cx["full_tools_bytes"], lambda names: len(jcs(render(by_name, names, "B")).encode("utf-8"))) @@ -441,7 +481,7 @@ def _run(cx: dict, task: dict, cond: str, run_id: str, ws: str) -> dict: round_tools.append(tools) coverage_trace.append({"round": turn + 1, "effective_expansions": n_eff, "covered": bench_eval.covered(task, names)}) try: - resp, ms, req_digest = client.chat(messages, tools) + resp, ms, req_digest = client.chat(messages, tools, reasoning_off=reasoning_off) except InfraError as err: infra_error, ended = str(err), "infra_failure" round_tools.pop() @@ -452,7 +492,7 @@ def _run(cx: dict, task: dict, cond: str, run_id: str, ws: str) -> dict: usage = resp.get("usage") or {} orig = msg.get("tool_calls") if isinstance(msg.get("tool_calls"), list) else [] disc_idx = [i for i, tc in enumerate(orig) - if cond == "B" and isinstance(tc, dict) and isinstance(tc.get("function"), dict) + if fam == "B" and isinstance(tc, dict) and isinstance(tc.get("function"), dict) and tc["function"].get("name") == DISCOVERY] filt_idx = [i for i in range(len(orig)) if i not in disc_idx] if disc_idx: @@ -472,7 +512,7 @@ def _run(cx: dict, task: dict, cond: str, run_id: str, ws: str) -> dict: "tools_bytes": len(jcs(tools).encode("utf-8")), "exposed_tools_count": len(tools), "exposed_caps_count": len(names), - "exposed_names": list(names) if cond == "B" else None, + "exposed_names": list(names) if fam == "B" else None, "prompt_tokens": usage.get("prompt_tokens"), "completion_tokens": usage.get("completion_tokens"), "latency_ms": ms, @@ -522,7 +562,7 @@ def _run(cx: dict, task: dict, cond: str, run_id: str, ws: str) -> dict: tool_msgs[i] = tm elif i in recs: cap = recs[i]["capability"] - if cond == "B" and cap is not None and cap in by_name and cap not in set(current_names()): + if fam == "B" and cap is not None and cap in by_name and cap not in set(current_names()): try: selection = expand(selection, catalog, {"kind": "requested_excluded", "name": cap}) entry = selection.extra["expansions"][-1] @@ -583,6 +623,7 @@ def _run(cx: dict, task: dict, cond: str, run_id: str, ws: str) -> dict: "rounds": rounds, "calls": calls, "expansions": [{k: v for k, v in e.items()} for e in expansion_events], "final_exposed_names": list(final_names), "coverage_trace": coverage_trace, "wall_ms": wall_ms, "selection": selection, "base_messages": base_messages, "_round_tools": round_tools, + "reasoning_off": reasoning_off, "system_prompt": system_prompt, "spec": spec, "trace_id": trace_id, "workspace_events": dict(authority.bench_events), "runtime_triggers": rt.log if rt is not None else None, } @@ -592,11 +633,12 @@ def measure_run_tokens(cx: dict, run: dict) -> None: """Outside the timed window: per-round tool-schema cost by prompt difference (memoized by digest).""" counter = cx["counter"] base_messages = run["base_messages"] - base = counter.count_prompt(base_messages, None) + off = run.get("reasoning_off", False) + base = counter.count_prompt(base_messages, None, off) run["base_context"] = base per_round = [] for tools in run["_round_tools"]: - per_round.append(max(counter.count_prompt(base_messages, tools) - base, 0)) + per_round.append(max(counter.count_prompt(base_messages, tools, off) - base, 0)) run["tool_schema_tokens"] = per_round @@ -629,8 +671,8 @@ def make_receipt(cx: dict, task: dict, cond: str, run: dict, attempt: int, prior if run["infra_failure"]: verdict = {"success": False, "infra_failure": True, "checks": [], "failed": ["infra_failure"]} else: - verdict = bench_eval.judge(task, cond, tr) - metrics = bench_eval.run_metrics(task, cond, run) + verdict = bench_eval.judge(task, cond[0], tr) + metrics = bench_eval.run_metrics(task, cond[0], run) sel = run["selection"] selection_block = None if sel is not None: @@ -639,21 +681,21 @@ def make_receipt(cx: dict, task: dict, cond: str, run: dict, attempt: int, prior d["kind"] = "selection" selection_block = {"round1": d, "round1_digest": selection_digest(r1), "final_digest": selection_digest(sel), "final_selected": [e["name"] for e in sel.selected]} - return { + rec = { "kind": "interplane_bench_receipt", "receipt_version": RECEIPT_VERSION, "run_id": run_id, "task": {"id": task["id"], "category": task["category"], "split": task["split"], "digest": file_sha(cx["tasks_dir"] / f"{task['id']}.json")}, "condition": cond, "attempt": attempt, "prior_infra_failures": prior, - "system_prompt_digest": text_sha(cx["system_prompt"]), + "system_prompt_digest": text_sha(run["base_messages"][0]["content"]), "user_request_digest": text_sha(task["user_request"]), "authority_profile": task["authority_profile"], "fixture": {"name": task["workspace_fixture"], "digest": cx["fixture_digests"][task["workspace_fixture"]]}, "generation": cx["generation"], - "discovery_tool": DISCOVERY if cond == "B" else None, + "discovery_tool": DISCOVERY if cond[0] == "B" else None, "selection": selection_block, "rounds": run["rounds"], "calls": run["calls"], "expansions": run["expansions"], **({"runtime_triggers": run["runtime_triggers"]} if run.get("runtime_triggers") is not None else {}), - "final_exposed_names": run["final_exposed_names"] if cond == "B" else None, + "final_exposed_names": run["final_exposed_names"] if cond[0] == "B" else None, "coverage_trace": run["coverage_trace"], "ended": run["ended"], "infra_error": run["infra_error"], "transcript": tr, "judge": verdict, "metrics": metrics, @@ -661,14 +703,30 @@ def make_receipt(cx: dict, task: dict, cond: str, run: dict, attempt: int, prior "measure": pair_meas, "timings": {"wall_ms": run["wall_ms"], "model_ms": sum(r["latency_ms"] for r in run["rounds"])}, } + if cx["campaign_mode"]: # 0.2x: extra receipt blocks; the 0.2 receipt layout stays unchanged + sp = run["spec"] + rec["condition_spec"] = {"id": cond, "family": sp["family"], "prompt_addendum": sp["addendum"], + "reasoning_off": sp["reasoning_off"], "expansion_policy": sp["expansion_policy"]} + present = sum(1 for r in run["rounds"] if r["reasoning_present"]) + rec["reasoning"] = {"off_requested": sp["reasoning_off"], + "field": cx["client"].reasoning_field if sp["reasoning_off"] else None, + "rounds_with_reasoning": present, + "invalid_for_arm4": bool(sp["reasoning_off"] and present)} + return rec def run_pair(cx: dict, task: dict, order: list, run_id: str, out: Path, conds: list) -> dict: prior: list = [] runs: dict = {} - for attempt in range(1, 4): - runs = {} + campaign = cx["campaign_mode"] + # 0.2: up to 3 whole-pair attempts. Campaign (PROTOCOL-0.2x.md section 6): a run with an + # infrastructure failure is re-run once, only the failed conditions. + for attempt in range(1, 3 if campaign else 4): + if not campaign: + runs = {} for cond in order: + if campaign and cond in runs and not runs[cond]["infra_failure"]: + continue runs[cond] = run_condition(cx, task, cond, run_id) bad = [c for c in order if runs[c]["infra_failure"]] if not bad: @@ -776,8 +834,13 @@ def build_identity(cx: dict, tasks: list) -> dict: } if cx["backends"] != "reference": # the 0.2 reference identity stays byte-identical ident["backends"] = backends_identity(cx) - if cx["expansion_policy"] != "0.2": - ident["expansion_policy"] = {"name": cx["expansion_policy"], "schema_budget_ratio": SCHEMA_BUDGET_RATIO, + if cx["campaign_mode"]: + ident["campaign"] = {"corpus": cx["corpus"], "conditions": {c: condition_spec(cx, c) for c in cx["conditions"]}, + "addendum_prompt_digest": text_sha(cx["system_prompt_addendum"]), + "reasoning_off_field": cx["client"].reasoning_off_fields()} + if cx["expansion_policy"] != "0.2" or "B3" in cx["conditions"]: + ident["expansion_policy"] = {"name": RUNTIME_POLICY if "B3" in cx["conditions"] else cx["expansion_policy"], + **({"applies_to": ["B3"]} if "B3" in cx["conditions"] else {}), "schema_budget_ratio": SCHEMA_BUDGET_RATIO, "full_tools_bytes": cx["full_tools_bytes"], "discover_limit": DISCOVER_LIMIT, "triggers": ["T1", "T2", "T3"], "suppressed": sorted(SUPPRESSED.values())} ident["identity_digest"] = digest_of(ident) @@ -785,21 +848,30 @@ def build_identity(cx: dict, tasks: list) -> dict: def backends_identity(cx: dict) -> dict: - stores = sorted(sim_backends.STORES_DIR.glob("*.json")) + stores = sorted(cx["stores_dir"].glob("*.json")) return {"mode": cx["backends"], "registry_sha256": file_sha(sim_backends.BACKENDS_PATH), "sim_backends_sha256": file_sha(Path(sim_backends.__file__)), "stores": {p.name: file_sha(p) for p in stores}} -def make_cx(args, tasks_dir: Path) -> dict: +def make_cx(args, tasks_dir: Path, root: Path = BENCH, conds=None) -> dict: + """``root`` is the corpus root (task fixture and stub paths are relative to it): bench/ for the 0.2 + corpus, bench/heldout-0.2x for the held-out set. system.md always comes from bench/.""" catalog = catalog_with_domains() sp = (BENCH / "prompts" / "system.md").read_text(encoding="utf-8") + campaign = bool(getattr(args, "campaign_mode", False)) + sp2 = None + if campaign: + sp2 = sp.rstrip("\n") + "\n\n" + (BENCH / "heldout-0.2x" / ADDENDUM_REL).read_text(encoding="utf-8") fixtures = sorted({(t["workspace_fixture"]) for t in load_tasks(tasks_dir, "all", [])}) - client = Client(args.endpoint, args.model, args.timeout, args.seed, args.temperature, args.max_tokens) + client = Client(args.endpoint, args.model, args.timeout, args.seed, args.temperature, args.max_tokens, + getattr(args, "reasoning_field", "reasoning_effort")) return { - "bench": BENCH, "tasks_dir": tasks_dir, "catalog": catalog, "by_name": {c.name: c for c in catalog.capabilities}, + "bench": root, "corpus": getattr(args, "corpus", "0.2"), "campaign_mode": campaign, + "conditions": list(conds or []), "system_prompt_addendum": sp2, + "stores_dir": (root / "stores") if root != BENCH else sim_backends.STORES_DIR, "tasks_dir": tasks_dir, "catalog": catalog, "by_name": {c.name: c for c in catalog.capabilities}, "system_prompt": sp, "client": client, "counter": LiveCounter(client), "max_rounds": args.max_rounds, - "fixture_digests": {f: tree_digest(BENCH / f) for f in fixtures}, + "fixture_digests": {f: tree_digest(root / f) for f in fixtures}, "backends": args.backends, "expansion_policy": args.expansion_policy, "full_tools_bytes": len(jcs(openai_tools_renderer(catalog.capabilities)).encode("utf-8")), @@ -809,10 +881,11 @@ def make_cx(args, tasks_dir: Path) -> dict: } -def check_corpus(strict: bool) -> dict: +def check_corpus(strict: bool, corpus: str = "0.2") -> dict: import validate # bench/tools/validate.py - frozen, now_d = validate.read_digest_file(), validate.digests() + cfg = validate.CORPORA[corpus] + frozen, now_d = validate.read_digest_file(cfg), validate.digests(cfg) for k in ("tasks_digest", "inputs_digest", "protocol_sha256"): if frozen.get(k) != now_d.get(k): if strict: @@ -821,25 +894,49 @@ def check_corpus(strict: bool) -> dict: "match": all(frozen.get(k) == now_d.get(k) for k in ("tasks_digest", "inputs_digest", "protocol_sha256"))} -def token_stability(cx: dict, task: dict) -> dict: +def token_stability(cx: dict, task: dict, reasoning_off: bool = False) -> dict: """Same (messages, tools) counted twice must give the same number (no prompt-cache undercount).""" msgs = [{"role": "system", "content": cx["system_prompt"]}, {"role": "user", "content": task["user_request"]}] tools = openai_tools_renderer(cx["catalog"].capabilities) c = LiveCounter(cx["client"]) - a = c.count_prompt(msgs, tools) + a = c.count_prompt(msgs, tools, reasoning_off) c.cache.clear() - b = c.count_prompt(msgs, tools) + b = c.count_prompt(msgs, tools, reasoning_off) c.cache.clear() - base1 = c.count_prompt(msgs, None) - return {"task": task["id"], "tools_count_1": a, "tools_count_2": b, "stable": a == b, "base_context": base1} + base1 = c.count_prompt(msgs, None, reasoning_off) + out = {"task": task["id"], "tools_count_1": a, "tools_count_2": b, "stable": a == b, "base_context": base1} + return {**out, "reasoning_off": True} if reasoning_off else out + + +def gpu_report() -> dict: + """PROTOCOL-0.2x.md section 8: compute processes and other inference or training processes.""" + apps = sh("nvidia-smi --query-compute-apps=pid,process_name,used_gpu_memory --format=csv") + procs = [ln for ln in sh("pgrep -af 'ollama runner|llama-server|sglang|vllm|train'").splitlines() + if "pgrep" not in ln and not ln.startswith(str(os.getpid()))] + foreign = [ln for ln in apps.splitlines()[1:] if ln.strip() and "ollama" not in ln] + runners = [ln for ln in procs if "ollama runner" in ln] + other = [ln for ln in procs if "ollama runner" not in ln] + reasons = (["another process holds the GPU"] if foreign else []) + (["more than one ollama runner"] if len(runners) > 1 else []) \ + + (["another inference or training process is running"] if other else []) + text = f"{now()}\n{apps}\npgrep:\n" + "\n".join(procs) + "\n" + return {"text": text, "clear": not reasons, "reasons": reasons} # ------------------------------------------------------------------------------- main def main(argv=None) -> int: ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) - ap.add_argument("--tasks", choices=["dev", "qual", "all"], default="dev") - ap.add_argument("--condition", choices=["A", "B", "both"], default="both") + ap.add_argument("--tasks", choices=["dev", "qual", "all"], default=None, + help="default: dev for corpus 0.2, qual for corpus 0.2x") + ap.add_argument("--corpus", choices=["0.2", CAMPAIGN_CORPUS], default="0.2", + help="0.2 = bench/tasks; 0.2x = the held-out set bench/heldout-0.2x (PROTOCOL-0.2x.md); needs --backends sim-1") + ap.add_argument("--condition", choices=list(CONDITION_IDS) + ["both", "all"], default="both", + help="A/B/both = 0.2. A2, A4, B1..B4 = the PROTOCOL-0.2x.md conditions; all = the seven, in order " + "A A2 A4 B1 B2 B3 B4 rotated left by (task index mod 7). B3 is arm 3 (runtime-v1), " + "A2/B2 add the discovery addendum, A4/B4 turn reasoning off") + ap.add_argument("--reasoning-field", choices=list(REASONING_FIELDS), default="reasoning_effort", + help="request field that turns reasoning off for A4/B4: reasoning_effort=none (Ollama) or " + "chat_template_kwargs.enable_thinking=false (SGLang, llama.cpp)") ap.add_argument("--endpoint", default="http://127.0.0.1:11434/v1") ap.add_argument("--model", default="qwen3.5:9b") ap.add_argument("--out", required=True) @@ -853,7 +950,7 @@ def main(argv=None) -> int: ap.add_argument("--resume", action="store_true") ap.add_argument("--prepare", action="store_true", help="write manifest.json (identity) and exit; no model request") ap.add_argument("--no-warmup", action="store_true") - ap.add_argument("--tasks-dir", default=str(BENCH / "tasks")) + ap.add_argument("--tasks-dir", default=None, help="default: the corpus's tasks folder") ap.add_argument("--allow-nonfrozen", action="store_true", help="offline tests with synthetic tasks only") ap.add_argument("--backends", choices=["reference", "sim-1"], default="reference", help="reference = 0.2 behaviour (only read_file/ls/glob/grep and task stubs execute); " @@ -865,7 +962,24 @@ def main(argv=None) -> int: out = Path(args.out) run_id = out.name.rstrip("/") - tasks_dir = Path(args.tasks_dir) + heldout = args.corpus == CAMPAIGN_CORPUS + root = BENCH / "heldout-0.2x" if heldout else BENCH + tasks_dir = Path(args.tasks_dir) if args.tasks_dir else root / "tasks" + args.tasks = args.tasks or ("qual" if heldout else "dev") + args.campaign_mode = heldout or args.condition not in ("A", "B", "both") + if args.campaign_mode: + if args.backends != "sim-1": + raise SystemExit("0.2x conditions and the held-out corpus need --backends sim-1 (PROTOCOL-0.2x.md section 10)") + if args.expansion_policy != "0.2": + raise SystemExit("--expansion-policy is fixed by the condition id in 0.2x (B3 = runtime-v1, others 0.2)") + if heldout and args.seed not in HELDOUT_SEEDS and not args.allow_nonfrozen: + raise SystemExit(f"held-out runs use seeds {list(HELDOUT_SEEDS)} (PROTOCOL-0.2x.md section 8)") + if args.condition == "both": + conds = list(CAMPAIGN_CONDITIONS[:1]) + ["B"] if not args.campaign_mode else list(CAMPAIGN_CONDITIONS) + elif args.condition == "all": + conds = list(CAMPAIGN_CONDITIONS) + else: + conds = [args.condition] src = os.environ.get("ODYSSEUS_SRC", "") ody = _odysseus.load() if ody is None or not src: @@ -875,10 +989,10 @@ def main(argv=None) -> int: ody_commit = sh(f"git -C {src} rev-parse HEAD") if not ody_commit.startswith(ODYSSEUS_COMMIT) and not args.allow_nonfrozen: raise SystemExit(f"Odysseus is at {ody_commit}, expected {ODYSSEUS_COMMIT}") - cx = make_cx(args, tasks_dir) + cx = make_cx(args, tasks_dir, root, conds) if text_sha(cx["system_prompt"]) != "sha256:" + FROZEN_PROMPT_SHA and not args.allow_nonfrozen: raise SystemExit("prompts/system.md does not match the digest every task pins") - corpus = check_corpus(strict=not args.allow_nonfrozen) + corpus = check_corpus(not args.allow_nonfrozen, args.corpus) tasks = load_tasks(tasks_dir, args.tasks, [s for s in args.only.split(",") if s]) if not tasks: raise SystemExit("no tasks selected") @@ -893,7 +1007,6 @@ def main(argv=None) -> int: identity = build_identity(cx, tasks) probe = json.loads(Path(args.probe).read_text(encoding="utf-8")) env = environment(args.endpoint, args.model, src) - conds = ["A", "B"] if args.condition == "both" else [args.condition] manifest_path = out / "manifest.json" manifest = { "kind": "interplane_bench_manifest", "manifest_version": "0.2.0", "run_id": run_id, @@ -915,9 +1028,16 @@ def main(argv=None) -> int: "corpus": corpus, "system_prompt_digest": identity["system_prompt_digest"], "generation": cx["generation"], "backends": identity.get("backends", {"mode": "reference"}), "expansion_policy": identity.get("expansion_policy", {"name": "0.2"}), - "order_rule": "tasks in id order; A first for even 0-based index, B first for odd (PROTOCOL-0.2.md section 2)", + "order_rule": ("tasks in id order; canonical condition order A A2 A4 B1 B2 B3 B4 rotated left by (task index mod 7) " + "(PROTOCOL-0.2x.md section 8)" if args.campaign_mode else + "tasks in id order; A first for even 0-based index, B first for odd (PROTOCOL-0.2.md section 2)"), "deterministic_identity": identity, } + if args.campaign_mode: + manifest["campaign"] = { + "corpus": args.corpus, "seed": args.seed, "conditions": {c: condition_spec(cx, c) for c in conds}, + "reasoning_off_field": cx["client"].reasoning_off_fields(), "addendum_prompt_digest": text_sha(cx["system_prompt_addendum"]), + "seeds_protocol": list(HELDOUT_SEEDS), "gate_seed": HELDOUT_SEEDS[0]} if manifest_path.exists(): old = json.loads(manifest_path.read_text(encoding="utf-8")) if old.get("deterministic_identity", {}).get("identity_digest") != identity["identity_digest"]: @@ -935,14 +1055,25 @@ def main(argv=None) -> int: stoch = manifest.get("stochastic_execution", {}) stoch["started_at"] = stoch.get("started_at") or now() samples = [load_snapshot()] - stoch["token_stability"] = token_stability(cx, tasks[0]) + gpu0 = gpu_report() if args.campaign_mode else None + if gpu0 is not None: + out.mkdir(parents=True, exist_ok=True) + (out / "gpu_at_start.txt").write_text(gpu0["text"], encoding="utf-8") + modes = sorted({condition_spec(cx, c)["reasoning_off"] for c in conds}) # counted the way each run is + stoch["token_stability"] = token_stability(cx, tasks[0], modes[0]) + if len(modes) == 2: + stoch["token_stability_reasoning_off"] = token_stability(cx, tasks[0], True) if not args.no_warmup and not manifest.get("stochastic_execution", {}).get("warmup"): - warm = next((t for t in load_tasks(tasks_dir, "dev", ["filesystem-001"])), None) + # one untimed dev-task run per seed block (section 8); the held-out set has no dev task + wcx = make_cx(args, BENCH / "tasks", BENCH, conds) if heldout else cx + wtasks_dir = BENCH / "tasks" if heldout else tasks_dir + wcond = "B1" if args.campaign_mode else "B" + warm = next((t for t in load_tasks(wtasks_dir, "dev", ["filesystem-001"])), None) if warm is not None: t0 = time.monotonic() try: - run_condition(cx, warm, "B", run_id + "-warmup") - stoch["warmup"] = {"task": warm["id"], "condition": "B", "wall_ms": int((time.monotonic() - t0) * 1000), "timed": False} + run_condition(wcx, warm, wcond, run_id + "-warmup") + stoch["warmup"] = {"task": warm["id"], "condition": wcond, "wall_ms": int((time.monotonic() - t0) * 1000), "timed": False} except InfraError as err: stoch["warmup"] = {"task": warm["id"], "error": str(err)} manifest["stochastic_execution"] = stoch @@ -955,7 +1086,7 @@ def main(argv=None) -> int: rpaths = [out / "receipts" / f"{task['id']}.{c}.json" for c in conds] if args.resume and all(p.exists() for p in rpaths): continue - order = list(conds) if len(conds) == 1 else (["A", "B"] if idx % 2 == 0 else ["B", "A"]) + order = rotated(conds, idx) samples.append(load_snapshot()) res = run_pair(cx, task, order, run_id, out, conds) done += 1 @@ -978,6 +1109,12 @@ def main(argv=None) -> int: "gpu_util_percent_max_sampled_at_pair_starts": max(utils + [old_load.get("gpu_util_percent_max_sampled_at_pair_starts") or 0]) if utils else None, "note": "sampled at start, before each pair, and at end; wall-clock is a reported metric and is affected by other GPU users", } + if gpu0 is not None: + gpu1 = gpu_report() + (out / "gpu_at_end.txt").write_text(gpu1["text"], encoding="utf-8") + manifest["latency_validity"] = { + "valid": gpu0["clear"] and gpu1["clear"], "reasons": sorted(set(gpu0["reasons"]) | set(gpu1["reasons"])), + "note": "section 8: an invalid block keeps its success and token figures; only latency is labelled invalid"} write_json(manifest_path, manifest) print(f"done: {done} pairs run; manifest {manifest_path}") return 0 diff --git a/bench/tools/test_analyze.py b/bench/tools/test_analyze.py index 9baa2b8..d3872c0 100644 --- a/bench/tools/test_analyze.py +++ b/bench/tools/test_analyze.py @@ -78,6 +78,122 @@ def write_run(out: Path) -> None: (out / "receipts" / f"{tid}.{cond}.json").write_text(json.dumps(receipt, indent=2, sort_keys=True) + "\n") +# ---------------------------------------------------------------- 0.2x campaign (seven conditions, three seeds) + +HELD = BENCH / "heldout-0.2x" / "tasks" +CONDS7 = ["A", "A2", "A4", "B1", "B2", "B3", "B4"] + + +def held_subset(tdir: Path) -> dict: + """Five real held-out tasks: one expansion task per kind, one denied, one filesystem.""" + allt = {t["id"]: t for t in (json.loads(p.read_text()) for p in sorted(HELD.glob("*.json")))} + pick = {} + for tid, t in allt.items(): + k = analyze.expansion_kind(t) if t["category"] == "expansion" else t["category"] + if k in ("named", "path", "nopath", "denied", "filesystem") and k not in pick: + pick[k] = tid + tdir.mkdir(parents=True, exist_ok=True) + for tid in pick.values(): + (tdir / f"{tid}.json").write_text(json.dumps(allt[tid])) + return {k: allt[v] for k, v in pick.items()} + + +def campaign_receipt(task: dict, cond: str, seed: int, rng: random.Random, recover: bool) -> dict: + fam = cond[0] + run = synth_run(task, fam, True, rng) + needs_exp = task["category"] == "expansion" and fam == "B" + if needs_exp and not recover: + run["expansions"] = [] + run["coverage_trace"] = [{"round": 1, "effective_expansions": 0, "covered": False}, {"round": 2, "effective_expansions": 0, "covered": False}] + run["final_exposed_names"] = [] + run["calls"][0].update(exposed=False) + run["calls"][0].update(index=0, executed=True) + if task["category"] == "denied": + run["calls"] = [{"round": 1, "index": 0, "tool": "manage_tokens", "capability": "manage_tokens", "decision": "denied", "status": "denied", + "error_code": "policy_denied", "discovery": False, "exposed": False, "executed": False}] + # the 0.2 mechanism (B1, B2, B4) also exposes after a denied call; runtime-v1 (B3) never does + run["expansions"] = ([{"round": 1, "call_index": 0, "trigger": "requested_excluded", "reason": "requested_excluded", + "added": ["manage_tokens"], "refused": []}] if cond in ("B1", "B2", "B4") else []) + tr = {"final_answer": run["final_answer"], + "calls": [{k: c[k] for k in ("round", "tool", "capability", "decision", "status", "error_code", "discovery")} for c in run["calls"]], + "expansions": [{"round": e["round"], "reason": e.get("reason"), "added": e["added"], "refused": e["refused"]} for e in run["expansions"]]} + rc = {"kind": "interplane_bench_receipt", "task": {"id": task["id"], "category": task["category"], "split": task["split"]}, "condition": cond, + "generation": {"seed": seed}, "rounds": run["rounds"], "calls": run["calls"], "expansions": run["expansions"], "transcript": tr, + "judge": bench_eval.judge(task, fam, tr), "metrics": bench_eval.run_metrics(task, fam, run), "measure": {}, + "tool_schema_tokens_per_round": run["tool_schema_tokens"], + "reasoning": {"off_requested": cond in ("A4", "B4"), "field": None, "rounds_with_reasoning": 0, "invalid_for_arm4": False}} + if cond == "B3" and needs_exp: + rc["runtime_triggers"] = [{"round": 1, "call_index": 0, "trigger": "T2", "name": "x", "outcome": "expanded" if recover else "refused"}] + if cond == "B3" and task["category"] == "denied": + rc["runtime_triggers"] = [{"round": 1, "call_index": 0, "trigger": "T2", "name": "manage_tokens", "outcome": "N1_policy_denied"}] + return rc + + +def write_campaign_block(out: Path, subset: dict, seed: int, recover: dict) -> None: + """recover: (cond, expansion kind) -> bool for this block; default True.""" + rng = random.Random(seed) + (out / "receipts").mkdir(parents=True, exist_ok=True) + (out / "manifest.json").write_text(json.dumps({"campaign": {"seed": seed}, "corpus": {"match": True}, "latency_validity": {"valid": True, "reasons": []}, + "deterministic_identity": {"identity_digest": f"sha256:synthetic-{seed}"}}, sort_keys=True) + "\n") + for k, t in subset.items(): + for cond in CONDS7: + rec = recover.get((cond, k), True) + (out / "receipts" / f"{t['id']}.{cond}.json").write_text(json.dumps(campaign_receipt(t, cond, seed, rng, rec), sort_keys=True) + "\n") + + +def test_campaign() -> None: + with tempfile.TemporaryDirectory() as td: + td = Path(td) + subset = held_subset(td / "tasks") + assert len(subset) == 5 + # seed 42: arm 3 (B3) recovers named and path but not nopath; arm 1 (B1) recovers nothing but tries on the named task + s42 = {("B3", "nopath"): False, ("B1", "named"): False, ("B1", "path"): False, ("B1", "nopath"): False} + # seed 43: B3 recovers nopath too (O2 flips); everything else as seed 42. seed 44 equals seed 42. + s43 = {k: v for k, v in s42.items() if k != ("B3", "nopath")} + for seed, rec in ((42, s42), (43, s43), (44, s42)): + write_campaign_block(td / f"s{seed}", subset, seed, rec) + args = ["--campaign", "--tasks-dir", str(td / "tasks"), "--stability", f"{td / 's43'},{td / 's44'}"] + analyze.main([str(td / "s42"), "--out", str(td / "o1"), *args]) + analyze.main([str(td / "s42"), "--out", str(td / "o2"), *args]) + for f in ("campaign-summary.json", "campaign-summary.md"): + assert (td / "o1" / f).read_bytes() == (td / "o2" / f).read_bytes(), f"{f} is not deterministic" + s = json.loads((td / "o1" / "campaign-summary.json").read_text()) + a1, a2, a3, a4 = (s["arms"][k] for k in "1234") + assert [a["condition"] for a in (a1, a2, a3, a4)] == ["B1", "B2", "B3", "B4"] and [a["baseline"] for a in (a1, a2, a3, a4)] == ["A", "A2", "A", "A4"] + # per-arm T, S, O1, O2 and the diagnostics O2a and O2b + assert a3["gates"]["T"]["pass"] is True and a3["gates"]["T"]["value"] > 0.9 + e3 = a3["expansion_tasks"] + assert (e3["tasks"], e3["O1_covered_final"], e3["O2_recovered_within_1"], e3["O2a_trigger_fired"], e3["O2b_recovered_given_trigger"]) == (3, 2, 2, 3, 2), e3 + assert a3["gates"]["O2"]["pass"] is False and a3["gate_flags"]["O2"] is False and a3["verdict"].startswith("FAIL") + e1 = a1["expansion_tasks"] + assert (e1["O2_recovered_within_1"], e1["O2a_trigger_fired"]) == (0, 0), e1 # B1 here neither recovered nor fired + assert a2["expansion_tasks"]["O2_recovered_within_1"] == 3 and a4["expansion_tasks"]["O2_recovered_within_1"] == 3 + # per expansion kind + assert a3["by_expansion_kind"]["nopath"]["O2_recovered_within_1"] == 0 and a3["by_expansion_kind"]["named"]["O2_recovered_within_1"] == 1 + assert sorted(a3["by_expansion_kind"]) == ["named", "nopath", "path"] + # fragile: B3 O1 and O2 flip under seed 43 only; arms with identical blocks are not fragile + assert a3["fragile"] is True and a3["stability"]["stability1"]["flipped"] == ["O1", "O2"] and a3["stability"]["stability2"]["flipped"] == [] + assert a3["verdict"].endswith("(fragile)") + assert a1["fragile"] is False and a2["fragile"] is False and a4["fragile"] is False + # negative controls: B3 zero; B1 shows the 0.2 mechanism exposing after a denied call + assert a3["negative_controls"] == {"executions_of_denied_or_pending_calls": 0, "expansions_fired_by_denied_or_pending_call": 0} + assert a1["negative_controls"]["expansions_fired_by_denied_or_pending_call"] == 1 + assert a3["trigger_counts"] == {"T2": 4} and a3["suppressed_n1_n2"] == 1, (a3["trigger_counts"], a3["suppressed_n1_n2"]) + # an arm 4 run with reasoning present is invalid + victim = next((td / "s42" / "receipts").glob("*.B4.json")) + r = json.loads(victim.read_text()) + r["reasoning"]["invalid_for_arm4"] = True + victim.write_text(json.dumps(r)) + analyze.main([str(td / "s42"), "--out", str(td / "o3"), *args]) + s3 = json.loads((td / "o3" / "campaign-summary.json").read_text()) + assert s3["arms"]["4"]["gates"]["overall"] == "INVALID" and len(s3["arms"]["4"]["reasoning_present_in_arm4_runs"]) == 1 + # without stability blocks the fragile label is not evaluated + analyze.main([str(td / "s42"), "--out", str(td / "o4"), "--campaign", "--tasks-dir", str(td / "tasks")]) + assert json.loads((td / "o4" / "campaign-summary.json").read_text())["arms"]["3"]["fragile"] is None + assert "Fragile: yes" in (td / "o1" / "campaign-summary.md").read_text() + print("campaign analyzer tests: PASS") + + def analyze_to(run: Path, out: Path, extra: list = ()) -> None: analyze.main([str(run), "--out", str(out), *extra]) @@ -128,6 +244,7 @@ def main() -> int: print("fixture and expected outputs written") return 0 test() + test_campaign() return 0 diff --git a/bench/tools/test_runner_offline.py b/bench/tools/test_runner_offline.py index 16f9760..3ce9ef6 100644 --- a/bench/tools/test_runner_offline.py +++ b/bench/tools/test_runner_offline.py @@ -93,12 +93,18 @@ def script(messages, tools): if n_tool == 0: return None, [call(0, "summarize_repo", {})] return "summarize_repo is not available", None + if Handler.lenient: # real held-out and dev tasks in the corpus-switch test: any answer will do + return "ok", None raise AssertionError("unscripted request") class Handler(BaseHTTPRequestHandler): log = [] tool_contents = [] + seen = [] # every request body's switch fields, including the max_tokens=1 measurement requests + lenient = False + fake_reasoning = False # reply with a reasoning field unless the request turned reasoning off + force_reasoning = False # ... even when it did (an invalid arm 4 run) def log_message(self, *a): pass @@ -106,12 +112,18 @@ class Handler(BaseHTTPRequestHandler): def do_POST(self): body = json.loads(self.rfile.read(int(self.headers["Content-Length"]))) tools = body.get("tools") or [] + off = body.get("reasoning_effort") == "none" or (body.get("chat_template_kwargs") or {}).get("enable_thinking") is False + Handler.seen.append({"system": body["messages"][0]["content"], "reasoning_effort": body.get("reasoning_effort"), + "chat_template_kwargs": body.get("chat_template_kwargs"), "seed": body.get("seed"), + "max_tokens": body.get("max_tokens")}) prompt = 50 + 7 * len(tools) + 3 * len(body["messages"]) if body.get("max_tokens") == 1: msg = {"role": "assistant", "content": "x"} else: text, calls = script(body["messages"], tools) msg = {"role": "assistant", "content": text or ""} + if Handler.fake_reasoning and (not off or Handler.force_reasoning): + msg["reasoning"] = "thinking" if calls: msg["tool_calls"] = calls Handler.log.append((body["messages"][1]["content"][:6], [t["function"]["name"] for t in tools])) @@ -293,6 +305,116 @@ def main() -> int: for t in rt_tasks.values(): rr = json.loads((rtout / "receipts" / f"{t['id']}.B.json").read_text()) assert bench_eval.judge(t, "B", rr["transcript"]) == rr["judge"] + # ---- 0.2x campaign switches (PROTOCOL-0.2x.md sections 4, 8, 10): the seven conditions, no model needed + assert run_bench.rotated(list(run_bench.CAMPAIGN_CONDITIONS), 0) == ["A", "A2", "A4", "B1", "B2", "B3", "B4"] + assert run_bench.rotated(list(run_bench.CAMPAIGN_CONDITIONS), 1)[:2] == ["A2", "A4"] + assert run_bench.rotated(list(run_bench.CAMPAIGN_CONDITIONS), 9) == run_bench.rotated(list(run_bench.CAMPAIGN_CONDITIONS), 2) + assert run_bench.rotated(["A", "B"], 0) == ["A", "B"] and run_bench.rotated(["A", "B"], 1) == ["B", "A"] # the 0.2 rule + sp = (BENCH / "prompts" / "system.md").read_text() + add = (BENCH / "heldout-0.2x" / "prompts" / "discovery-addendum.md").read_text() + sp2 = sp + "\n" + add # system.md ends with a newline: exactly one blank line between them + assert run_bench.text_sha(sp2) != run_bench.text_sha(sp) + ep = f"http://127.0.0.1:{srv.server_port}/v1" + cout = Path(td) / "camp" + Handler.fake_reasoning = True + rc = run_bench.main(["--tasks", "dev", "--condition", "all", "--endpoint", ep, "--out", str(cout), "--tasks-dir", str(rdir), + "--allow-nonfrozen", "--no-warmup", "--backends", "sim-1", "--seed", "43"]) + Handler.fake_reasoning = False + assert rc == 0 + conds7 = list(run_bench.CAMPAIGN_CONDITIONS) + C = lambda k, c: json.loads((cout / "receipts" / f"{rt_tasks[k]['id']}.{c}.json").read_text()) + cm = json.loads((cout / "manifest.json").read_text()) + assert cm["conditions"] == conds7 and sorted(cm["campaign"]["conditions"]) == sorted(conds7), cm["conditions"] + assert cm["campaign"]["seed"] == 43 and cm["generation"]["seed"] == 43 and cm["campaign"]["reasoning_off_field"] == {"reasoning_effort": "none"} + assert (cout / "gpu_at_start.txt").exists() and (cout / "gpu_at_end.txt").exists() and "valid" in cm["latency_validity"] + for k in rt_tasks: + for c in conds7: + r = C(k, c) + assert r["condition"] == c and r["condition_spec"]["id"] == c and r["generation"]["seed"] == 43 + assert all(isinstance(x["prompt_tokens"], int) and isinstance(x["completion_tokens"], int) for x in r["rounds"]) + assert len(r["tool_schema_tokens_per_round"]) == len(r["rounds"]) and r["base_context_tokens"] > 0 + # addendum: only A2 and B2 carry it; the digest is of the composed prompt + for c in conds7: + want = run_bench.text_sha(sp2) if c in ("A2", "B2") else run_bench.text_sha(sp) + assert C("RT-T2", c)["system_prompt_digest"] == want, c + assert C("RT-T2", c)["condition_spec"]["prompt_addendum"] is (c in ("A2", "B2")) + # reasoning off: only A4 and B4 send the field, and then no round carries reasoning + for c in conds7: + r = C("RT-T2", c) + if c in ("A4", "B4"): + assert r["reasoning"] == {"off_requested": True, "field": "reasoning_effort", "rounds_with_reasoning": 0, "invalid_for_arm4": False}, r["reasoning"] + else: + assert r["reasoning"]["off_requested"] is False and r["reasoning"]["rounds_with_reasoning"] == len(r["rounds"]), (c, r["reasoning"]) + # family: A family renders the full catalog and has no discovery tool; B family does + for c in ("A", "A2", "A4"): + r = C("RT-T2", c) + assert r["metrics"]["exposed_tools_first"] == 71 and r["discovery_tool"] is None and r["final_exposed_names"] is None + for c in ("B1", "B2", "B3", "B4"): + r = C("RT-T2", c) + assert r["metrics"]["exposed_tools_first"] < 15 and r["discovery_tool"] == run_bench.DISCOVERY + # policy by condition id: only B3 runs runtime-v1 (T1 on an unknown tool, N1 and N2 as trigger rules) + for c in ("B1", "B2", "B4"): + assert "runtime_triggers" not in C("RT-T1", c) and C("RT-T1", c)["expansions"] == [], c + (ev,) = C("RT-T2", c)["expansions"] + assert ev["trigger"] == "requested_excluded" and ev["added"] == ["read_file"], ev + assert len(C("RT-N1", c)["expansions"]) == 1 # the 0.2 mechanism still exposes after a denied call + r = C("RT-T1", "B3") + assert [e["trigger"] for e in r["expansions"]] == ["T1"] and r["runtime_triggers"] + for k in ("RT-N1", "RT-N2"): # negative controls: no expansion, no execution + r = C(k, "B3") + assert r["expansions"] == [] and all(not c["executed"] for c in r["calls"] if c["decision"] in ("denied", "requires_approval")) + assert any(c["decision"] in ("denied", "requires_approval") for c in r["calls"]) + # the switch fields reach the request body only when asked for + tt = rdir / "one" + tt.mkdir() + (tt / f"{rt_tasks['RT-T2']['id']}.json").write_text(json.dumps(rt_tasks["RT-T2"])) + def bodies(cond, *extra): + Handler.seen.clear() + o = Path(td) / f"sw-{cond}-{'-'.join(extra) or 'plain'}" + assert run_bench.main(["--tasks", "dev", "--condition", cond, "--endpoint", ep, "--out", str(o), "--tasks-dir", str(tt), + "--allow-nonfrozen", "--no-warmup", "--backends", "sim-1", *extra]) == 0 + return list(Handler.seen), o + seen_a, _ = bodies("A") + assert seen_a and all(b["reasoning_effort"] is None and b["chat_template_kwargs"] is None and b["seed"] == 42 for b in seen_a) + seen4, _ = bodies("A4") + assert any(b["max_tokens"] == 1 for b in seen4) and all(b["reasoning_effort"] == "none" for b in seen4), seen4 + seen4k, _ = bodies("B4", "--reasoning-field", "chat_template_kwargs") + assert all(b["chat_template_kwargs"] == {"enable_thinking": False} and b["reasoning_effort"] is None for b in seen4k) + seen2, _ = bodies("A2") + assert all(b["system"] == sp2 for b in seen2 if b["max_tokens"] != 1) # every model turn + assert any(b["system"] == sp2 and b["max_tokens"] == 1 for b in seen2) # and the token measurement + Handler.fake_reasoning = Handler.force_reasoning = True + _, o = bodies("B4", "--seed", "44") + Handler.fake_reasoning = Handler.force_reasoning = False + r = json.loads(next((o / "receipts").glob("*.B4.json")).read_text()) + assert r["reasoning"]["invalid_for_arm4"] is True and r["generation"]["seed"] == 44, r["reasoning"] # reasoning present: invalid + # refusals: the campaign needs sim-1, the condition fixes the policy, held-out seeds are 42 to 44 + for bad in (["--condition", "B1"], ["--condition", "B1", "--backends", "sim-1", "--expansion-policy", "runtime-v1"], + ["--corpus", "0.2x", "--backends", "sim-1", "--seed", "7"]): + try: + run_bench.main(["--tasks", "dev", "--endpoint", ep, "--out", str(Path(td) / "bad"), "--tasks-dir", str(tt), "--allow-nonfrozen" if "7" not in bad else "--no-warmup", *bad]) + raise AssertionError(f"accepted {bad}") + except SystemExit as e: + assert str(e) != "0" and e.code != 0, bad + # corpus switch: the real held-out set, frozen digests checked (no --allow-nonfrozen), fixtures, + # stubs and stores resolved under bench/heldout-0.2x, the dev warm-up taken from bench/tasks + hids = sorted(p.stem for p in (BENCH / "heldout-0.2x" / "tasks").glob("*.json")) + pick = [next(i for i in hids if i.startswith("expansion-")), next(i for i in hids if i.startswith("multidomain-"))] + hout = Path(td) / "held" + Handler.lenient = True + rc = run_bench.main(["--corpus", "0.2x", "--condition", "all", "--backends", "sim-1", "--seed", "42", "--endpoint", ep, + "--out", str(hout), "--only", ",".join(pick)]) + Handler.lenient = False + assert rc == 0 + hm = json.loads((hout / "manifest.json").read_text()) + assert hm["corpus"]["match"] is True and hm["tasks"] == "qual" and hm["task_ids"] == pick, hm["task_ids"] + assert hm["stochastic_execution"]["warmup"]["task"] == "filesystem-001" and hm["stochastic_execution"]["warmup"]["condition"] == "B1" + assert hm["backends"]["stores"] and all(p.endswith(".json") for p in hm["backends"]["stores"]) + for tid in pick: + for c in conds7: + r = json.loads((hout / "receipts" / f"{tid}.{c}.json").read_text()) + assert r["task"]["split"] == "qual" and r["fixture"]["name"].startswith("fixtures/") and r["fixture"]["digest"] + assert hm["order_rule"].startswith("tasks in id order; canonical condition order") # resume: nothing is rerun before = len(Handler.log) run_bench.main(["--tasks", "dev", "--condition", "both", "--endpoint", f"http://127.0.0.1:{srv.server_port}/v1",