diff --git a/CHANGELOG.md b/CHANGELOG.md index 9a4cf50..67737b7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,23 @@ pre-1.0 (`0.x`), the public API may change between minor versions. ## [Unreleased] ### Added +- **Main-run decision kit (internal bench tooling).** `--analyze ` + in `python -m dynamic_subgraphs._bench_main` applies the frozen §4 rule of + `docs/evals/bench-dynamic-vs-fixed-2026-06.md` via the new + `dynamic_subgraphs/_bench_verdict.py`: per-task paired Pareto keyed by + arm name (A1/A2 are both `invented`), full and worker-only cost, the 60% + share plus an exact one-sided sign test, a seeded 10,000-resample + bootstrap CI, the λ = 0.05 penalty cut, and KEEP / KILL / INCONCLUSIVE / + INCONCLUSIVE-leaning-template-cache per sub-arm, headline and stratum. It + writes `verdict.json` and `verdict.md`. Golden tests cover all four + verdicts. The runbook (`docs/evals/bench-main-run-v1.md` §6) lists every + choice the code makes and the win bars the owner signs off on. +- **Live spend kill-switch for the bench.** `SpendGuard` stops a run before + spend would pass `spend_cap_usd` (config: $8, the top of the registered + envelope; `--max-spend-usd` overrides) or when a `STOP` file appears in the + bench dir. A live run refuses to start without a cap and aborts on + untrackable (unpriced) spend. Completed rows are kept and `spend.json` + records why it stopped. - **MCP server (`python -m app.mcp`, new `mcp` extra).** Exposes governed subgraph runs to MCP hosts over stdio or streamable HTTP. Tools: `run_subgraph`, `resume_run`, `replay_run`, `server_info`, diff --git a/docs/evals/bench-main-run-v1.md b/docs/evals/bench-main-run-v1.md index 2ec7d0e..d3751f3 100644 --- a/docs/evals/bench-main-run-v1.md +++ b/docs/evals/bench-main-run-v1.md @@ -1,10 +1,12 @@ # Main run v1 — runbook (dynamic vs router) -> **Status:** READY, validated offline. Only the paid live run is left. +> **Status:** READY, validated offline. Only the paid live run is left, and +> it needs the owner's sign-off on §6 first. > The decision rule is the frozen §4 of > [`bench-dynamic-vs-fixed-2026-06.md`](./bench-dynamic-vs-fixed-2026-06.md); -> this runbook implements it and does not change it. No verdict is computed -> by code. Apply §4 to the rows in the results doc. +> this runbook implements it and does not change it. §4 is applied by +> `dynamic_subgraphs/_bench_verdict.py`, committed before any paid main-run +> data exists, so the analysis can't be chosen after seeing results (§6). ## 1. What is pinned @@ -118,12 +120,42 @@ uv run python -m dynamic_subgraphs._bench_main \ --config docs/evals/bench-main-v1.config.json --dry-run # 3. THE LIVE RUN (paid). Needs both keys; refuses before any spend if either -# is missing. Forces LangSmith tracing off (pilot parity). +# is missing. Forces LangSmith tracing off (pilot parity). Runs under the +# spend kill-switch (below). export OPENAI_API_KEY=... TAVILY_API_KEY=... uv run python -m dynamic_subgraphs._bench_main \ --config docs/evals/bench-main-v1.config.json --live + +# 4. Apply the frozen §4 rule. Writes verdict.json + verdict.md next to the +# rows and prints the markdown table. +uv run python -m dynamic_subgraphs._bench_main \ + --config docs/evals/bench-main-v1.config.json \ + --analyze runs/bench/main-v1/bench.jsonl ``` +### Spend kill-switch + +Every `--dry-run` and `--live` run is guarded by a `SpendGuard` +(`dynamic_subgraphs/bench.py`): + +- **Cap.** `spend_cap_usd` in the config is **$8.00**, the top of §4's + registered $4–8 envelope (the estimate with margin is about $6). + `--max-spend-usd X` overrides it for one launch. Before each task run, the + guard stops the benchmark if spend so far plus that run's estimate + (`cost_estimate.usd_per_run`) would pass the cap. It can overshoot by at + most one run's cost minus its estimate. A live run refuses to start with + no cap. +- **Manual stop.** Create `runs/bench//STOP` (e.g. + `touch runs/bench/main-v1/STOP`) and the run stops before its next task + run. The in-flight run finishes and is recorded. +- **Untracked spend.** Spend is each row's `cost_usd`. A failed run that + used tokens but has no price is charged its arm's estimate. In a live run + a *successful* run with tokens and no price aborts, because spend can't + be tracked (install the `cost` extra: `uv sync --all-extras`). +- **On abort** the CLI exits with code 3. Every completed row is in + `bench.jsonl`, `spend.json` holds the spend and the reason, and + `report.json` is not written. Treat it like any other partial run (below). + PowerShell for step 3: `$env:OPENAI_API_KEY="..."; $env:TAVILY_API_KEY="..."`, then the same `uv run ...` line. @@ -155,13 +187,80 @@ the registered sizing, so never report verdicts from a capped run. - `tests/test_bench.py` covers the harness: sub-arms, per-type repeats, rows surviving a mid-run crash, and refusing duplicate arm names. - The full 1,152-run `--dry-run` was run locally: 1,152 rows, all `ok`, 288 - per arm, in about 36 s. + per arm, in about 36 s. `--analyze` on those rows runs cleanly in about + 3 s (the mock rows spend no tokens, so the verdicts it prints are + meaningless and the report says so). +- `tests/test_bench_verdict.py` holds golden synthetic fixtures that land on + each of the four verdicts (with ties, floor-ineligible tasks and failed + runs), plus every number in §6. `tests/test_bench_killswitch.py` covers + the cap, the STOP file, untracked spend and the mid-run abort. ## 5. After the run -Apply §4 per dynamic sub-arm against `routed`: the floor at 0.6, the -per-task paired Pareto on (quality, full cost), the worker-only sensitivity -cut, ≥60% plus a sign test at p<0.05 with a 10,000-resample bootstrap CI, and -the λ = 0.05 penalty cut. Report verdict lines per headline (structural and -goal) and per stratum. The headline is **A2 vs B**, with A1 alongside. Write -the results into §5 of the results doc. +Run step 4 (`--analyze`) on the run's `bench.jsonl`. It applies §4 per +dynamic sub-arm against `routed` and prints one verdict line per sub-arm × +headline (structural, goal) × scope (all tasks, then each stratum). The +headline is **A2 vs B**, with A1 alongside. Copy `verdict.md` into §5 of the +results doc and commit `verdict.json` with it. If the report says +`registered_sizing: false` or lists unpaired tasks, it is not a +decision-grade run. + +## 6. Reading the verdict (owner sign-off before the paid run) + +### How §4 is turned into code + +§4 leaves several choices open. Each is fixed in `_bench_verdict.py` now, +before any paid data, so none can be picked after seeing results. +Changing any of them after the run is a re-registration and must be written +up as one. + +| Choice | Fixed as | +|---|---| +| Pairing | By `ArmRunRow.arm`, not origin (A1 and A2 are both `invented`; `corpus.compare_origins` can't tell them apart). Each sub-arm vs `routed`. | +| Per-task value | Mean over repeats of the headline score, blended quality, full cost, worker-only cost and tokens. Failed runs score 0. | +| Floor | An arm meets it on a task iff its mean blended quality ≥ 0.6. Task is floor-eligible iff at least one arm meets it. If only one arm does, that arm wins the task. If neither does, the task is dropped. | +| Pareto | Win = ≥ on headline score and ≤ on cost, strictly better on one. Anything else is a tie, including better quality at higher cost. | +| Cost | Full = `cost_usd` (planner included). Worker-only = `worker_cost_usd`, or `cost_usd` when there's no planner split (the router has no planner). If any row on a task is unpriced, that task uses tokens and both bases are equal (flagged). | +| Win share | Wins ÷ floor-eligible tasks. Ties stay in the denominator ("≥60% of floor-eligible tasks"). | +| Sign test | Exact one-sided binomial (`math.comb`) over decisive tasks, ties excluded. | +| Bar | Share ≥ 60% **and** p < 0.05. | +| Bootstrap | 95% percentile CI of the win share; resample eligible tasks; 10,000 resamples; `random.Random(20260611)`. Reported, not part of the bar. | +| Verdict | KEEP: dynamic clears the bar on full cost. KILL: router clears it on full **and** worker-only cost. INCONCLUSIVE-leaning-template-cache: dynamic clears it on worker-only cost only. Otherwise INCONCLUSIVE. | +| λ cut | Per run `headline − 0.05 × tokens / 10,000`; per task the higher mean wins. Reported, never decides. | +| Strata | Same computation, marked descriptive. | + +### The arithmetic + +These numbers come from the code and are pinned in +`tests/test_bench_verdict.py`. + +- **No stratum can reach a verdict.** A stratum has 4 tasks, so the best + one-sided p is 4/4 wins = 1/16 = **0.0625**. Per-stratum lines are + descriptive only. They can show "complex tasks favor planning" as a + pattern, but they can't KEEP or KILL anything. +- **The headline needs ≥17 of 24 wins (71%), not 60%.** With no ties, + 16/24 gives p = 0.076 and 17/24 gives p = 0.032. The sign test binds + harder than the 60% share. +- **Ties move the bar.** Ties leave the sign test's n but stay in the + share's denominator, so both bars move: + + | Ties (of 24 eligible) | Decisive n | Wins for p<0.05 | Wins for ≥60% share | Wins needed | + |---|---|---|---|---| + | 0 | 24 | 17 | 15 | **17** | + | 2 | 22 | 16 | 15 | **16** | + | 4 | 20 | 15 | 15 | **15** | + | 6 | 18 | 13 | 15 | **15** | + | 8 | 16 | 12 | 15 | **15** | + | ≥10 | ≤14 | – | 15 | **impossible** | + + With 8 ties, 12/16 decisive passes the sign test (p = 0.038), but 12/24 is + only a 50% share, so it is INCONCLUSIVE. With 10 or more ties no KEEP or + KILL is possible. Floor-ineligible tasks shrink the 24 the same way. +- **Repeats don't add decision power.** Repeats are averaged into one value + per task before the Pareto check, so they reduce noise within a task. + The sign test's n is the number of tasks (at most 24), whatever the repeat + count. A larger batch of tasks is the only way to more power, which is + §4's INCONCLUSIVE path ("expand the batch"). + +Sign-off: the owner has read this section and accepts these numbers before +launching `--live`. diff --git a/docs/evals/bench-main-v1.config.json b/docs/evals/bench-main-v1.config.json index 2ef5125..8de391a 100644 --- a/docs/evals/bench-main-v1.config.json +++ b/docs/evals/bench-main-v1.config.json @@ -44,6 +44,9 @@ "note": "C (sanity floor): fixed-host-graph-v1, unchanged." } ], + "headline_arm": "invented-a2", + "spend_cap_usd": 8.0, + "spend_cap_note": "Live kill-switch: the run stops before its next task run once booked spend plus that run's estimate would pass this. $8 is the top of the §4 registered envelope ($4-8); the estimate with margin is ~$6.", "repeats_cap": 20, "repeats_by_task_type": { "compare": 20, diff --git a/dynamic_subgraphs/_bench_main.py b/dynamic_subgraphs/_bench_main.py index ca8dc53..34b2c9a 100644 --- a/dynamic_subgraphs/_bench_main.py +++ b/dynamic_subgraphs/_bench_main.py @@ -2,7 +2,7 @@ Reads a committed run config (``docs/evals/bench-main-v1.config.json``) that pins the pack, arms, planner/worker models and per-stratum repeats, then -calls :func:`dynamic_subgraphs.bench.run_benchmark`. Three modes: +calls :func:`dynamic_subgraphs.bench.run_benchmark`. Four modes: # Print the run plan + cost estimate. No engine, no network. python -m dynamic_subgraphs._bench_main --config --estimate @@ -10,12 +10,17 @@ # Full schedule offline: mock planner + mock runners, zero tokens. python -m dynamic_subgraphs._bench_main --config --dry-run - # The paid live run. Requires --live AND the provider keys. + # The paid live run. Requires --live AND the provider keys. Stops before + # spending past spend_cap_usd (or --max-spend-usd), or when a STOP file + # appears in runs/bench//. python -m dynamic_subgraphs._bench_main --config --live + # Apply the frozen §4 rule to a finished run's rows. + python -m dynamic_subgraphs._bench_main --config --analyze + Internal tooling, not public API (underscore module, see -docs/api-stability.md). The KEEP/KILL rule is NOT applied here; it lives in -the results doc so code can't quietly re-score the verdict. +docs/api-stability.md). The §4 rule lives in ``_bench_verdict``, committed +before the paid run so the analysis can't be chosen after seeing the data. """ from __future__ import annotations @@ -30,11 +35,14 @@ from pathlib import Path from typing import Any, cast +from dynamic_subgraphs._bench_verdict import analyze_file from dynamic_subgraphs.bench import ( BenchArm, BenchReport, + BenchSpendAbort, BenchTask, RouterLibrary, + SpendGuard, resolve_repeats, run_benchmark, ) @@ -64,6 +72,8 @@ class MainRunConfig: usd_per_run: dict[str, float] safety_margin: float seconds_per_run: float + spend_cap_usd: float | None = None + headline_arm: str | None = None @classmethod def load(cls, path: Path | str, root: Path | str = ".") -> MainRunConfig: @@ -95,6 +105,13 @@ def load(cls, path: Path | str, root: Path | str = ".") -> MainRunConfig: missing = {a.name for a in arms} - set(usd) if missing: raise ValueError(f"cost_estimate.usd_per_run missing arms: {missing}") + spend_cap = raw.get("spend_cap_usd") + if spend_cap is not None and not float(spend_cap) > 0: + raise ValueError(f"spend_cap_usd must be > 0, got {spend_cap}") + headline = raw.get("headline_arm") + invented = {a.name for a in arms if a.origin == "invented"} + if headline is not None and headline not in invented: + raise ValueError(f"headline_arm {headline!r} is not an invented arm") return cls( bench_id=raw["bench_id"], pack=base / raw["pack"], @@ -107,8 +124,21 @@ def load(cls, path: Path | str, root: Path | str = ".") -> MainRunConfig: usd_per_run=usd, safety_margin=float(est["safety_margin"]), seconds_per_run=float(est["seconds_per_run"]), + spend_cap_usd=float(spend_cap) if spend_cap is not None else None, + headline_arm=headline, ) + @property + def dynamic_arms(self) -> tuple[str, ...]: + return tuple(a.name for a in self.arms if a.origin == "invented") + + @property + def baseline_arm(self) -> str: + routed = [a.name for a in self.arms if a.origin == "routed"] + if len(routed) != 1: + raise ValueError(f"need exactly one routed arm, got {routed}") + return routed[0] + def _model(obj: Mapping[str, Any]) -> Model: return Model(obj["provider"], obj["model"]) @@ -164,14 +194,27 @@ def run_main( bench_id: str | None = None, max_repeats: int | None = None, env: Mapping[str, str] | None = None, + max_spend_usd: float | None = None, ) -> BenchReport: """Execute the configured run. ``mode`` is ``"dry-run"`` or ``"live"``. Dry-run uses the mock planner and mock runners (zero tokens) on the exact same pack, arms and repeat schedule as the live run. + + Both modes run under a :class:`SpendGuard` (the kill-switch): + ``max_spend_usd`` overrides the config's ``spend_cap_usd``. A live run + refuses to start without a cap, and aborts if a successful run comes back + unpriced. Creating ``/bench//STOP`` stops the run + before its next task run. """ if mode not in ("dry-run", "live"): raise ValueError(f"unknown mode {mode!r}") + cap = max_spend_usd if max_spend_usd is not None else cfg.spend_cap_usd + if mode == "live" and cap is None: + raise SystemExit( + "live run refused: no spend cap (set spend_cap_usd in the config " + "or pass --max-spend-usd). Nothing was spent." + ) if mode == "live": env = os.environ if env is None else env missing = [k for k in LIVE_ENV_VARS if not env.get(k)] @@ -181,15 +224,27 @@ def run_main( ) tasks = BenchTask.from_jsonl(cfg.pack) library = RouterLibrary.from_dir(cfg.router_library, cfg.single_fixed) + bid = bench_id or cfg.bench_id + guard = ( + SpendGuard( + cap_usd=cap, + fallback_usd_per_run=cfg.usd_per_run, + stop_file=Path(runs_dir) / "bench" / bid / "STOP", + require_priced=mode == "live", + ) + if cap is not None + else None + ) return run_benchmark( tasks=tasks, repeats=_effective_repeats(cfg, max_repeats), runs_dir=runs_dir, router_library=library, - bench_id=bench_id or cfg.bench_id, + bench_id=bid, planner="mock" if mode == "dry-run" else "llm", model=cfg.worker_model, arms=cfg.arms, + spend_guard=guard, ) @@ -208,6 +263,12 @@ def main(argv: Sequence[str] | None = None) -> int: mode.add_argument("--estimate", action="store_true", help="plan + cost only") mode.add_argument("--dry-run", action="store_true", help="mock, zero tokens") mode.add_argument("--live", action="store_true", help="PAID live run") + mode.add_argument( + "--analyze", + type=Path, + metavar="BENCH_JSONL", + help="apply the frozen §4 rule; writes verdict.json + verdict.md", + ) p.add_argument("--runs-dir", type=Path, default=None) p.add_argument("--bench-id", default=None, help="override config bench_id") p.add_argument( @@ -216,9 +277,35 @@ def main(argv: Sequence[str] | None = None) -> int: default=None, help="cap every stratum's repeats (smoke runs only; not the registered sizing)", ) + p.add_argument( + "--max-spend-usd", + type=float, + default=None, + help="kill-switch: stop before spend exceeds this (overrides spend_cap_usd)", + ) + p.add_argument( + "--out-dir", + type=Path, + default=None, + help="--analyze output dir (default: next to the bench.jsonl)", + ) args = p.parse_args(argv) cfg = MainRunConfig.load(args.config) + if args.analyze is not None: + _, md = analyze_file( + args.analyze, + dynamic_arms=cfg.dynamic_arms, + baseline_arm=cfg.baseline_arm, + headline_arm=cfg.headline_arm, + expected_repeats=cfg.repeats_by_task_type, + out_dir=args.out_dir, + ) + print(md) + dest = args.out_dir or args.analyze.parent + print(f"report: {dest / 'verdict.json'}") + return 0 + tasks = BenchTask.from_jsonl(cfg.pack) plan = plan_run(cfg, tasks, args.max_repeats) print( @@ -230,9 +317,22 @@ def main(argv: Sequence[str] | None = None) -> int: f"(${plan.estimated_usd_with_margin:.2f} with x{cfg.safety_margin} margin), " f"~{plan.estimated_hours:.1f} h sequential" ) + cap = args.max_spend_usd if args.max_spend_usd is not None else cfg.spend_cap_usd + print(f"kill-switch: spend cap {'none' if cap is None else f'${cap:.2f}'}") if args.estimate: return 0 + try: + report = _execute(cfg, args) + except BenchSpendAbort as exc: + print(f"ABORTED by kill-switch: {exc}", file=sys.stderr) + print("completed rows are in bench.jsonl; see spend.json", file=sys.stderr) + return 3 + print(json.dumps(_summarize(report), indent=2)) + return 0 + + +def _execute(cfg: MainRunConfig, args: argparse.Namespace) -> BenchReport: if args.live: # LangSmith quota was exhausted during the pilot; tracing only adds # retry latency for dropped data, so keep it off (pilot parity). @@ -245,6 +345,7 @@ def main(argv: Sequence[str] | None = None) -> int: runs_dir=runs_dir, bench_id=args.bench_id, max_repeats=args.max_repeats, + max_spend_usd=args.max_spend_usd, ) else: runs_dir = args.runs_dir or Path(tempfile.mkdtemp(prefix="bench-dry-")) @@ -254,10 +355,10 @@ def main(argv: Sequence[str] | None = None) -> int: runs_dir=runs_dir, bench_id=args.bench_id or f"{cfg.bench_id}-dryrun", max_repeats=args.max_repeats, + max_spend_usd=args.max_spend_usd, ) - print(json.dumps(_summarize(report), indent=2)) print(f"rows: {Path(runs_dir) / 'bench' / report.bench_id / 'bench.jsonl'}") - return 0 + return report if __name__ == "__main__": # pragma: no cover diff --git a/dynamic_subgraphs/_bench_verdict.py b/dynamic_subgraphs/_bench_verdict.py new file mode 100644 index 0000000..54ee19e --- /dev/null +++ b/dynamic_subgraphs/_bench_verdict.py @@ -0,0 +1,608 @@ +"""The frozen §4 decision rule, as code (internal). + +Applies ``docs/evals/bench-dynamic-vs-fixed-2026-06.md`` §4 (registered +2026-06-11, frozen) to a main-run ``bench.jsonl``. Every choice the prose +leaves open is fixed below and was committed **before** any paid main-run +data existed, so the analysis can't be picked after seeing results. Changing +any constant or operationalization here after the paid run is a +re-registration and has to be recorded in the results doc. + +Operationalization (one line per forking path): + +* **Pairing.** Rows are keyed by ``ArmRunRow.arm``, not origin: A1 and A2 are + both ``invented``. Each dynamic sub-arm is compared with the ``routed`` arm. +* **Per-task aggregate.** For each (task, arm): the mean over repeats of the + headline score, blended quality, full cost, worker-only cost and tokens. + Failed runs count as quality 0 (pilot rule); a missing headline on a row + also counts as 0. +* **Floor.** An arm meets the floor on a task iff its mean blended quality is + >= 0.6. A task is floor-eligible iff at least one arm meets it. If only one + arm meets it, that arm wins the task (as ``corpus.compare_origins`` does: + only eligible runs compete). If neither does, the task is excluded. +* **Pareto.** Both arms eligible: an arm wins iff it is >= on headline score + and <= on cost, strictly better on one. Anything else is a tie (including + trade-offs: better quality at higher cost). +* **Cost axis.** USD when every row of both arms on the task is priced, else + total tokens for that task (flagged in the report). +* **Full cost** = ``cost_usd`` (planner included). **Worker-only cost** = + ``worker_cost_usd`` when the planner split exists, else ``cost_usd`` (no + deduction; the router has no planner, so its worker cost is its full cost). + On the token axis the two bases are identical. +* **Win share** = wins / floor-eligible tasks (ties stay in the denominator, + as §4 reads: "≥60% of floor-eligible tasks"). +* **Sign test** = exact one-sided binomial over decisive tasks (ties + excluded): p = P(X >= wins | n = wins_a + wins_b, 0.5). +* **Bar** = win share >= 0.60 AND p < 0.05. +* **Bootstrap CI** = 95% percentile interval of the win share, resampling + floor-eligible tasks with replacement, 10,000 resamples, + ``random.Random(20260611)`` (the registration date) fresh per interval. +* **Verdict**, in order: KEEP iff the dynamic arm clears the bar on full cost. + KILL iff the router clears it on full AND worker-only cost. + INCONCLUSIVE-leaning-template-cache iff the dynamic arm clears it on + worker-only cost (but not full). Otherwise INCONCLUSIVE. +* **λ cut** (secondary, never decisive): per run + ``adjusted = headline - 0.05 · total_tokens / 10,000``; per task the higher + mean adjusted score wins (equal = tie), over the same floor-eligible tasks. +* **Strata** get the same computation but are descriptive only: 4 tasks per + stratum give a best one-sided p of 1/16 = 0.0625, so no stratum can clear + the bar. +""" + +from __future__ import annotations + +import json +import math +import random +from collections.abc import Iterable, Mapping, Sequence +from dataclasses import asdict, dataclass +from pathlib import Path +from typing import Any, Literal + +from dynamic_subgraphs.bench import ArmRunRow + +RULE = "docs/evals/bench-dynamic-vs-fixed-2026-06.md §4 (frozen 2026-06-11)" +QUALITY_FLOOR = 0.6 +WIN_SHARE = 0.60 +ALPHA = 0.05 +BOOTSTRAP_RESAMPLES = 10_000 +BOOTSTRAP_SEED = 20260611 +CI_LEVEL = 0.95 +LAMBDA = 0.05 +LAMBDA_TOKENS = 10_000 +HEADLINES: tuple[str, ...] = ("structural", "goal") +ALL = "all" + +KEEP = "KEEP" +KILL = "KILL" +INCONCLUSIVE = "INCONCLUSIVE" +LEANING = "INCONCLUSIVE-leaning-template-cache" +VERDICTS: tuple[str, ...] = (KEEP, KILL, INCONCLUSIVE, LEANING) + +Outcome = Literal["dynamic", "baseline", "tie", "ineligible"] + + +# --------------------------------------------------------------------------- +# Statistics +# --------------------------------------------------------------------------- + + +def sign_test_p(wins: int, n: int) -> float: + """Exact one-sided sign-test p: P(X >= wins) for X ~ Binomial(n, 0.5). + + ``n`` is the number of decisive (non-tie) tasks. n == 0 gives 1.0. + """ + if n < 0 or wins < 0 or wins > n: + raise ValueError(f"need 0 <= wins <= n, got wins={wins}, n={n}") + if n == 0: + return 1.0 + tail: int = sum(math.comb(n, k) for k in range(wins, n + 1)) + return tail / (1 << n) + + +def min_wins_for_p(n: int, alpha: float = ALPHA) -> int | None: + """Fewest wins out of ``n`` decisive tasks with p < ``alpha``; None if none.""" + for w in range(n + 1): + if sign_test_p(w, n) < alpha: + return w + return None + + +def required_wins(eligible: int, ties: int) -> int | None: + """Fewest wins that clear the full bar (share AND sign test). + + ``eligible`` floor-eligible tasks of which ``ties`` are ties, so + ``eligible - ties`` are decisive. None if no win count can clear it. + """ + decisive = eligible - ties + by_p = min_wins_for_p(decisive) + if by_p is None: + return None + by_share = math.ceil(WIN_SHARE * eligible - 1e-9) + need = max(by_p, by_share) + return need if need <= decisive else None + + +def bootstrap_ci( + indicators: Sequence[int], + resamples: int = BOOTSTRAP_RESAMPLES, + seed: int = BOOTSTRAP_SEED, + level: float = CI_LEVEL, +) -> tuple[float, float] | None: + """Percentile bootstrap CI of the mean of a 0/1 per-task indicator.""" + m = len(indicators) + if m == 0: + return None + rng = random.Random(seed) + pool = list(indicators) + means = sorted(sum(rng.choices(pool, k=m)) / m for _ in range(resamples)) + tail = (1 - level) / 2 + lo = means[math.floor(tail * (resamples - 1))] + hi = means[math.ceil((1 - tail) * (resamples - 1))] + return (lo, hi) + + +# --------------------------------------------------------------------------- +# Per-task aggregation +# --------------------------------------------------------------------------- + + +@dataclass(frozen=True) +class ArmTask: + """One arm's mean metrics on one task, across its repeats.""" + + runs: int + quality: float + structural: float + goal: float + tokens: float + full_usd: float | None # None when any repeat is unpriced + worker_usd: float | None + missing_headline: int + + def headline(self, name: str) -> float: + return self.structural if name == "structural" else self.goal + + @property + def floor_met(self) -> bool: + return self.quality >= QUALITY_FLOOR + + +def _mean(xs: Sequence[float]) -> float: + return sum(xs) / len(xs) + + +def aggregate(rows: Sequence[ArmRunRow]) -> ArmTask: + """Aggregate one arm's repeats on one task.""" + if not rows: + raise ValueError("no rows to aggregate") + missing = sum( + 1 + for r in rows + if r.status == "ok" and (r.structural_quality is None or r.goal_score is None) + ) + + def score(v: float | None, r: ArmRunRow) -> float: + return float(v) if (v is not None and r.status == "ok") else 0.0 + + priced = all(r.cost_usd is not None for r in rows) + full = [float(r.cost_usd) for r in rows if r.cost_usd is not None] + worker = [ + float(r.worker_cost_usd if r.worker_cost_usd is not None else r.cost_usd) + for r in rows + if r.cost_usd is not None + ] + return ArmTask( + runs=len(rows), + quality=_mean([r.quality if r.status == "ok" else 0.0 for r in rows]), + structural=_mean([score(r.structural_quality, r) for r in rows]), + goal=_mean([score(r.goal_score, r) for r in rows]), + tokens=_mean([float(r.total_tokens) for r in rows]), + full_usd=_mean(full) if priced else None, + worker_usd=_mean(worker) if priced else None, + missing_headline=missing, + ) + + +def adjusted(rows: Sequence[ArmRunRow], headline: str) -> float: + """Mean λ-penalized headline score: score - 0.05 · tokens / 10k.""" + vals = [] + for r in rows: + raw = r.structural_quality if headline == "structural" else r.goal_score + s = float(raw) if (raw is not None and r.status == "ok") else 0.0 + vals.append(s - LAMBDA * (r.total_tokens / LAMBDA_TOKENS)) + return _mean(vals) + + +def pareto(qa: float, ca: float, qb: float, cb: float) -> Outcome: + """Paired Pareto on (quality up, cost down). 'dynamic' means a wins.""" + if qa >= qb and ca <= cb and (qa > qb or ca < cb): + return "dynamic" + if qb >= qa and cb <= ca and (qb > qa or cb < ca): + return "baseline" + return "tie" + + +@dataclass(frozen=True) +class TaskComparison: + """One dynamic arm vs the baseline on one task, for one headline.""" + + task_id: str + task_type: str + headline: str + cost_axis: Literal["usd", "tokens"] + dynamic_floor_met: bool + baseline_floor_met: bool + full: Outcome + worker: Outcome + lambda_cut: Outcome + + +def compare_task( + task_id: str, + task_type: str, + headline: str, + dyn_rows: Sequence[ArmRunRow], + base_rows: Sequence[ArmRunRow], +) -> TaskComparison: + """Apply floor -> Pareto (both cost bases) -> λ cut for one task/headline.""" + d, b = aggregate(dyn_rows), aggregate(base_rows) + usd = d.full_usd is not None and b.full_usd is not None + axis: Literal["usd", "tokens"] = "usd" if usd else "tokens" + + def outcome(cost_d: float, cost_b: float) -> Outcome: + if not d.floor_met and not b.floor_met: + return "ineligible" + if d.floor_met != b.floor_met: + return "dynamic" if d.floor_met else "baseline" + return pareto(d.headline(headline), cost_d, b.headline(headline), cost_b) + + if usd: + assert d.full_usd is not None and b.full_usd is not None + assert d.worker_usd is not None and b.worker_usd is not None + full = outcome(d.full_usd, b.full_usd) + worker = outcome(d.worker_usd, b.worker_usd) + else: + full = worker = outcome(d.tokens, b.tokens) + + if full == "ineligible": + lam: Outcome = "ineligible" + else: + ad, ab = adjusted(dyn_rows, headline), adjusted(base_rows, headline) + lam = "dynamic" if ad > ab else "baseline" if ab > ad else "tie" + return TaskComparison( + task_id=task_id, + task_type=task_type, + headline=headline, + cost_axis=axis, + dynamic_floor_met=d.floor_met, + baseline_floor_met=b.floor_met, + full=full, + worker=worker, + lambda_cut=lam, + ) + + +# --------------------------------------------------------------------------- +# Verdict lines +# --------------------------------------------------------------------------- + + +@dataclass(frozen=True) +class SideStats: + """One side's evidence on one cost basis (or the λ cut).""" + + wins: int + losses: int + ties: int + eligible: int # wins + losses + ties + decisive: int # wins + losses: the sign test's n + share: float | None # wins / eligible + p: float # exact one-sided sign test + ci: tuple[float, float] | None + meets_bar: bool + + +def side_stats( + outcomes: Sequence[Outcome], side: Outcome, with_ci: bool = True +) -> SideStats: + other: Outcome = "baseline" if side == "dynamic" else "dynamic" + elig = [o for o in outcomes if o != "ineligible"] + wins = sum(1 for o in elig if o == side) + losses = sum(1 for o in elig if o == other) + ties = len(elig) - wins - losses + p = sign_test_p(wins, wins + losses) + share = wins / len(elig) if elig else None + ci = bootstrap_ci([1 if o == side else 0 for o in elig]) if with_ci else None + meets = share is not None and share >= WIN_SHARE and p < ALPHA + return SideStats( + wins=wins, + losses=losses, + ties=ties, + eligible=len(elig), + decisive=wins + losses, + share=share, + p=p, + ci=ci, + meets_bar=meets, + ) + + +def decide(dyn_full: bool, dyn_worker: bool, base_full: bool, base_worker: bool) -> str: + """§4 verdict from the four bar checks (see module docstring).""" + if dyn_full: + return KEEP + if base_full and base_worker: + return KILL + if dyn_worker: + return LEANING + return INCONCLUSIVE + + +@dataclass(frozen=True) +class VerdictLine: + """One §4 verdict line: dynamic sub-arm vs baseline, headline, scope.""" + + dynamic_arm: str + baseline_arm: str + headline: str + scope: str # "all" or a task_type (stratum) + decisive_scope: bool # False for strata (descriptive only) + tasks: int + ineligible: int + token_axis_tasks: int + full: SideStats # dynamic arm, full cost + worker: SideStats # dynamic arm, worker-only cost + baseline_full: SideStats # router, full cost + baseline_worker: SideStats # router, worker-only cost + lambda_cut: SideStats # dynamic arm, λ-penalized (never decisive) + verdict: str + + +def verdict_line( + dynamic_arm: str, + baseline_arm: str, + headline: str, + scope: str, + comps: Sequence[TaskComparison], +) -> VerdictLine: + full = [c.full for c in comps] + worker = [c.worker for c in comps] + d_full = side_stats(full, "dynamic") + d_worker = side_stats(worker, "dynamic") + b_full = side_stats(full, "baseline") + b_worker = side_stats(worker, "baseline") + lam = side_stats([c.lambda_cut for c in comps], "dynamic", with_ci=False) + return VerdictLine( + dynamic_arm=dynamic_arm, + baseline_arm=baseline_arm, + headline=headline, + scope=scope, + decisive_scope=scope == ALL, + tasks=len(comps), + ineligible=sum(1 for c in comps if c.full == "ineligible"), + token_axis_tasks=sum(1 for c in comps if c.cost_axis == "tokens"), + full=d_full, + worker=d_worker, + baseline_full=b_full, + baseline_worker=b_worker, + lambda_cut=lam, + verdict=decide( + d_full.meets_bar, d_worker.meets_bar, b_full.meets_bar, b_worker.meets_bar + ), + ) + + +# --------------------------------------------------------------------------- +# Whole-report analysis +# --------------------------------------------------------------------------- + + +def load_rows(path: Path | str) -> list[ArmRunRow]: + """Read ``bench.jsonl`` into rows (unknown or missing fields raise).""" + rows: list[ArmRunRow] = [] + for ln, line in enumerate(Path(path).read_text("utf-8").splitlines(), 1): + if not line.strip(): + continue + try: + rows.append(ArmRunRow(**json.loads(line))) + except (TypeError, json.JSONDecodeError) as exc: + raise ValueError(f"{path}:{ln}: not an ArmRunRow ({exc})") from exc + return rows + + +def analyze( + rows: Iterable[ArmRunRow], + *, + dynamic_arms: Sequence[str], + baseline_arm: str = "routed", + headline_arm: str | None = None, + expected_repeats: Mapping[str, int] | None = None, +) -> dict[str, Any]: + """Apply §4 to ``rows``. Returns a JSON-safe report dict. + + Raises ``ValueError`` on evidence that can't be scored honestly: rows from + more than one bench_id, duplicate (task, arm, repeat) keys, or a named arm + with no rows. Tasks missing one side of a pair are excluded and listed in + ``warnings`` (a partial run is not decision-grade). + """ + rows = list(rows) + if not rows: + raise ValueError("no rows") + bench_ids = sorted({r.bench_id for r in rows}) + if len(bench_ids) > 1: + raise ValueError(f"rows span several bench_ids: {bench_ids}") + seen: set[tuple[str, str, int]] = set() + for r in rows: + key = (r.task_id, r.arm, r.repeat) + if key in seen: + raise ValueError(f"duplicate row {key}") + seen.add(key) + arms_present = {r.arm for r in rows} + for a in (*dynamic_arms, baseline_arm): + if a not in arms_present: + raise ValueError(f"arm {a!r} has no rows (present: {sorted(arms_present)})") + + by: dict[tuple[str, str], list[ArmRunRow]] = {} + task_type: dict[str, str] = {} + for r in rows: + by.setdefault((r.task_id, r.arm), []).append(r) + task_type[r.task_id] = r.task_type + tasks = sorted(task_type) + strata = sorted(set(task_type.values())) + + warnings: list[str] = [] + registered_sizing: bool | None = None + if expected_repeats is not None: + registered_sizing = True + for (tid, arm), rs in sorted(by.items()): + want = expected_repeats.get(task_type[tid]) + if want is not None and len(rs) != want: + registered_sizing = False + warnings.append( + f"{tid}/{arm}: {len(rs)} repeats, registered {want} " + "(not the registered sizing; never report a verdict from it)" + ) + if all(r.total_tokens == 0 for r in rows): + warnings.append( + "no row spent any tokens: mock (--dry-run) data, the verdicts " + "only show the analyzer runs and mean nothing" + ) + missing = sum(1 for r in rows if r.status == "ok" and r.goal_score is None) + if missing: + warnings.append(f"{missing} ok rows lack goal_score (scored as 0)") + + lines: list[VerdictLine] = [] + per_task: list[dict[str, Any]] = [] + for dyn in dynamic_arms: + for h in HEADLINES: + comps: list[TaskComparison] = [] + for tid in tasks: + d_rows, b_rows = by.get((tid, dyn)), by.get((tid, baseline_arm)) + if not d_rows or not b_rows: + warnings.append(f"{tid}: unpaired for {dyn} vs {baseline_arm}") + continue + if len(d_rows) != len(b_rows): + warnings.append( + f"{tid}: {dyn} has {len(d_rows)} repeats, " + f"{baseline_arm} has {len(b_rows)} (paired design broken)" + ) + comps.append(compare_task(tid, task_type[tid], h, d_rows, b_rows)) + lines.append(verdict_line(dyn, baseline_arm, h, ALL, comps)) + for s in strata: + sc = [c for c in comps if c.task_type == s] + lines.append(verdict_line(dyn, baseline_arm, h, s, sc)) + per_task.extend({"dynamic_arm": dyn, **asdict(c)} for c in comps) + token_tasks = sum(1 for c in per_task if c["cost_axis"] == "tokens") + if token_tasks: + warnings.append( + f"{token_tasks} task comparisons fell back to the token cost axis " + "(unpriced rows): worker-only cost = full cost there" + ) + + return { + "rule": RULE, + "constants": { + "quality_floor": QUALITY_FLOOR, + "win_share": WIN_SHARE, + "alpha": ALPHA, + "bootstrap_resamples": BOOTSTRAP_RESAMPLES, + "bootstrap_seed": BOOTSTRAP_SEED, + "ci_level": CI_LEVEL, + "lambda": LAMBDA, + "lambda_tokens": LAMBDA_TOKENS, + }, + "bench_id": bench_ids[0], + "rows": len(rows), + "tasks": len(tasks), + "strata": strata, + "dynamic_arms": list(dynamic_arms), + "baseline_arm": baseline_arm, + "headline_arm": headline_arm, + "registered_sizing": registered_sizing, + "warnings": list(dict.fromkeys(warnings)), + "lines": [asdict(line) for line in lines], + "per_task": per_task, + } + + +# --------------------------------------------------------------------------- +# Markdown +# --------------------------------------------------------------------------- + + +def _pct(x: float | None) -> str: + return "-" if x is None else f"{100 * x:.0f}%" + + +def _ci(ci: Any) -> str: + return "-" if ci is None else f"[{100 * ci[0]:.0f}%, {100 * ci[1]:.0f}%]" + + +def _side(s: Mapping[str, Any]) -> str: + return f"{s['wins']}/{s['decisive']} (p={s['p']:.4f})" + + +def to_markdown(report: Mapping[str, Any]) -> str: + """Render the verdict lines as a markdown table (one row per line).""" + out = [ + f"# §4 verdict — `{report['bench_id']}`", + "", + f"Rule: {report['rule']}. Rows: {report['rows']}, tasks: {report['tasks']}. " + f"Headline arm: `{report['headline_arm']}` vs `{report['baseline_arm']}`. " + f"Registered sizing: {report['registered_sizing']}.", + "", + "Wins/ties/n are floor-eligible tasks; p is the exact one-sided sign " + "test over decisive tasks (ties excluded); CI is the 95% bootstrap " + "interval of the win share. Strata are descriptive only (best " + "possible p with 4 tasks is 0.0625).", + "", + "| arm | headline | scope | n | wins | ties | losses | share | p | 95% CI " + "| worker-only wins/n | router full wins/n | router worker wins/n " + "| λ cut wins/n | verdict |", + "|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|", + ] + for ln in report["lines"]: + f = ln["full"] + verdict = ln["verdict"] if ln["decisive_scope"] else f"({ln['verdict']})" + if ln["scope"] == ALL and ln["dynamic_arm"] == report["headline_arm"]: + verdict = f"**{verdict}**" + out.append( + f"| {ln['dynamic_arm']} | {ln['headline']} | {ln['scope']} " + f"| {f['eligible']} | {f['wins']} | {f['ties']} | {f['losses']} " + f"| {_pct(f['share'])} | {f['p']:.4f} | {_ci(f['ci'])} " + f"| {_side(ln['worker'])} | {_side(ln['baseline_full'])} " + f"| {_side(ln['baseline_worker'])} | {_side(ln['lambda_cut'])} " + f"| {verdict} |" + ) + if report["warnings"]: + out += ["", "**Warnings**", ""] + out += [f"- {w}" for w in report["warnings"]] + return "\n".join(out) + "\n" + + +def analyze_file( + path: Path | str, + *, + dynamic_arms: Sequence[str], + baseline_arm: str = "routed", + headline_arm: str | None = None, + expected_repeats: Mapping[str, int] | None = None, + out_dir: Path | str | None = None, +) -> tuple[dict[str, Any], str]: + """Analyze a ``bench.jsonl``; write ``verdict.json`` + ``verdict.md``. + + Outputs go next to the input unless ``out_dir`` is given. + """ + report = analyze( + load_rows(path), + dynamic_arms=dynamic_arms, + baseline_arm=baseline_arm, + headline_arm=headline_arm, + expected_repeats=expected_repeats, + ) + md = to_markdown(report) + dest = Path(out_dir) if out_dir is not None else Path(path).parent + dest.mkdir(parents=True, exist_ok=True) + (dest / "verdict.json").write_text(json.dumps(report, indent=2), "utf-8") + (dest / "verdict.md").write_text(md, "utf-8") + return report, md diff --git a/dynamic_subgraphs/bench.py b/dynamic_subgraphs/bench.py index 0345575..9dd5520 100644 --- a/dynamic_subgraphs/bench.py +++ b/dynamic_subgraphs/bench.py @@ -9,9 +9,9 @@ Persists runs/bench//bench.jsonl (one ArmRunRow per line) and report.json (row count + pilot CV table). The KEEP/KILL decision rule is -deliberately NOT encoded here — it is pre-registered after the pilot -(spec §0/§7) and applied in the results doc, not by code that could be -quietly edited post-hoc. +deliberately NOT encoded here: it is pre-registered (results doc §4) and +applied by ``dynamic_subgraphs._bench_verdict``, which was committed before +any paid main-run data existed. ``SpendGuard`` is the live-run kill-switch. """ from __future__ import annotations @@ -68,6 +68,85 @@ class BenchIntegrityError(DynamicSubgraphsError, RuntimeError): """ +class BenchSpendAbort(DynamicSubgraphsError, RuntimeError): + """Raised by :class:`SpendGuard` to stop a run before more money is spent. + + Every row finished before the abort is already in ``bench.jsonl``, and + ``spend.json`` records why the run stopped. + """ + + +@dataclass +class SpendGuard: + """Live spend kill-switch for :func:`run_benchmark`. + + Before each run it stops the benchmark if ``stop_file`` exists (an + operator's manual kill) or if the spend so far plus the next run's + estimate would exceed ``cap_usd``. So the cap can be overshot by at most + the difference between one run's real cost and its estimate. + + Spend is each row's ``cost_usd``. A row that used tokens but has no price + is charged its arm's estimate from ``fallback_usd_per_run``; with + ``require_priced`` (live runs) an unpriced *successful* row aborts + instead, because the spend could not be tracked at all. + """ + + cap_usd: float + fallback_usd_per_run: Mapping[str, float] = field(default_factory=dict) + stop_file: Path | None = None + require_priced: bool = False + spent_usd: float = 0.0 + runs: int = 0 + unpriced_runs: int = 0 + aborted: str | None = None + + def __post_init__(self) -> None: + if not self.cap_usd > 0: + raise ValueError(f"cap_usd must be > 0, got {self.cap_usd}") + + def before_run(self, arm: str, run_id: str) -> None: + """Raise :class:`BenchSpendAbort` if ``run_id`` must not start.""" + if self.stop_file is not None and self.stop_file.exists(): + self._abort(f"stop file {self.stop_file} present before {run_id}") + projected = self.spent_usd + self.fallback_usd_per_run.get(arm, 0.0) + if projected > self.cap_usd: + self._abort( + f"spend cap ${self.cap_usd:.2f} would be exceeded by {run_id}: " + f"spent ${self.spent_usd:.4f} + estimate " + f"${self.fallback_usd_per_run.get(arm, 0.0):.4f}" + ) + + def charge(self, row: ArmRunRow) -> None: + """Book one finished row's spend.""" + self.runs += 1 + if row.cost_usd is not None: + self.spent_usd += row.cost_usd + return + if row.total_tokens <= 0: + return # nothing was spent (mock run, or failed before any call) + if self.require_priced and row.status == "ok": + self._abort( + f"run {row.run_id} used {row.total_tokens} tokens with no price; " + "live spend can't be tracked (install the 'cost' extra)" + ) + self.unpriced_runs += 1 + self.spent_usd += self.fallback_usd_per_run.get(row.arm, 0.0) + + def to_dict(self) -> dict[str, Any]: + return { + "cap_usd": self.cap_usd, + "spent_usd": round(self.spent_usd, 6), + "runs": self.runs, + "unpriced_runs": self.unpriced_runs, + "aborted": self.aborted, + "stop_file": str(self.stop_file) if self.stop_file else None, + } + + def _abort(self, reason: str) -> None: + self.aborted = reason + raise BenchSpendAbort(reason) + + # --------------------------------------------------------------------------- # BenchTask # --------------------------------------------------------------------------- @@ -368,6 +447,7 @@ def run_benchmark( model: Model | None = None, planner_model: Model | None = None, arms: Sequence[BenchArm] | None = None, + spend_guard: SpendGuard | None = None, ) -> BenchReport: """Run all tasks across all arms for ``repeats`` repetitions. @@ -389,10 +469,16 @@ def run_benchmark( - ``"authored"``: the single fixed-floor spec; substituted via fill_spec; runs on the REAL worker path. + ``spend_guard`` is the live kill-switch: it is checked before every run + and charged after it. When it trips, :class:`BenchSpendAbort` propagates + after the completed rows are flushed; ``spend.json`` in the bench dir + records the spend and the reason either way. + Runs are sequential (no threading). Plan/validation failures synthesize quality=0.0 / floor=False rows (the plan-failure rule). Raises: + BenchSpendAbort: if ``spend_guard`` stops the run. BenchIntegrityError: if ``bench_id`` reuses a non-empty bench dir, or if a run succeeds (status=="ok") without an EvalResult — an infrastructure failure that must not be booked as quality-0 data. @@ -432,6 +518,49 @@ def run_benchmark( rows: list[ArmRunRow] = [] bench_dir.mkdir(parents=True, exist_ok=True) + try: + _run_rows( + tasks=tasks, + arm_list=arm_list, + task_repeats=task_repeats, + bench_id=bench_id, + bench_dir=bench_dir, + router_library=router_library, + engine=engine, + planner_model=planner_model, + spend_guard=spend_guard, + rows=rows, + ) + finally: + if spend_guard is not None: + (bench_dir / "spend.json").write_text( + json.dumps(spend_guard.to_dict(), indent=2), encoding="utf-8" + ) + + pilot = _pilot_stats(rows) + report = BenchReport( + bench_id=bench_id, + rows=tuple(rows), + pilot=pilot, + ) + _persist(report, runs_dir) + return report + + +def _run_rows( + *, + tasks: Sequence[BenchTask], + arm_list: Sequence[BenchArm], + task_repeats: Mapping[str, int], + bench_id: str, + bench_dir: Path, + router_library: RouterLibrary, + engine: DynamicSubgraphs, + planner_model: Model | None, + spend_guard: SpendGuard | None, + rows: list[ArmRunRow], +) -> None: + """The sequential run loop; appends to ``rows`` and ``bench.jsonl``.""" with (bench_dir / "bench.jsonl").open("w", encoding="utf-8") as partial: for task in tasks: for bench_arm in arm_list: @@ -443,6 +572,8 @@ def run_benchmark( ) for repeat in range(task_repeats[task.task_id]): run_id = f"{bench_id}-{task.task_id}-{arm}-r{repeat}" + if spend_guard is not None: + spend_guard.before_run(arm, run_id) # Determine fixed_spec for routed/authored arms. fixed: GraphSpec | None @@ -537,12 +668,5 @@ def run_benchmark( rows.append(row) partial.write(json.dumps(asdict(row)) + "\n") partial.flush() - - pilot = _pilot_stats(rows) - report = BenchReport( - bench_id=bench_id, - rows=tuple(rows), - pilot=pilot, - ) - _persist(report, runs_dir) - return report + if spend_guard is not None: + spend_guard.charge(row) diff --git a/tests/test_bench_killswitch.py b/tests/test_bench_killswitch.py new file mode 100644 index 0000000..a28b837 --- /dev/null +++ b/tests/test_bench_killswitch.py @@ -0,0 +1,170 @@ +"""The live-run spend kill-switch (``SpendGuard``). Offline; spends nothing.""" + +from __future__ import annotations + +import json +from dataclasses import replace +from pathlib import Path +from typing import Any +from unittest.mock import patch + +import pytest + +from dynamic_subgraphs import DynamicSubgraphs, EvalReference +from dynamic_subgraphs._bench_main import MainRunConfig, main, run_main +from dynamic_subgraphs.bench import ( + ArmRunRow, + BenchSpendAbort, + BenchTask, + RouterLibrary, + SpendGuard, + run_benchmark, +) +from dynamic_subgraphs.engine import RunResult +from dynamic_subgraphs.usage import TokenUsage + +CONFIG = Path("docs/evals/bench-main-v1.config.json") +LIB = RouterLibrary.from_dir( + Path("docs/evals/router-library-v1"), Path("docs/evals/fixed-host-graph-v1.json") +) + + +def _row(cost: float | None, tokens: int = 100, status: str = "ok") -> ArmRunRow: + return ArmRunRow( + bench_id="b", + task_id="t", + task_type="compare", + arm="routed", + repeat=0, + run_id="b-t-routed-r0", + status=status, + quality=0.0, + quality_floor_met=False, + value_per_ktok=None, + cost_usd=cost, + planner_cost_usd=None, + worker_cost_usd=None, + total_tokens=tokens, + node_count=None, + topology_signature=None, + ) + + +def test_guard_books_cost_and_stops_before_the_cap() -> None: + g = SpendGuard(cap_usd=0.01, fallback_usd_per_run={"routed": 0.003}) + g.before_run("routed", "r0") + g.charge(_row(0.004)) + g.before_run("routed", "r1") # 0.004 + 0.003 <= 0.01 + g.charge(_row(0.004)) + with pytest.raises(BenchSpendAbort, match="spend cap"): + g.before_run("routed", "r2") # 0.008 + 0.003 > 0.01 + assert g.aborted and g.to_dict()["spent_usd"] == 0.008 + + +def test_guard_charges_estimate_for_unpriced_spend_only() -> None: + g = SpendGuard(cap_usd=1.0, fallback_usd_per_run={"routed": 0.002}) + g.charge(_row(None, tokens=0)) # mock run: nothing spent + g.charge(_row(None, tokens=50, status="plan_failed")) + assert g.spent_usd == 0.002 and g.unpriced_runs == 1 and g.runs == 2 + + +def test_guard_live_refuses_untrackable_spend() -> None: + g = SpendGuard(cap_usd=1.0, require_priced=True) + g.charge(_row(None, tokens=50, status="plan_failed")) # failure: estimate + with pytest.raises(BenchSpendAbort, match="no price"): + g.charge(_row(None, tokens=50)) + + +def test_guard_stop_file(tmp_path: Path) -> None: + stop = tmp_path / "STOP" + g = SpendGuard(cap_usd=1.0, stop_file=stop) + g.before_run("routed", "r0") + stop.touch() + with pytest.raises(BenchSpendAbort, match="stop file"): + g.before_run("routed", "r1") + + +def test_guard_rejects_non_positive_cap() -> None: + with pytest.raises(ValueError): + SpendGuard(cap_usd=0) + + +def _priced_failure(*args: Any, **kwargs: Any) -> RunResult: + return RunResult( + run_id=kwargs["run_id"], + status="execution_failed", + response=None, + usage=TokenUsage(input_tokens=80, output_tokens=20, total_tokens=100), + cost=0.004, + ) + + +def test_run_benchmark_aborts_mid_run_and_keeps_rows(tmp_path: Path) -> None: + tasks = [ + BenchTask(f"t{i}", "summarize", "Summarize: sky.", EvalReference()) + for i in range(2) + ] + guard = SpendGuard(cap_usd=0.01) + with ( + patch.object(DynamicSubgraphs, "run", side_effect=_priced_failure), + pytest.raises(BenchSpendAbort), + ): + run_benchmark( + tasks=tasks, + repeats=1, + runs_dir=tmp_path, + router_library=LIB, + bench_id="kill", + planner="mock", + spend_guard=guard, + ) + bench = tmp_path / "bench" / "kill" + rows = (bench / "bench.jsonl").read_text("utf-8").splitlines() + assert len(rows) == 3 # 3 x $0.004 = $0.012 > $0.01: run 4 never starts + spend = json.loads((bench / "spend.json").read_text("utf-8")) + assert spend["spent_usd"] == 0.012 and spend["aborted"] + assert not (bench / "report.json").exists() + + +def test_config_pins_cap_at_top_of_registered_envelope() -> None: + cfg = MainRunConfig.load(CONFIG) + assert cfg.spend_cap_usd == 8.0 + assert cfg.headline_arm == "invented-a2" + assert cfg.dynamic_arms == ("invented-a1", "invented-a2") + assert cfg.baseline_arm == "routed" + + +def test_live_run_refused_without_a_cap(tmp_path: Path) -> None: + cfg = replace(MainRunConfig.load(CONFIG), spend_cap_usd=None) + env = {"OPENAI_API_KEY": "x", "TAVILY_API_KEY": "x"} + with ( + patch.object(DynamicSubgraphs, "run", side_effect=AssertionError("ran")), + pytest.raises(SystemExit, match="no spend cap"), + ): + run_main(cfg, mode="live", runs_dir=tmp_path, env=env) + + +def test_cli_kill_switch_exit_code( + tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + # Cap below one A1 run's estimate: stops before the first run. + rc = main( + [ + "--config", + str(CONFIG), + "--dry-run", + "--max-repeats", + "1", + "--runs-dir", + str(tmp_path), + "--max-spend-usd", + "0.001", + ] + ) + assert rc == 3 + err = capsys.readouterr().err + assert "ABORTED by kill-switch" in err + spend = json.loads( + (tmp_path / "bench" / "main-v1-dryrun" / "spend.json").read_text("utf-8") + ) + assert spend["runs"] == 0 and spend["cap_usd"] == 0.001 diff --git a/tests/test_bench_verdict.py b/tests/test_bench_verdict.py new file mode 100644 index 0000000..c3e10ae --- /dev/null +++ b/tests/test_bench_verdict.py @@ -0,0 +1,378 @@ +"""Golden tests for the frozen §4 analyzer (``dynamic_subgraphs._bench_verdict``). + +Synthetic ``bench.jsonl`` fixtures are built to land on each of the four +verdicts, plus the bar arithmetic the owner signs off on before the paid run +(see docs/evals/bench-main-run-v1.md §6). +""" + +from __future__ import annotations + +import json +import math +from dataclasses import asdict +from pathlib import Path +from typing import Any + +import pytest + +from dynamic_subgraphs._bench_main import MainRunConfig, main +from dynamic_subgraphs._bench_verdict import ( + BOOTSTRAP_RESAMPLES, + BOOTSTRAP_SEED, + INCONCLUSIVE, + KEEP, + KILL, + LEANING, + analyze, + bootstrap_ci, + decide, + load_rows, + min_wins_for_p, + pareto, + required_wins, + sign_test_p, +) +from dynamic_subgraphs.bench import ArmRunRow + +CONFIG = Path("docs/evals/bench-main-v1.config.json") +STRATA = ("compare", "research", "summarize", "extract", "plan", "synthesize") +DYN = ("invented-a1", "invented-a2") + +# --------------------------------------------------------------------------- +# Fixture builder +# --------------------------------------------------------------------------- + +# A per-arm, per-task scenario: (quality, full_cost, planner_cost). Headline +# scores are set equal to blended quality so one number drives everything. +Arm = tuple[float, float, float] + +ROUTER: Arm = (0.80, 0.0010, 0.0) +# Dynamic outcomes against ROUTER, by construction: +WIN: Arm = (0.90, 0.0008, 0.0002) # better and cheaper on both bases +LOSE: Arm = (0.70, 0.0020, 0.0002) # worse and dearer even worker-only +TIE: Arm = (0.90, 0.0020, 0.0002) # better but dearer on both bases -> tie +# Dearer on full cost only because of the planner: worker-only it wins. +TEMPLATE: Arm = (0.90, 0.0014, 0.0006) +LOW_ROUTER: Arm = (0.30, 0.0010, 0.0) +LOW_DYN: Arm = (0.20, 0.0010, 0.0002) + + +def _row( + task_id: str, + task_type: str, + arm: str, + repeat: int, + spec: Arm, + *, + status: str = "ok", +) -> ArmRunRow: + q, cost, planner = spec + ok = status == "ok" + return ArmRunRow( + bench_id="golden", + task_id=task_id, + task_type=task_type, + arm=arm, + repeat=repeat, + run_id=f"golden-{task_id}-{arm}-r{repeat}", + status=status, + quality=q if ok else 0.0, + quality_floor_met=ok and q >= 0.6, + value_per_ktok=None, + cost_usd=cost, + planner_cost_usd=planner if planner else None, + worker_cost_usd=round(cost - planner, 6) if planner else None, + total_tokens=1000, + node_count=1, + topology_signature=None, + structural_quality=q if ok else None, + goal_score=q if ok else None, + ) + + +def build( + dyn_outcomes: list[Arm], + *, + router: list[Arm] | None = None, + repeats: int = 2, +) -> list[ArmRunRow]: + """24 tasks (4 per stratum, in order); both dynamic arms share outcomes.""" + assert len(dyn_outcomes) == 24 + router = router or [ROUTER] * 24 + rows: list[ArmRunRow] = [] + for i, (d, b) in enumerate(zip(dyn_outcomes, router, strict=True)): + tt = STRATA[i // 4] + tid = f"{tt}-{i % 4 + 1}" + for rep in range(repeats): + for arm in DYN: + rows.append(_row(tid, tt, arm, rep, d)) + rows.append(_row(tid, tt, "routed", rep, b)) + return rows + + +def run(rows: list[ArmRunRow]) -> dict[str, Any]: + return analyze(rows, dynamic_arms=DYN, headline_arm="invented-a2") + + +def line(report: dict[str, Any], arm: str, headline: str, scope: str) -> Any: + (hit,) = [ + ln + for ln in report["lines"] + if (ln["dynamic_arm"], ln["headline"], ln["scope"]) == (arm, headline, scope) + ] + return hit + + +def headline_verdicts(report: dict[str, Any]) -> set[str]: + return {ln["verdict"] for ln in report["lines"] if ln["scope"] == "all"} + + +# --------------------------------------------------------------------------- +# Arithmetic the owner signs off on (runbook §6) +# --------------------------------------------------------------------------- + + +def test_sign_test_is_exact_binomial_tail() -> None: + assert sign_test_p(4, 4) == 1 / 16 == 0.0625 + assert sign_test_p(0, 0) == 1.0 + assert sign_test_p(17, 24) == pytest.approx(536155 / 2**24) + assert sign_test_p(17, 24) < 0.05 < sign_test_p(16, 24) + with pytest.raises(ValueError): + sign_test_p(5, 4) + + +def test_stratum_of_four_can_never_reach_p_below_alpha() -> None: + """4 tasks: best one-sided p is 0.0625, so per-stratum is descriptive.""" + assert min_wins_for_p(4) is None + assert required_wins(4, 0) is None + + +def test_headline_bar_is_17_of_24_not_60_percent() -> None: + assert min_wins_for_p(24) == 17 # 71% > 60%: the sign test binds + assert math.ceil(0.6 * 24) == 15 + assert required_wins(24, 0) == 17 + + +def test_ties_move_the_bar() -> None: + # Sign-test bar over decisive tasks only: + assert min_wins_for_p(20) == 15 # 4 ties + assert min_wins_for_p(16) == 12 # 8 ties + # With the 60%-of-eligible share, 8 ties make the share bind instead: + # 12/16 decisive passes p, but 12/24 = 50% < 60%, so 15 wins are needed. + assert required_wins(24, 4) == 15 + assert required_wins(24, 8) == 15 + assert required_wins(24, 10) is None # 14 decisive; 15 needed > 14 + + +def test_pareto_and_decide() -> None: + assert pareto(0.9, 1.0, 0.8, 1.0) == "dynamic" + assert pareto(0.8, 1.0, 0.8, 2.0) == "dynamic" + assert pareto(0.8, 2.0, 0.9, 1.0) == "baseline" + assert pareto(0.9, 2.0, 0.8, 1.0) == "tie" # trade-off + assert pareto(0.8, 1.0, 0.8, 1.0) == "tie" # identical + assert decide(True, True, False, False) == KEEP + assert decide(False, False, True, True) == KILL + assert decide(False, False, True, False) == INCONCLUSIVE # not "even worker" + assert decide(False, True, False, False) == LEANING + assert decide(False, False, False, False) == INCONCLUSIVE + + +def test_bootstrap_is_seeded_and_golden() -> None: + ind = [1] * 18 + [0] * 6 + a = bootstrap_ci(ind) + assert a == bootstrap_ci(ind) == bootstrap_ci(ind, BOOTSTRAP_RESAMPLES, 20260611) + assert BOOTSTRAP_SEED == 20260611 and BOOTSTRAP_RESAMPLES == 10_000 + assert a == (0.5833333333333334, 0.9166666666666666) + assert bootstrap_ci([]) is None + assert bootstrap_ci([1, 1, 1, 1]) == (1.0, 1.0) + + +# --------------------------------------------------------------------------- +# Golden verdicts +# --------------------------------------------------------------------------- + + +def test_golden_keep_with_ties_and_floor_ineligible_tasks() -> None: + # 17 wins, 4 ties, 1 loss, 2 tasks where neither arm meets the floor. + outcomes = [WIN] * 17 + [TIE] * 4 + [LOSE] + [LOW_DYN] * 2 + router = [ROUTER] * 22 + [LOW_ROUTER] * 2 + report = run(build(outcomes, router=router)) + ln = line(report, "invented-a2", "goal", "all") + f = ln["full"] + assert (f["wins"], f["ties"], f["losses"], f["eligible"]) == (17, 4, 1, 22) + assert ln["ineligible"] == 2 and ln["tasks"] == 24 + assert f["p"] == pytest.approx(sign_test_p(17, 18)) + assert f["share"] == pytest.approx(17 / 22) + lo, hi = f["ci"] + assert lo < 17 / 22 < hi + assert ln["verdict"] == KEEP + assert headline_verdicts(report) == {KEEP} + # The λ cut is reported but never decides. + assert ln["lambda_cut"]["wins"] == 21 and "meets_bar" in ln["lambda_cut"] + + +def test_golden_kill_requires_router_win_even_worker_only() -> None: + outcomes = [LOSE] * 18 + [TIE] * 6 + report = run(build(outcomes)) + ln = line(report, "invented-a2", "structural", "all") + assert ln["baseline_full"]["wins"] == 18 + assert ln["baseline_worker"]["wins"] == 18 + assert ln["baseline_worker"]["meets_bar"] + assert ln["verdict"] == KILL + assert headline_verdicts(report) == {KILL} + + +def test_golden_leaning_template_cache() -> None: + """Loses (ties) on full cost because of the planner; wins worker-only.""" + outcomes = [TEMPLATE] * 20 + [TIE] * 4 + report = run(build(outcomes)) + ln = line(report, "invented-a2", "goal", "all") + assert ln["full"]["wins"] == 0 and ln["full"]["ties"] == 24 + assert ln["worker"]["wins"] == 20 and ln["worker"]["meets_bar"] + assert ln["verdict"] == LEANING + assert headline_verdicts(report) == {LEANING} + + +def test_golden_inconclusive_mixed() -> None: + outcomes = [WIN, LOSE] * 12 + report = run(build(outcomes)) + assert headline_verdicts(report) == {INCONCLUSIVE} + f = line(report, "invented-a1", "goal", "all")["full"] + assert (f["wins"], f["losses"]) == (12, 12) + + +def test_one_fewer_win_flips_keep_to_inconclusive() -> None: + keep = run(build([WIN] * 17 + [LOSE] * 7)) + near = run(build([WIN] * 16 + [LOSE] * 8)) + assert line(keep, "invented-a2", "goal", "all")["verdict"] == KEEP + assert line(near, "invented-a2", "goal", "all")["verdict"] == INCONCLUSIVE + + +def test_share_bar_binds_with_many_ties() -> None: + """12 wins / 8 ties / 4 losses: p=0.038 passes, 50% share does not.""" + report = run(build([WIN] * 12 + [TIE] * 8 + [LOSE] * 4)) + f = line(report, "invented-a2", "goal", "all")["full"] + assert f["p"] < 0.05 and f["share"] == 0.5 + assert not f["meets_bar"] + assert line(report, "invented-a2", "goal", "all")["verdict"] == INCONCLUSIVE + + +def test_floor_only_one_arm_met_counts_as_that_arm_winning() -> None: + # Dynamic below floor, router above: router wins regardless of cost. + cheap_low = (0.50, 0.0001, 0.00005) + report = run(build([cheap_low] * 24)) + ln = line(report, "invented-a2", "goal", "all") + assert ln["baseline_full"]["wins"] == 24 and ln["verdict"] == KILL + + +def test_failed_runs_score_zero() -> None: + rows = build([WIN] * 24) + # Fail every repeat of the dynamic arm on one task: mean quality 0. + rows = [ + _row(r.task_id, r.task_type, r.arm, r.repeat, WIN, status="plan_failed") + if (r.task_id == "compare-1" and r.arm in DYN) + else r + for r in rows + ] + report = run(rows) + (pt,) = [ + c + for c in report["per_task"] + if c["task_id"] == "compare-1" + and c["dynamic_arm"] == "invented-a2" + and c["headline"] == "goal" + ] + assert not pt["dynamic_floor_met"] and pt["full"] == "baseline" + + +def test_strata_are_descriptive_and_never_decide() -> None: + report = run(build([WIN] * 24)) + for s in STRATA: + ln = line(report, "invented-a2", "goal", s) + assert ln["full"]["wins"] == 4 and ln["full"]["p"] == 0.0625 + assert not ln["decisive_scope"] and ln["verdict"] == INCONCLUSIVE + + +def test_arms_keyed_by_name_not_origin() -> None: + """A1 and A2 are both 'invented'; each gets its own lines.""" + rows = build([WIN] * 24) + rows = [ + _row(r.task_id, r.task_type, r.arm, r.repeat, LOSE) + if r.arm == "invented-a1" + else r + for r in rows + ] + report = run(rows) + assert line(report, "invented-a1", "goal", "all")["verdict"] == KILL + assert line(report, "invented-a2", "goal", "all")["verdict"] == KEEP + + +def test_unpriced_rows_fall_back_to_tokens_and_warn() -> None: + rows = [ + ArmRunRow(**{**asdict(r), "cost_usd": None, "worker_cost_usd": None}) + for r in build([WIN] * 24) + ] + report = run(rows) + assert any("token cost axis" in w for w in report["warnings"]) + assert {c["cost_axis"] for c in report["per_task"]} == {"tokens"} + + +def test_refuses_mixed_bench_ids_duplicates_and_missing_arms() -> None: + rows = build([WIN] * 24) + with pytest.raises(ValueError, match="bench_ids"): + run([*rows, ArmRunRow(**{**asdict(rows[0]), "bench_id": "other"})]) + with pytest.raises(ValueError, match="duplicate"): + run([*rows, rows[0]]) + with pytest.raises(ValueError, match="no rows"): + run([r for r in rows if r.arm != "routed"]) + + +def test_sizing_check_flags_capped_runs() -> None: + report = analyze( + build([WIN] * 24, repeats=1), + dynamic_arms=DYN, + expected_repeats=MainRunConfig.load(CONFIG).repeats_by_task_type, + ) + assert report["registered_sizing"] is False + assert any("not the registered sizing" in w for w in report["warnings"]) + + +# --------------------------------------------------------------------------- +# CLI +# --------------------------------------------------------------------------- + + +def _write(rows: list[ArmRunRow], path: Path) -> Path: + path.write_text("".join(json.dumps(asdict(r)) + "\n" for r in rows), "utf-8") + return path + + +def test_cli_analyze_writes_json_and_markdown( + tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + jsonl = _write(build([WIN] * 17 + [LOSE] * 7), tmp_path / "bench.jsonl") + assert main(["--config", str(CONFIG), "--analyze", str(jsonl)]) == 0 + out = capsys.readouterr().out + assert "| invented-a2 | goal | all | 24 | 17 | 0 | 7 |" in out + assert "**KEEP**" in out + report = json.loads((tmp_path / "verdict.json").read_text("utf-8")) + assert report["headline_arm"] == "invented-a2" + assert report["dynamic_arms"] == list(DYN) + assert (tmp_path / "verdict.md").read_text("utf-8").startswith("# §4 verdict") + assert len(load_rows(jsonl)) == 24 * 2 * 3 + + +def test_cli_analyze_on_dry_run_output(tmp_path: Path) -> None: + """The analyzer accepts real harness output (capped dry-run for CI speed; + the full 1,152-row dry-run is the same path, see the runbook).""" + runs = tmp_path / "runs" + args = ["--config", str(CONFIG), "--runs-dir", str(runs)] + assert main([*args, "--dry-run", "--max-repeats", "1"]) == 0 + jsonl = runs / "bench" / "main-v1-dryrun" / "bench.jsonl" + assert main(["--config", str(CONFIG), "--analyze", str(jsonl)]) == 0 + report = json.loads((jsonl.parent / "verdict.json").read_text("utf-8")) + assert report["rows"] == 96 and report["tasks"] == 24 + # 2 sub-arms x 2 headlines x (all + 6 strata) + assert len(report["lines"]) == 2 * 2 * 7 + assert report["registered_sizing"] is False # --max-repeats 1 + assert any("mock" in w for w in report["warnings"])