"""Step 7b: System C's judge measured on the 23 dev probes, beside B and the fused top 8. uv run python -m coveragecheck.evals.judge_probes [--ids p01,p05] Evidence only (AgentSystem.evidence: the graph up to select, no answer call): the probes have expected SECTIONS but no gold answers, so what can be measured is what C would show the answer model. The run's judge calls are cached (llm.py), so re-running the report costs nothing. Owner rules (7b): tune on the dev probes ONLY (the draft gold set shaped C's design and is now a development set; the final comparison runs on a new held-out set); at most 2 prompt revisions; no rule may target a specific probe. Pass criteria were declared before the first run (SPEC "Step 7 progress", 7b). Measured per probe: coverage = share of expected sections shown (a shown section counts if it is an expected one or inside one: hits.first_hit), "full" = all shown; the passages shown (after expansion). Variants replayed OFFLINE from the same trace (no extra call): min grade 2 (the 7b default before the change to 1), and round 1 only (what the second search adds). Judge stats: calls, reasks, how often code repaired a grade, the second-round rate, fallbacks, tokens, per-call latency, spend. """ import argparse import json import statistics from datetime import date, datetime from pathlib import Path from coveragecheck import config from coveragecheck.agent.judge import Verdict, select from coveragecheck.evals.hits import first_hit from coveragecheck.evals.probes import load_probes def coverage( sources: list[str], expected: frozenset[str], lineage: dict[str, frozenset[str]] ) -> frozenset[str]: """The expected sections that some shown source is (or sits inside).""" return frozenset(e for e in expected if first_hit(sources, frozenset({e}), lineage)) def verdict_from(round_trace: dict) -> Verdict: """A judge round rebuilt from C's trace (chunk ids instead of rows: select only needs hashable keys), so selection can be replayed without calling the judge.""" requirements = round_trace["requirements"] return Verdict( dict(round_trace["grades"]), [r["need"] for r in requirements], [list(r["stated_by"]) for r in requirements], list(round_trace["queries"]), dict(round_trace.get("raw_grades", {})), ) def replay(trace: dict, min_grade: int, keep: int, second_round: bool = True) -> list[str]: """The chunk ids C would keep (before expansion) under another min grade, or without the second round, from one run's trace. Same rule as the select node, including the fallback to the fused top `keep` when nothing is eligible.""" candidates = list(trace.get("candidates", [])) if "judge" not in trace: return [] rounds = [(candidates, verdict_from(trace["judge"]))] if second_round and "judge_new" in trace: rounds.append((list(trace["research"]["candidates"]), verdict_from(trace["judge_new"]))) kept = select(rounds, keep, min_grade) return kept or candidates[:keep] def repairs(round_trace: dict) -> int: """How many grades code changed (a passage named for a requirement but graded 1 or not at all, raised to 2).""" raw = round_trace.get("raw_grades", {}) return sum(1 for cid, g in round_trace["grades"].items() if raw.get(cid) != g) def dollars(tokens_in: int, tokens_out: int) -> float: """Spend at the answer model's list prices (config).""" return ( tokens_in * config.LLM_PRICE_IN_PER_MTOK + tokens_out * config.LLM_PRICE_OUT_PER_MTOK ) / 1e6 def summarize(rows: list[dict], variants: list[str], baseline: str) -> list[dict]: """Per variant: probes with every expected section shown, with at least one shown, mean coverage, median passages shown, sections the baseline showed that the variant loses (regressions) and sections the baseline missed that the variant shows (gains). A probe where a variant has no result (C failed: AnswerFailed) counts as showing NOTHING, never as absent: dropping it would flatter C (7b design audit).""" empty = {"covered": [], "n_shown": 0} out = [] for name in variants: got = [(r, r["variants"].get(name, empty)) for r in rows] cov = [len(v["covered"]) / len(r["expected"]) for r, v in got] lost = gained = 0 for r, v in got: mine = set(v["covered"]) base = set(r["variants"].get(baseline, empty)["covered"]) lost += len(base - mine) gained += len(mine - base) out.append( { "variant": name, "probes": len(got), "full": sum(1 for r, v in got if len(v["covered"]) == len(r["expected"])), "any": sum(1 for _, v in got if v["covered"]), "mean_coverage": round(statistics.fmean(cov), 3) if cov else 0.0, "median_shown": statistics.median(v["n_shown"] for _, v in got) if got else 0, "lost_vs_" + baseline: lost, "gained_vs_" + baseline: gained, } ) return out def judge_stats(rows: list[dict]) -> dict: """Totals over the probes C judged: calls, reasks, repairs, second rounds, fallbacks, tokens, per-call latency and spend (cache hits replay the original call's usage, so a re-run reports the first run's cost and time).""" judged = [r for r in rows if r.get("trace") and "judge" in r["trace"]] rounds = [r["trace"][k] for r in judged for k in ("judge", "judge_new") if k in r["trace"]] per_call_ms = [x["usage"]["llm_ms"] / max(x["usage"]["calls"], 1) for x in rounds] tin = sum(x["usage"]["tokens_in"] for x in rounds) tout = sum(x["usage"]["tokens_out"] for x in rounds) return { "probes_judged": len(judged), "errors": sum(1 for r in rows if r.get("error")), "judge_calls": sum(x["usage"]["calls"] for x in rounds), "reasks": sum(x["usage"]["reasks"] for x in rounds), "repaired_grades": sum(repairs(x) for x in rounds), "second_rounds": sum(1 for r in judged if "judge_new" in r["trace"]), "fallbacks": sum(1 for r in judged if r["trace"].get("fallback")), "tokens_in_mean": round(tin / len(rounds)) if rounds else 0, "tokens_out_mean": round(tout / len(rounds)) if rounds else 0, "call_ms_p50": round(statistics.median(per_call_ms)) if per_call_ms else 0, "call_ms_max": round(max(per_call_ms)) if per_call_ms else 0, "usd": round(dollars(tin, tout), 4), } def report(rows: list[dict], variants: list[str], baseline: str) -> list[str]: """The printed report: the variant table, the judge stats, then one line per probe (coverage per variant, so every gain and loss can be read by hand).""" lines = ["variant | full | any | mean cov | median shown | lost | gained"] for s in summarize(rows, variants, baseline): lines.append( f"{s['variant']} | {s['full']}/{s['probes']} | {s['any']} | {s['mean_coverage']:.3f} | " f"{s['median_shown']} | {s['lost_vs_' + baseline]} | {s['gained_vs_' + baseline]}" ) lines.append("judge: " + json.dumps(judge_stats(rows))) for r in rows: cells = " ".join( f"{name}={len(v['covered'])}/{len(r['expected'])}" for name, v in r["variants"].items() ) extra = f" ERROR {r['error']}" if r.get("error") else "" lines.append(f"{r['id']} {cells}{extra}") return lines def main() -> None: # pragma: no cover - runs the models; tested through its parts from coveragecheck.agent.graph import AgentSystem, no_reranker from coveragecheck.agent.schemas import AnswerFailed from coveragecheck.evals.hits import ancestry from coveragecheck.evals.run import git_commit from coveragecheck.index import dense from coveragecheck.index.store import load_table from coveragecheck.llm import LLM from coveragecheck.retrieve.structured import StructuredRetriever, fastembed_reranker parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) parser.add_argument("--ids", help="comma-separated probe ids (default: all)") args = parser.parse_args() probes = load_probes() if args.ids: wanted = args.ids.split(",") unknown = sorted(set(wanted) - {p.id for p in probes}) if unknown: raise SystemExit(f"unknown probe id(s): {unknown}") probes = [p for p in probes if p.id in wanted] embedder = dense.fastembed_embedder() c = AgentSystem(StructuredRetriever.load(embedder, no_reranker), LLM.load(), checker=None) b = StructuredRetriever.load(embedder, fastembed_reranker()) b.warm_up() lineage = ancestry(load_table(config.INDEX_DIR / "sections.parquet")) hybrid = c.retriever.retriever row_of = {cid: i for i, cid in enumerate(hybrid.chunk_ids)} today = datetime.now().date() def expanded(kept: list[str], day: date) -> list[str]: rows = [row_of[x] for x in kept] rows += [e.row for e in c.retriever.expand_rows(rows, day)] return [hybrid.source_ids[x] for x in rows] out = [] for p in probes: day = p.policy_date or today fused = [x.row for x in hybrid.search(p.question, day).candidates[: config.JUDGE_KEEP]] shown = { "b": b.retrieve(p.question, day).source_ids, "fused8": [hybrid.source_ids[x] for x in fused], } row = {"id": p.id, "kind": p.kind, "expected": sorted(p.expected), "day": day.isoformat()} try: ev = c.evidence(p.question, day) shown["c"] = ev.source_ids shown["c_grade2"] = expanded(replay(ev.trace, 2, c.keep), day) shown["c_round1"] = expanded(replay(ev.trace, c.min_grade, c.keep, False), day) row["trace"] = ev.trace except AnswerFailed as failure: row["error"], row["trace"] = failure.kind, failure.work.trace row["variants"] = { name: {"covered": sorted(coverage(src, p.expected, lineage)), "n_shown": len(src)} for name, src in shown.items() } out.append(row) print( p.id, {k: f"{len(v['covered'])}/{len(p.expected)}" for k, v in row["variants"].items()}, flush=True, ) names = ["b", "fused8", "c", "c_grade2", "c_round1"] print("\n".join(report(out, names, "b"))) stamp = datetime.now().strftime("%Y%m%d-%H%M%S") path = config.RUNS_DIR / f"judge-probes-{stamp}.jsonl" path.parent.mkdir(parents=True, exist_ok=True) meta = { "meta": {"commit": git_commit(), "settings": c.settings, "probes": [p.id for p in probes]} } path.write_text( "\n".join(json.dumps(x) for x in [meta, *out]) + "\n", encoding="utf-8", newline="\n" ) print("saved", Path(path).relative_to(config.ROOT)) if __name__ == "__main__": main()