10A.8 Regression Testing, CI and Experiment Tracking

ProductionLesson 8 of 1212,338 words10 parts
Module 10A · 0 of 12 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12

An eval that only runs when someone remembers to run it is a vibe check with extra steps. This lesson turns the evals of lessons 10A.1–10A.7 into engineering gates: a tiered suite that runs on every commit, statistical rules for deciding "did this change make things worse?" without being fooled by noise, a fast runner with record/replay caching and a spend cap, pytest and GitHub Actions wiring, experiment tracking so every number is reproducible, and the playbooks for the four changes that actually break LLM systems — prompts, models, retrieval indexes and dependencies.

What you'll learn

  • What belongs in a regression gate: which changes trigger evals, how to pick a baseline, and the four kinds of thresholds (absolute floors, relative non-regression, per-slice floors, cost/latency budgets), plus grouped cases and the cluster bootstrap
  • How to make evals fast and cheap: tiered suites (smoke / PR / nightly / pre-release), record/replay caching of model calls, batch APIs, cheap-judge-first tiering, bounded parallelism and budget caps
  • evalkit/runner.py and evalkit/compare.py: a bounded-parallel runner with a call cache and result store, plus paired statistics and gate evaluation — all pure stdlib, all runnable on fixtures with no keys
  • pytest integration (parametrised cases, markers, JUnit/JSON reports, pytest-xdist, and how promptfoo, DeepEval and Inspect AI plug into pytest) and a complete GitHub Actions workflow
  • Experiment tracking: what to log per run, where results should live, the tool landscape (MLflow, Weights & Biases Weave, Langfuse, LangSmith, Braintrust, Phoenix, Opik, DVC, or plain JSONL), run comparison, leaderboards and reproducibility
  • Playbooks for model upgrades and deprecations, prompt changes, retrieval/index rebuilds and dependency upgrades — including shadow evaluation, canary rollouts and rollback
  • Test hygiene: keeping eval data out of prompts, held-out discipline, rotating canary cases, dataset versioning in CI and flaky-test triage

What you don't need

  • API keys. Every code sample in this lesson runs on fixtures with no network; the parts that would call a provider are marked and their output is labelled illustrative. The pytest and GitHub Actions files are reference configurations — they are shown, not executed.
  • Statistics beyond means and "a range that probably contains the true value". The bootstrap, permutation test and confidence-interval reasoning are all implemented in plain Python and explained as they appear.
  • The eval methodology itself. Datasets are 10A.2, scorers and metrics are 10A.3, judges are 10A.4–10A.5, and RAG/agent/multimodal metrics are 10A.6–10A.7. This lesson assumes you have a suite that produces scores; it is about what you do with those scores.

Setup

This lesson's code is pure Python standard library — no packages to install. If you are starting the evalkit package fresh:

bash
uv init evalkit --bare --python 3.13 && cd evalkit
mkdir -p evalkit tests               # the package directory, and the folder Part 5 uses for pytest files

The two modules this lesson adds are evalkit/runner.py and evalkit/compare.py, both printed in full in Part 4 (§4.1 and §4.2). Part 6 adds a thin evalkit/cli.py wrapper. For the pytest parts (Part 5) add:

bash
uv add pytest pytest-xdist        # or: pip install pytest pytest-xdist

The pytest samples were checked against pytest 9.2.0 and pytest-xdist 3.8.0 (the current releases as of November 2026; xdist is MIT-licensed). A plain install gives you the newest release. The GitHub Actions workflow in Part 6 needs no local setup — it runs on GitHub's runners.


What you must be able to do after this lesson#

  • Decide which changes should trigger an eval and pick a baseline
  • Set absolute, relative and per-slice thresholds for a gate
  • Use paired statistics to decide whether a change is a real regression
  • Split evals into smoke, PR and nightly tiers and cache model calls
  • Run evals from pytest and a GitHub Actions workflow
  • Follow a playbook for a model upgrade or prompt change

Why this matters for an AI engineer#

You'll hear... You'll understand it after...
"We ran the evals and it looked fine." 1.1 What triggers an eval
"Is v2 better than v1, or is that noise?" 2.3 Paired comparisons
"The gate is flaky — it fails on Mondays." 2.5 Taming flaky gates
"Our eval suite takes 40 minutes and costs $30." Part 3: Fast and cheap
"Just cache the model calls." 3.2 Record/replay caching — and why a warm cache can hide a real regression
"Run the evals on every PR." Part 5: pytest and Part 6: GitHub Actions
"Which experiment was that number from?" Part 7: Experiment tracking
"The provider is retiring our model next month." 8.1 The model-upgrade playbook
"We shipped the prompt change and quality dropped." 8.2 The prompt-change playbook and Part 9: Test hygiene

Part 1: From eval to regression gate#

1.1 What triggers an eval#

A regression gate answers one question: did this change make the system worse? The first design decision is therefore not the threshold — it is the trigger: which changes are allowed to ship without a fresh eval, and which must run one. The honest answer is that almost everything that can change model behaviour is a trigger:

What changed Why it can regress quality Cheapest sufficient suite
Prompt text / template / few-shot examples The prompt is the program; a deleted rule or reordered section silently changes outputs (04.9) Smoke + the prompt's own golden cases
Model ID, snapshot or provider Weights, post-training and serving stack all differ; even a pinned snapshot's behaviour drifts (02.9, Part 8) Full suite, shadow run before cutover
Sampling / reasoning parameters (max_tokens, effort, verbosity) Changes answer length, completeness and cost at once Smoke + cost/latency budgets
Tool definitions, schemas, MCP servers The model chooses tools by their descriptions; a renamed argument breaks calls (08) Agent/tool-call eval slice
Retrieval config: chunking, embedding model, index, reranker, filters Different chunks in context → different grounded answers (05.9, Part 5, 06.10) Retrieval metrics first (cheap, deterministic), then RAG eval
Ingestion data / corpus content The answer can only be as good as what was ingested Data-quality checks (05.10) + spot RAG cases
Application code around the model (parsing, routing, retries, context assembly) A json.loads that now tolerates a new shape changes what downstream sees Unit tests + contract tests (03.10) + smoke eval
Dependencies (SDK bumps, judge model, scorer libraries) An SDK upgrade can change request serialisation; a judge upgrade re-baselines every score Offline suite on cassettes + a judge canary set
Nothing — scheduled Providers ship silent serving changes; corpora drift; judges drift Nightly extended suite

The rule that falls out: the eval trigger list is part of the change-management policy, not an implementation detail. Write it down next to your CI config, because the failure mode is always the same — someone changes the retrieval top-k "just as a config tweak" and nobody re-runs the RAG eval.

1.2 Baseline selection: what exactly are you comparing against?#

A gate needs a baseline: the recorded result of the last known-good configuration. Three mistakes make baselines useless:

  1. Comparing against "whatever ran last". If the last run was itself a regression that slipped through, every subsequent comparison inherits the damage. The baseline should be the last accepted run — the one a human or an automated gate signed off.
  2. Comparing across different units. A score is a function of (dataset version, prompt version, model snapshot, scorer version, judge version). Comparing triage@1.1 on claude-haiku-5-5 against triage@1.0 on gpt-6-luna measures a model swap and a prompt change and possibly a dataset edit, and tells you nothing about which mattered. The baseline manifest must record the full tuple; the comparison must either hold it fixed or change exactly one element.
  3. No baseline at all on first run. The first run of a new suite establishes the baseline; it cannot gate against anything. Say so in the report rather than letting a green first run imply quality.

Good baseline hygiene, concretely:

  • Store every accepted run's results.jsonl + manifest (see Part 4) under a name like runs/triage-v1-baseline/.
  • The baseline is a directory, not a number: per-case scores let you do paired comparisons later; an aggregate "0.87" does not.
  • Re-baseline deliberately. When a change is accepted because it improves quality, promote its run to baseline and record why in the run's manifest notes field.
  • Keep the baseline's dataset fingerprint. If the eval set itself changed (cases added, labels corrected), paired diffs computed against the old baseline silently drop the new cases — correct behaviour, but it must be visible, not accidental.

1.3 Thresholds and gates#

A gate is the rule that turns scores into a ship/no-ship decision. Four threshold types cover almost everything, and they answer different questions:

Threshold Question it answers Example Failure mode if misused
Absolute floor (min_overall) "Is the system good enough, period?" Pass rate ≥ 0.80 on the golden set Set too high → permanent red; too low → meaningless green
Relative non-regression (max_drop) "Did this change make it worse than the accepted baseline?" Mean score may not drop more than 2% vs baseline On a noisy metric, point-estimate comparisons flap; use the CI rule in 2.5
Per-slice floor (slice_floors) "Did we regress on the slice that matters?" billing slice ≥ 0.90 even if overall is fine Too many slices → multiple-comparison noise (2.6)
Operational budget (max_cost_usd, max_p95_latency_ms) "Can we afford to ship this?" Eval run ≤ $5; p95 latency ≤ 4s Budgets belong in the gate, not in a dashboard nobody reads

Three structural choices matter as much as the numbers:

  • Gate only on regression evals. 10A.1, 5.5 separates capability evals (a low pass rate on purpose, a hill to climb) from regression evals (cases that already pass and must keep passing). A capability eval is reported but never blocks a merge: a failing case there means "not solved yet", not "broken". Tag cases suite=capability or suite=regression, point every threshold below at the regression slice, and graduate a capability case once it passes consistently.
  • Blocking vs advisory. A blocking failure stops the merge/deploy. Reserve it for hard requirements: must-pass safety cases, schema validity, the absolute floor, egregious regressions. Everything statistical-but-uncertain — a possible 1% dip inside noise — should be advisory: reported loudly, posted to the PR, but not blocking. A gate that blocks on noise trains people to ignore it, and then it blocks on the real regression too.
  • Known failures (allow-lists). Every mature suite has cases that fail for reasons nobody is fixing this quarter — a provider limitation, a genuinely ambiguous label, a bug scheduled for next sprint. The honest pattern is an allow-list with an expiry: the case is excluded from the gate by name, with a reason and a review date, and the suite reports "3 allow-listed failures" separately so they can't silently become permanent. An allow-list without expiry is how "known issue" becomes "invisible issue". Part 9 covers the discipline.

1.4 The demo that motivates the rest of the lesson#

Everything in Parts 2–4 exists because of one uncomfortable fact, which the code in this lesson reproduces exactly. Two versions of a triage prompt score identically on the aggregate — 0.833 both — while the set of failing cases moved: v2 fixes an edge case and breaks a billing case. A gate that only looks at the mean passes a change that broke the slice users care about. The paired, sliced, CI-aware gate in Part 4 catches it. Keep that example in mind; it is the running fixture for the rest of the lesson.


Part 2: Statistical decisions in CI#

2.1 Where the noise comes from#

A CI gate fails for two completely different reasons: the system got worse, or the measurement moved. Before writing any threshold, enumerate the noise sources in your pipeline:

Noise source Magnitude Mitigation
Model non-determinism Small per call, but flips near-ties; one flipped token changes the whole answer (02.5, Part 7) Repeated runs, pass-rate metrics, structured outputs, pinned snapshots
Sampling noise (small eval set) A 12-case suite at 83% has a confidence interval roughly ±25 points wide More cases, or accept wider gates; 2.4 tells you the n you need
Judge noise The judge itself is a model: run-to-run verdict flips, position bias (10A.4, 10A.5) Judge repeats averaged, binary verdicts over 1–10 scales, judge version pinned in the manifest
Infrastructure flakes 429s, timeouts, provider 5xx, expired keys Infra-error classification (Part 4), retries with backoff (03.8), never count them as quality failures
Dataset drift The eval set changed but nobody noticed dataset_fingerprint in every manifest (4.2)

The first three are signal-shaped noise: they look like quality changes. The last is a process bug. Treat them differently.

2.2 Repeated runs: what repeats=k actually measures#

Running each case k times and averaging answers "how reliably does the system pass this case?" — the pass-rate view. It is the right tool for two questions:

  • Gate stability: a case that passes 9/10 runs is meaningfully different from one that passes 5/10, even if both "passed" once.
  • Variance characterisation: pass^k-style metrics (10A.7) need all-k-success rates, which single runs can't give.

But repeats have a hard interaction with caching, and getting it wrong fabricates certainty:

A pragmatic policy: gates run repeats=1 live (one honest sample per case, statistics across cases do the work), and characterisation runs use repeats=3–5 on a fresh cache a few times per release, with results stored as the baseline.

2.3 Paired comparisons: is B better than A?#

When candidate and baseline run on the same cases, compare them paired: per-case difference d_i = score_B(i) − score_A(i), then ask whether the mean of d is distinguishable from zero. Pairing is the whole trick — hard cases are hard for both systems, so their difficulty cancels out and the comparison becomes far more sensitive than comparing two independent means.

Two complementary tests, both in evalkit/compare.py (§4.1 code):

  • Paired bootstrap CI — resample the per-case differences with replacement 10,000 times and report the middle 95%. If the interval excludes zero, the difference is real at this sample size; if it straddles zero, you cannot tell.
  • Sign-flip permutation p-value — under the null hypothesis each difference is symmetric about zero, so randomly flipping signs gives the null distribution. The p-value is the fraction of permutations as extreme as observed. Assumption-light: no normality needed, works on 0/1 accuracy scores.

And always report the effect size (paired Cohen's d = mean(d)/sd(d)): a "significant" +0.01 gain on 2,000 cases can be real and still not matter. Statistical significance answers "is it real?"; effect size answers "is it worth shipping?" — a gate needs both.

2.4 Minimum detectable effect#

Before running an experiment, ask: if the true improvement is X, will n cases show it? The minimum detectable effect (MDE) is the smallest mean paired difference your design can reliably detect:

text
MDE ≈ (z_{1−α/2} + z_{power}) · sd(differences) / √n

The demo's numbers make it concrete — with per-case difference SD ≈ 0.43 (typical when most cases are all-or-nothing):

n cases MDE (α=0.05, power=0.8)
12 ≈ 0.35
50 ≈ 0.17
100 ≈ 0.12
300 ≈ 0.07

A 12-case smoke suite cannot detect a 5% quality change — it would need the true effect to be ~35 points. That's not a reason to abandon small suites (they catch gross regressions cheaply), but it is the reason a "no significant difference" result on 30 cases means "we can't tell", not "it's fine". Write the MDE next to the result; it is the honest error bar on your conclusion.

2.5 Taming flaky gates#

A flaky gate is worse than no gate: it trains the team to re-run until green, and the re-run culture eventually merges the real regression. The fixes, in order of leverage:

  1. Gate on the confidence bound, not the point estimate — for non-regression. evalkit.compare.evaluate_gate implements the rule: FAIL only when the paired bootstrap CI proves the drop exceeds tolerance; WARN (advisory, non-blocking) when the CI straddles it. A wide CI produces a warning, not a coin-flip block.
  2. Hard floors use point estimates + minimum n. "Must-pass" cases are deterministic assertions (schema valid, no PII, citation exists) — they don't need statistics, they need min_cases so a 3-case run can't "pass".
  3. Retry infrastructure, not verdicts. A case that ended infra_error is retried by the runner's caller or marked not_run — it is excluded from quality statistics, never scored 0. Part 4 shows the classifier.
  4. Variance budgets. Track each metric's run-to-run SD over recent runs; alert when it grows (the system got flakier) even if the mean holds. A mean-stable but variance-doubling model is a production incident waiting for a bad-luck user.
  5. One automatic re-run, then human. For borderline gate results, a single confirmation run on a fresh sample is legitimate if the policy is written down and the second run is the one that counts. Two runs and pick the better is p-hacking; a pre-registered "borderline → one confirm run" rule is not.

2.6 Multiple comparisons and sequential testing#

Two statistical traps specific to sliced eval reporting:

  • Multiple comparisons. If you compute a CI for 20 slices, ~1 will exclude zero by chance alone (at α=0.05). Slice floors should be few and pre-registered (the 3–5 slices that matter), and borderline slice findings should be labelled "needs more data" rather than declared regressions. If you do scan many slices, widen the interval (Bonferroni: use α/k per slice) or accept that you're exploring, not confirming.
  • Sequential testing / peeking. Checking the gate every hour and shipping when it first goes green inflates false positives — you're sampling until noise looks like signal. Either fix the evaluation schedule (gate runs are discrete events: PR, nightly, release) or use a sequential method designed for continuous monitoring. For eval gates, discrete scheduled runs are almost always the right answer; continuous monitoring is an online-evaluation concern (10A.9).

2.7 Grouped cases: when the cases are not independent#

Every interval in this part resamples cases as if each were an independent observation. Many real datasets break that assumption: ten questions written from one document, the turns of one conversation, a seed ticket and its paraphrases, every ticket from one customer. Cases in a group tend to pass or fail together (one hard document sinks all ten of its questions), so n grouped cases carry less information than n independent ones, and the per-case bootstrap in compare.py gives an interval that is too narrow: it manufactures false regressions and false wins. 10A.2, 6.7 explains the design effect and gives a cluster bootstrap for a single pass rate; the paired version for a gate resamples whole groups of differences. Tag each case with its group (doc, conversation_id, customer) and use this function instead of paired_bootstrap_ci whenever such a tag exists (save it as evalkit/cluster.py and run python3 evalkit/cluster.py from the project root):

python
# evalkit/cluster.py
import random
import statistics


def paired_cluster_bootstrap_ci(diffs_by_group: dict[str, list[float]], *,
                                iters: int = 10_000, alpha: float = 0.05,
                                seed: int = 0) -> tuple[float, float, float]:
    """CI for the mean paired difference when cases come in groups (several
    questions per document, turns per conversation). Resamples whole GROUPS
    with replacement, so cases that pass or fail together are not counted as
    independent evidence. Returns (mean, lo, hi) over all cases."""
    groups = list(diffs_by_group.values())
    if len(groups) < 2:
        raise ValueError("need at least two groups to resample")
    all_diffs = [d for g in groups for d in g]
    rng = random.Random(seed)
    means = []
    for _ in range(iters):
        picked = rng.choices(groups, k=len(groups))
        flat = [d for g in picked for d in g]
        means.append(statistics.fmean(flat))
    means.sort()
    return (statistics.fmean(all_diffs),
            means[int(alpha / 2 * iters)],
            means[min(int((1 - alpha / 2) * iters), iters - 1)])


if __name__ == "__main__":
    # 8 documents x 5 questions; v2 fixes whole documents or breaks them
    by_doc = {f"doc-{i}": [d] * 5 for i, d in
              enumerate([1, 1, 1, 0, 0, 0, 0, -1])}   # +3 docs, -1 doc
    flat = [d for g in by_doc.values() for d in g]
    from compare import paired_bootstrap_ci   # flat import: run this file by path
    m, lo, hi = paired_bootstrap_ci(flat)
    print(f"per-case bootstrap  : mean {m:+.3f}  CI [{lo:+.3f}, {hi:+.3f}]  (n={len(flat)})")
    m, lo, hi = paired_cluster_bootstrap_ci(by_doc)
    print(f"cluster bootstrap   : mean {m:+.3f}  CI [{lo:+.3f}, {hi:+.3f}]  (groups={len(by_doc)})")

Output (real — deterministic, pure stdlib; the demo is extreme on purpose: 8 documents of 5 questions each, where v2 fixes 3 documents entirely and breaks 1):

text
per-case bootstrap  : mean +0.250  CI [+0.050, +0.450]  (n=40)
cluster bootstrap   : mean +0.250  CI [-0.250, +0.750]  (groups=8)

The per-case interval says "v2 is better, confidently". The cluster interval says what the data really support: eight documents is eight observations, and the CI straddles zero. The same rule applies to the slice floors and the MDE table above: size and read them by the number of groups, not only the number of cases, and keep group-aware splits (10A.2, 6.7) so tuning data never shares a document with the gate set. To feed the function from the runner's results, group scores_by_case differences by the tag value you chose (for example with slice_values-style grouping on a doc tag).


Part 3: Making evals fast and cheap#

A suite that costs $30 and takes 40 minutes will be run once a week, and weekly evals miss regressions for six days. The design goal is the right eval at the right cadence: cheap enough to run often, deep enough to catch what matters.

3.1 Tiered suites#

Tier When it runs Size What it uses What it catches
Smoke Every commit / every PR ~20 cases, repeats=1 Fake/replay client OR cheapest live model Plumbing breaks: prompt template errors, parse failures, schema violations, gross regressions
PR eval PRs touching prompts/models/eval config ~50–150 cases Live calls on the pinned model, bounded workers Real quality regressions on the changed component
Nightly Schedule, off-peak Full golden set + extended slices, repeats=2–3 Live calls, possibly batch API Slow drift, slice regressions, variance growth, judge drift
Pre-release Before a model/prompt promotion, on demand Exhaustive: full set × repeats, all providers/models in matrix Batch APIs, highest budget The decision-grade evidence for a ship call

The tiers gate on the regression slice only (10A.1, 5.5); capability cases ride along in the nightly tier as reported trend lines. The tiers compose: smoke is a subset of the PR suite, which is a subset of nightly. Keep them as named slices of one dataset (tags: ["smoke"] on ~20 cases — or the equivalent tag on your dataset's own schema) so "the smoke suite" can never drift away from "the real suite" — a hand-picked second dataset is a second thing to maintain and a second thing to be wrong.

When even the nightly set is too big: sample, don't skip. Production-derived datasets grow to tens of thousands of cases, and no tier budget survives running all of them nightly. The fix is a stratified, seeded sample: draw cases proportionally within each slice dimension (tags["type"], difficulty, language) so a 2% adversarial slice doesn't vanish from a 5% sample, and fix the RNG seed so the sample is reproducible and recorded in the manifest. Two rules keep it honest:

  • Size the sample from the MDE table (2.4): if the change you're watching for is 5 points and n=100 gives MDE ≈ 0.12, the sample is too small to see it — sample more, or accept that this run can only catch gross regressions and say so in the report.
  • Sampling is for iteration tiers, never for the pre-release decision. The ship/no-ship run uses the full set (or the batch API, 3.3); a sample that happened to miss the one broken slice is exactly the failure sampling introduces.
python
import random


def stratified_sample(cases, frac=0.2, seed=20261106):
    """Proportional sample within each `type` tag; deterministic via seed.
    `cases` need a `.tags` dict — EvalExample (10A.2) and the runner's JSONL
    cases both have one."""
    rng = random.Random(seed)
    by_type = {}
    for c in cases:
        by_type.setdefault(c.tags.get("type", "_untagged"), []).append(c)
    return [c for tag in sorted(by_type)
            for c in rng.sample(by_type[tag],
                                max(1, round(len(by_type[tag]) * frac)))]

Record sample_frac, sample_seed and n_sampled/n_total in the run manifest (7.1) — a sampled number that looks like a full-set number is how teams fool themselves twice.

flowchart TD
    A["commit / PR"] --> B["smoke suite<br/>~20 cases, fake or replay<br/>seconds, $0"]
    B --> C{"paths touched<br/>prompts / models / evals?"}
    C -->|no| D["merge"]
    C -->|yes| E["PR eval<br/>~100 cases, live pinned model<br/>minutes, ~$0.5–2"]
    E --> F{"gate verdict"}
    F -->|pass| D
    F -->|fail| G["block merge<br/>or advisory comment"]
    D --> H["nightly: full suite<br/>+ repeats + extended slices"]
    H --> I["pre-release: exhaustive<br/>matrix over models, batch API"]
    I --> J["promote / rollback decision"]

3.2 Record/replay caching of model calls#

The HTTP-level version of this idea — VCR-style cassettes — is 03.10, Part 7.5, and it is the right tool for testing your plumbing. The eval-level version is different in an important way: it caches at the call seam inside your task, keyed by everything that can change the answer — function name, model ID, generation params, and the full payload (the rendered prompt + inputs). evalkit.runner.CallCache + cached_call (Part 4 code) implement it as append-only JSONL.

Four properties make it safe to reason about:

  • The key is the contract. Prompt edit, model bump, parameter change → different key → cache miss → live call. A cache that can't tell the system changed is worse than no cache.
  • Exceptions are never cached. A 429 or timeout today must not replay as a 429 forever.
  • TTL (max_age_s). Records expire; a week-old replay can't hide this week's silent provider update.
  • Per-key locking. N parallel workers asking the same question coalesce: one pays, the rest replay.

And the failure it exists to prevent — and to cause, if misused:

3.3 Batch APIs for big suites#

When a suite needs thousands of calls and latency doesn't matter — nightly runs, pre-release matrices, judge scoring over a full dataset — the Batch APIs roughly halve cost at the price of waiting (03.9, Part 6). The eval-specific rules:

  • Never batch the smoke or PR tier — you need the answer in minutes, not hours.
  • Batch the judge calls too. Judge scoring is often 3–10× the generator's token count; batching it is the single biggest eval-cost lever after caching.
  • Join on your own IDs. Results come back out of order; carry case_id/custom_id through (the deterministic-ID discipline of 03.9, 6.3 applies verbatim).
  • Batches have their own failure model: one job, per-request results, possible expiry. Reconcile results against the submitted manifest and resubmit only failures — 03.9 owns the lifecycle.

3.4 Cheap-judge-first, bounded parallelism, and provider uptime#

Three cost/robustness patterns that multiply:

  • Tiered judging. Run the cheap judge (small model, deterministic scorer) on everything; escalate to the strong judge only on disagreement, low confidence, or a sampled audit fraction. A 10× cheaper judge that agrees with the strong one 90% of the time cuts judge spend ~10× for a measured quality cost — measure the agreement first (10A.5 owns that validation).
  • Bounded concurrency, always. run_suite(workers=4) caps in-flight calls. Provider rate limits are per-key and shared with production; an eval that melts the quota at 2am is an outage, not a test. Size workers to your rate-limit tier (03.8, Part 9, 03.9, 4.7) and to CI runner count.
  • Infra failures are not quality failures. The runner classifies exceptions: provider 429/timeout/5xx → infra_error (retried or excluded); anything else → task_error (a bug — should fail loudly). Counting a provider outage as "quality dropped to zero" produces the worst possible CI story: a red gate that says nothing about your code. Part 4 shows the classifier seam.

3.5 Budget caps#

Every run gets a Budget(max_calls=..., max_cost_usd=..., cost_of=...): checked before each call, raised as BudgetExceeded, remaining cases marked not_run. The budget is shared by every worker thread, so it holds a lock; check() reserves a call slot atomically, which means calls counts calls that were started (including ones that then raised an exception), and the cost cap is enforced from the booked cost, so once it is reached no later case makes a live call. Calls already in flight on other workers still finish and can overshoot a cost cap by their own price. A runaway loop, a retry storm or a misconfigured repeats=100 stops at the cap instead of the invoice. Cost per run is also a first-class metric in the manifest — eval spend is a budget line, and you can't manage what you don't record (03.7 owns the per-call cost math).

A spend cap is only as good as the cost it is fed, so the budget refuses to trust a bad one. If cost_of returns NaN (which is never greater than the cap), a negative number (which refunds spend), infinity, a non-number, or raises, the budget marks itself broken, raises BudgetExceeded, and refuses every later call; a NaN or negative cap is rejected at construction. These three tests hold that behaviour (save as test_budget_attacks.py next to the evalkit package):

python
# test_budget_attacks.py — costs that would have slipped under a spend cap.
# Run from the project root: python3 -m unittest test_budget_attacks -v
import math
import unittest

from evalkit.runner import Budget, BudgetExceeded


class BudgetAttackTests(unittest.TestCase):
    def test_a_cost_that_cannot_be_trusted_stops_the_run(self):
        for bad in (math.nan, -5.0, "0.3", None, math.inf):
            budget = Budget(max_cost_usd=1.0, cost_of=lambda output, bad=bad: bad)
            budget.check()
            with self.assertRaises(BudgetExceeded):
                budget.spend("output")
            with self.assertRaises(BudgetExceeded):   # and every later call is refused
                budget.check()

    def test_a_cost_function_that_raises_is_not_a_free_call(self):
        budget = Budget(max_cost_usd=1.0, cost_of=lambda output: 1 / 0)
        budget.check()
        with self.assertRaises(BudgetExceeded):
            budget.spend("output")

    def test_a_nan_or_negative_cap_is_refused(self):
        for kwargs in ({"max_calls": math.nan}, {"max_cost_usd": -1.0}, {"max_calls": True}):
            with self.assertRaises(ValueError):
                Budget(**kwargs)


if __name__ == "__main__":
    unittest.main()

Run python3 -m unittest test_budget_attacks -v and you get real output:

text
test_a_cost_function_that_raises_is_not_a_free_call ... ok
test_a_cost_that_cannot_be_trusted_stops_the_run ... ok
test_a_nan_or_negative_cap_is_refused ... ok

----------------------------------------------------------------------
Ran 3 tests in 0.000s

OK

Part 4: The runner and the result store#

4.1 evalkit/compare.py — the statistics#

Everything in Part 2 is implemented here: bootstrap CIs, paired differences, the permutation test, effect size, minimum detectable effect, and evaluate_gate — the function that turns a MetricSummary plus optional paired diffs into a pass/warn/fail verdict. Pure stdlib, deterministic given a seed.

python
# evalkit/compare.py
"""evalkit/compare.py — paired statistics and gate evaluation. Stdlib only.

Everything here is deterministic given a seed, so a CI gate is reproducible:
the same run records and the same baseline always produce the same verdict.
"""
from __future__ import annotations

import math
import random
import statistics
from dataclasses import dataclass, field


# ---------------------------------------------------------------------------
# Descriptive summary with a bootstrap interval
# ---------------------------------------------------------------------------

@dataclass
class MetricSummary:
    """One metric over one run: the point estimate, its uncertainty, and slices."""
    mean: float
    n: int
    ci_lo: float
    ci_hi: float
    slices: dict[str, float] = field(default_factory=dict)
    slice_n: dict[str, int] = field(default_factory=dict)


def bootstrap_mean_ci(values: list[float], *, iters: int = 10_000,
                      alpha: float = 0.05, seed: int = 0) -> tuple[float, float, float]:
    """Percentile bootstrap CI for the MEAN of `values`.

    Resample the observations with replacement `iters` times, recompute the
    mean each time, and report the (alpha/2, 1-alpha/2) percentiles. Returns
    (mean, lo, hi). With fewer than ~20 values the interval is honest but wide;
    that's the point — it tells you the sample is too small to be sure.
    """
    n = len(values)
    if n == 0:
        raise ValueError("bootstrap_mean_ci needs at least one value")
    mean = statistics.fmean(values)
    if n == 1:
        return mean, mean, mean
    rng = random.Random(seed)
    means = sorted(
        statistics.fmean(rng.choices(values, k=n)) for _ in range(iters)
    )
    lo = means[int((alpha / 2) * iters)]
    hi = means[min(int((1 - alpha / 2) * iters), iters - 1)]
    return mean, lo, hi


def summarise_metric(values: list[float], *,
                     slices: dict[str, list[float]] | None = None,
                     iters: int = 10_000, seed: int = 0) -> MetricSummary:
    """Summarise one metric overall and per slice (slice name -> values)."""
    mean, lo, hi = bootstrap_mean_ci(values, iters=iters, seed=seed)
    out = MetricSummary(mean=mean, n=len(values), ci_lo=lo, ci_hi=hi)
    for name, vals in (slices or {}).items():
        if not vals:
            continue
        out.slices[name] = statistics.fmean(vals)
        out.slice_n[name] = len(vals)
    return out


# ---------------------------------------------------------------------------
# Paired comparison: is B better than A on the SAME cases?
# ---------------------------------------------------------------------------

def paired_diffs(scores_a: dict[str, float], scores_b: dict[str, float]) -> list[float]:
    """Per-case differences b - a, restricted to cases both runs scored."""
    shared = sorted(set(scores_a) & set(scores_b))
    return [scores_b[c] - scores_a[c] for c in shared]


def paired_bootstrap_ci(diffs: list[float], *, iters: int = 10_000,
                        alpha: float = 0.05, seed: int = 0) -> tuple[float, float, float]:
    """CI for the MEAN paired difference. Reuses bootstrap_mean_ci: the paired
    difference IS the unit of resampling, which is what makes the comparison
    sensitive to small real effects — case difficulty cancels out."""
    return bootstrap_mean_ci(diffs, iters=iters, alpha=alpha, seed=seed)


def sign_flip_permutation_p(diffs: list[float], *, iters: int = 20_000,
                            seed: int = 0) -> float:
    """Two-sided permutation p-value for 'is the mean difference non-zero?'.

    Under the null hypothesis each paired difference is symmetric about zero,
    so randomly flipping signs gives the null distribution of the mean. The
    p-value is the fraction of permutations at least as extreme as observed.
    """
    n = len(diffs)
    if n == 0:
        raise ValueError("need at least one paired difference")
    observed = abs(statistics.fmean(diffs))
    rng = random.Random(seed)
    extreme = 0
    for _ in range(iters):
        perm = statistics.fmean(d * rng.choice((-1.0, 1.0)) for d in diffs)
        if abs(perm) >= observed:
            extreme += 1
    return (extreme + 1) / (iters + 1)   # +1 keeps p > 0 (never claim certainty)


def paired_effect_size(diffs: list[float]) -> float:
    """Cohen's d for paired data: mean(diffs) / sd(diffs).

    |d| ~ 0.2 small, ~0.5 medium, ~0.8 large — a rule of thumb, not a law.
    A 'statistically significant' 0.5-point gain that is d=0.05 is noise wearing
    a costume; report the effect size next to the p-value.

    Edge cases: `nan` with fewer than 2 diffs; `0.0` when every diff is zero
    (no change at all); `±inf` when every diff is identical and non-zero.
    `json.dumps` writes non-finite values as bare `Infinity`/`NaN`, which
    strict JSON parsers reject — map them to `None` before serialising a
    report.
    """
    if len(diffs) < 2:
        return float("nan")
    mean, sd = statistics.fmean(diffs), statistics.stdev(diffs)
    if sd == 0:
        return 0.0 if mean == 0 else math.copysign(float("inf"), mean)
    return mean / sd


def _normal_quantile(p: float) -> float:
    """Inverse standard normal CDF (Acklam's rational approximation, |err| < 1e-9)."""
    a = [-3.969683028665376e+01, 2.209460984245205e+02, -2.759285104469687e+02,
         1.383577518672690e+02, -3.066479806614716e+01, 2.506628277459239e+00]
    b = [-5.447609879822406e+01, 1.615858368580409e+02, -1.556989798598866e+02,
         6.680131188771972e+01, -1.328068155288572e+01]
    c = [-7.784894002430293e-03, -3.223964580411365e-01, -2.400758277161838e+00,
         -2.549732539343734e+00, 4.374664141464968e+00, 2.938163982698783e+00]
    d = [7.784695709041462e-03, 3.224671290700398e-01, 2.445134137142996e+00,
         3.754408661907416e+00]
    plow, phigh = 0.02425, 1 - 0.02425
    if p < plow:
        q = math.sqrt(-2 * math.log(p))
        return (((((c[0] * q + c[1]) * q + c[2]) * q + c[3]) * q + c[4]) * q + c[5]) / \
               ((((d[0] * q + d[1]) * q + d[2]) * q + d[3]) * q + 1)
    if p > phigh:
        q = math.sqrt(-2 * math.log(1 - p))
        return -(((((c[0] * q + c[1]) * q + c[2]) * q + c[3]) * q + c[4]) * q + c[5]) / \
                ((((d[0] * q + d[1]) * q + d[2]) * q + d[3]) * q + 1)
    q = p - 0.5
    r = q * q
    return (((((a[0] * r + a[1]) * r + a[2]) * r + a[3]) * r + a[4]) * r + a[5]) * q / \
           (((((b[0] * r + b[1]) * r + b[2]) * r + b[3]) * r + b[4]) * r + 1)


def min_detectable_effect(n_pairs: int, sd_diff: float, *,
                          alpha: float = 0.05, power: float = 0.8) -> float:
    """Smallest mean paired difference a study of `n_pairs` cases can detect.

    Normal approximation: MDE = (z_{1-alpha/2} + z_{power}) * sd / sqrt(n).
    Use it BEFORE the run: if your hoped-for improvement is below the MDE, the
    eval cannot see it and 'no significant difference' will be the answer no
    matter what. sd_diff is the SD of the paired differences — usually much
    smaller than the SD of raw scores, which is why pairing helps.
    """
    if n_pairs < 2 or sd_diff <= 0:
        return float("nan")
    z_a = _normal_quantile(1 - alpha / 2)
    z_b = _normal_quantile(power)
    return (z_a + z_b) * sd_diff / math.sqrt(n_pairs)


# ---------------------------------------------------------------------------
# Gate evaluation
# ---------------------------------------------------------------------------

@dataclass
class GateThresholds:
    """The rules a run must satisfy to ship. All optional; set what you need.

    - min_overall:        hard floor on the headline metric's point estimate.
    - max_drop:           tolerated drop vs baseline, as a fraction of the
                          baseline mean (0.02 = 'may not fall more than 2%').
                          Judged with a paired bootstrap CI, not a point diff.
    - slice_floors:       {slice_name: minimum mean} — per-slice hard floors.
    - min_cases:          refuse to pass a run smaller than this (anti-'30 cases').
    - max_cost_usd:       budget caps on the run itself.
    - max_p95_latency_ms: operational budgets count as gate criteria too.
    """
    min_overall: float | None = None
    max_drop: float | None = None
    slice_floors: dict[str, float] = field(default_factory=dict)
    min_cases: int = 1
    max_cost_usd: float | None = None
    max_p95_latency_ms: float | None = None


@dataclass
class GateResult:
    passed: bool
    failures: list[str] = field(default_factory=list)
    warnings: list[str] = field(default_factory=list)


def _pct(values: list[float], q: float) -> float:
    if not values:
        return float("nan")
    xs = sorted(values)
    return xs[min(int(q * (len(xs) - 1)), len(xs) - 1)]


def evaluate_gate(current: MetricSummary,
                  diffs_vs_baseline: list[float] | None,
                  thresholds: GateThresholds,
                  *,
                  baseline_mean: float | None = None,
                  cost_usd: float | None = None,
                  latencies_ms: list[float] | None = None,
                  alpha: float = 0.05) -> GateResult:
    """Decide pass/fail for one metric against its thresholds.

    `diffs_vs_baseline` are the paired per-case differences (current - baseline)
    for the SAME cases; pass None when there is no baseline (first run, or the
    baseline predates paired scoring). The non-regression rule is deliberately
    CI-based:

      - FAIL  when the bootstrap CI shows the drop exceeds the tolerance with
               confidence (upper bound of the diff CI < -tolerance * baseline).
      - WARN  when the CI straddles the tolerance: possibly a regression, but
               the sample is too small to be sure — do not block on it, do
               investigate it.
      - PASS  otherwise.

    A point-estimate gate on a noisy metric is how teams get a red build on
    Monday and a green one on Tuesday with no code change.
    """
    res = GateResult(passed=True)

    if current.n < thresholds.min_cases:
        res.passed = False
        res.failures.append(
            f"only {current.n} cases scored; gate requires >= {thresholds.min_cases}"
        )

    if thresholds.min_overall is not None:
        if current.mean < thresholds.min_overall:
            res.passed = False
            res.failures.append(
                f"mean {current.mean:.3f} < floor {thresholds.min_overall:.3f}"
            )
        elif current.ci_lo < thresholds.min_overall:
            res.warnings.append(
                f"mean {current.mean:.3f} passes floor {thresholds.min_overall:.3f} "
                f"but CI [{current.ci_lo:.3f}, {current.ci_hi:.3f}] dips below it"
            )

    if thresholds.max_drop is not None and baseline_mean is not None:
        if diffs_vs_baseline:
            d_mean, d_lo, d_hi = paired_bootstrap_ci(diffs_vs_baseline)
            drop = -d_mean                      # positive = current worse
            tol_abs = thresholds.max_drop * abs(baseline_mean)
            if d_hi < -tol_abs:
                res.passed = False
                res.failures.append(
                    f"drop {drop:.3f} exceeds tolerance {tol_abs:.3f} "
                    f"(paired diff CI [{d_lo:.3f}, {d_hi:.3f}], n={len(diffs_vs_baseline)})"
                )
            elif d_lo < -tol_abs:
                res.warnings.append(
                    f"possible drop {drop:.3f} near tolerance {tol_abs:.3f}; "
                    f"CI [{d_lo:.3f}, {d_hi:.3f}] too wide to be sure — investigate"
                )
        else:
            res.warnings.append(
                "max_drop set but no paired baseline diffs; non-regression not checked"
            )

    for name, floor in thresholds.slice_floors.items():
        val = current.slices.get(name)
        n = current.slice_n.get(name, 0)
        if val is None:
            res.warnings.append(f"slice '{name}' missing from this run")
            continue
        if val < floor:
            res.passed = False
            res.failures.append(f"slice '{name}' mean {val:.3f} < floor {floor:.3f}")
        elif n < 30:
            res.warnings.append(
                f"slice '{name}' has only {n} cases; its floor is noisy"
            )

    if thresholds.max_cost_usd is not None and cost_usd is not None:
        if cost_usd > thresholds.max_cost_usd:
            res.passed = False
            res.failures.append(
                f"cost ${cost_usd:.2f} > budget ${thresholds.max_cost_usd:.2f}"
            )

    if thresholds.max_p95_latency_ms is not None and latencies_ms:
        p95 = _pct(latencies_ms, 0.95)
        if p95 > thresholds.max_p95_latency_ms:
            res.passed = False
            res.failures.append(
                f"p95 latency {p95:.0f}ms > budget {thresholds.max_p95_latency_ms:.0f}ms"
            )

    return res

Two details worth noticing in evaluate_gate:

  • max_drop is judged on the paired bootstrap CI of the differences, not on baseline.mean - current.mean. The CI rule produces three outcomes — confident fail, confident pass, and "too wide to tell" (a warning, not a block). That middle state is where most real gate decisions live on small suites.
  • Slice floors check current.slices, which summarise_metric fills from per-slice value lists — the runner copies each case's .tags/.metadata onto CaseResult.slices, and slice_values(results, metric, dim=...) groups scores by one tag dimension for exactly this.

4.2 evalkit/runner.py — the engine#

The runner owns three concerns: the CallCache seam (3.2), run_suite (bounded parallelism, repeats, infra classification, budget), and ResultStore/save_run (JSONL + manifest). It is deliberately agnostic about what a "case" is: _case_id accepts .id or .example_id (the field name 10A.2's EvalExample uses), and _case_slices reads .tags/.metadata for slice breakdowns — so dataset cases drop in with no wrapper. Scorers are the one real adapter: they take (case, output) and return a float, so 10A.3's Score-returning graders go through run_graders plus a small collapse — the three-line shim is in 5.1.

python
# evalkit/runner.py
"""evalkit/runner.py — bounded-parallel eval runner, call cache, result store.

Stdlib only. The runner never looks inside a case beyond `.id`; scorers and the
task under test are plain callables, so the whole thing runs on fakes.

Layers, cheapest first:
  CallCache   — record/replay ONE model call, keyed by everything that changes
                the answer (function, model, params, payload). Distinct from
                the HTTP cassettes of lesson 03.10: this caches at the call
                seam, so it works for any provider and survives SDK changes.
  run_suite   — runs (case x scorer) work on a thread pool with a hard worker
                bound, per-case repeats, an infra-error classifier, and a
                spend cap that stops the run instead of the invoice.
  ResultStore — appends one JSONL row per case-run plus a manifest, so every
                number in a report can be traced to the exact run that made it.
"""
from __future__ import annotations

import hashlib
import json
import math
import os
import platform
import subprocess
import threading
import time
import uuid
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Callable, Iterable, Protocol, Sequence


# ---------------------------------------------------------------------------
# The seams: what a "case" and a "score" look like to the runner
# ---------------------------------------------------------------------------

class CaseLike(Protocol):
    """Documentation of the case contract — not enforced at runtime.

    The runner reads `.id` for result rows (or `.example_id`, the field name
    10A.2's `EvalExample` uses — see `_case_id`) and `.tags`/`.metadata` for
    slice breakdowns. Everything else belongs to the task and scorers.
    """


Task = Callable[[Any], Any]               # case -> raw system output
Scorer = Callable[[Any, Any], float]      # (case, output) -> score in [0, 1]
InfraClassifier = Callable[[BaseException], bool]  # is this exception a provider/infra failure?


# ---------------------------------------------------------------------------
# CallCache: record/replay at the model-call seam
# ---------------------------------------------------------------------------

def _canonical(obj: Any) -> str:
    """Stable JSON for cache keys: sorted keys, no whitespace."""
    return json.dumps(obj, sort_keys=True, separators=(",", ":"), default=str)


class CallCache:
    """JSONL-backed record/replay for model calls.

    Key = sha256 of {fn, model, params, payload} — everything that can change
    the answer. A prompt edit, a model bump or a parameter change is a cache
    MISS by design: evals must notice when the thing under test changed.
    Replays return the recorded response verbatim, so a cached eval run is
    deterministic and free.

    The file is append-only JSONL: safe to share between runs, and `get`
    replays the LAST record written for a key — the file is the log, so the
    newest write wins on every load, in every process. Re-recording a key
    overwrites the replay; `refresh(key)` drops a key entirely when the
    recorded answer is known-stale.

    `max_age_s` makes records expire: a replay older than the TTL counts as a
    miss, the next `put` becomes the record later processes replay, and TTL
    expiry actually works across runs. Without a TTL, a warm cache can hide a
    provider-side model update — the recorded answer replays while production
    quietly degraded.
    """

    def __init__(self, path: str | Path, *, enabled: bool = True,
                 max_age_s: float | None = None):
        self.path = Path(path)
        self.enabled = enabled
        self.max_age_s = max_age_s
        self._index: dict[str, dict] | None = None
        self._guard = threading.Lock()
        self._key_locks: dict[str, threading.Lock] = {}
        self.hits = 0
        self.misses = 0

    def lock_for(self, key: str) -> threading.Lock:
        """Per-key lock so concurrent identical calls coalesce: the second
        caller waits for the first to record, then replays instead of paying
        for a duplicate call."""
        with self._guard:
            return self._key_locks.setdefault(key, threading.Lock())

    def _load(self) -> dict[str, dict]:
        if self._index is None:
            with self._guard:
                if self._index is None:
                    self._index = {}
                    if self.path.exists():
                        for line in self.path.read_text().splitlines():
                            if not line.strip():
                                continue
                            rec = json.loads(line)
                            # last write wins: append-only file, so the newest
                            # record for a key is always its last line
                            self._index[rec["key"]] = rec
        return self._index

    @staticmethod
    def make_key(fn: str, model: str | None, params: dict | None,
                 payload: Any) -> str:
        return hashlib.sha256(_canonical(
            {"fn": fn, "model": model, "params": params or {}, "payload": payload}
        ).encode()).hexdigest()

    def _fresh(self, rec: dict) -> bool:
        """Is this record inside the TTL? Records written before `recorded_epoch`
        existed (older cache files) are treated as fresh — fail open, not closed."""
        if self.max_age_s is None:
            return True
        epoch = rec.get("recorded_epoch")
        return epoch is None or (time.time() - epoch) <= self.max_age_s

    def get(self, key: str) -> dict | None:
        if not self.enabled:
            return None
        rec = self._load().get(key)
        if rec is not None and self._fresh(rec):
            self.hits += 1
            return rec["response"]
        self.misses += 1
        return None

    def peek(self, key: str) -> dict | None:
        """Lookup without touching the hit/miss counters — for the re-check
        inside `cached_call`'s per-key lock, where the fast-path `get` already
        counted this call."""
        if not self.enabled:
            return None
        rec = self._load().get(key)
        return rec["response"] if (rec is not None and self._fresh(rec)) else None

    def put(self, key: str, fn: str, model: str | None, params: dict | None,
            payload: Any, response: Any, *, usage: dict | None = None,
            latency_ms: float | None = None, extra: dict | None = None) -> None:
        if not self.enabled:
            return
        rec = {
            "key": key, "fn": fn, "model": model, "params": params or {},
            "payload_sha": hashlib.sha256(_canonical(payload).encode()).hexdigest()[:16],
            "response": response, "usage": usage, "latency_ms": latency_ms,
            "recorded_epoch": time.time(),
            "recorded_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
            "extra": extra or {},
        }
        self.path.parent.mkdir(parents=True, exist_ok=True)
        with self.path.open("a") as f:
            f.write(json.dumps(rec, default=str) + "\n")
        self._load()[key] = rec

    def stats(self) -> dict[str, int]:
        return {"hits": self.hits, "misses": self.misses,
                "entries": len(self._load())}

    def clear(self) -> None:
        """Drop the in-memory index (the file stays; delete it to truly reset)."""
        self._index = None
        self.hits = self.misses = 0

    def refresh(self, key: str) -> None:
        """Drop every stored record for `key` — file AND index — so the next
        `get` misses and `cached_call` makes a live call. Use when you know
        the recorded answer is stale (e.g. after a provider-side change you
        want to re-measure) rather than waiting out the TTL. Call it between
        runs, not while workers are mid-flight."""
        self._load().pop(key, None)
        if not self.path.exists():
            return
        kept = [ln for ln in self.path.read_text().splitlines()
                if ln.strip() and json.loads(ln).get("key") != key]
        self.path.write_text("".join(ln + "\n" for ln in kept))


def cached_call(cache: CallCache, *, fn: str, model: str | None,
                params: dict | None, payload: Any,
                call: Callable[[], Any],
                usage_of: Callable[[Any], dict | None] | None = None) -> Any:
    """The one-line seam every model call in an eval should go through.

        answer = cached_call(cache, fn="triage", model=MODEL, params=PARAMS,
                             payload=messages, call=lambda: client.chat(...))

    Returns the recorded response on a hit; on a miss runs `call`, stores the
    response (plus usage and wall-clock latency when `usage_of` is given) and
    returns it. Exceptions are never cached — a 429 today must not replay as a
    429 forever.

    Identical calls that arrive concurrently coalesce on a per-key lock: the
    first records, the rest replay. Without it, N parallel workers asking the
    same question would each pay for a live call before the first record lands.

    IMPORTANT for evals: a repeat that HITS the cache returns the recorded
    answer, so `repeats=k` against a warm cache measures zero variance. Use a
    fresh cache (or `enabled=False`) when repeats exist to sample the model's
    run-to-run noise; use the warm cache when you want a deterministic,
    free replay of an already-measured run.
    """
    key = CallCache.make_key(fn, model, params, payload)
    hit = cache.get(key)
    if hit is not None:
        return hit
    with cache.lock_for(key):
        hit = cache.peek(key)         # re-check: a concurrent caller may have recorded
        if hit is not None:
            cache.hits += 1           # it was a hit after all: the fast-path `get`
            cache.misses -= 1         # booked a miss for this call, so undo it
            return hit
        t0 = time.perf_counter()
        response = call()
        ms = (time.perf_counter() - t0) * 1000
        cache.put(key, fn, model, params, payload, response,
                  usage=usage_of(response) if usage_of else None, latency_ms=ms)
        return response


# ---------------------------------------------------------------------------
# run_suite: bounded parallelism, repeats, infra classification, budget cap
# ---------------------------------------------------------------------------

@dataclass
class CaseResult:
    case_id: str
    status: str                      # ok | infra_error | task_error | scorer_error | not_run
    scores: dict[str, float] = field(default_factory=dict)
    output: Any = None
    output_truncated: bool = False
    error: str | None = None
    error_kind: str | None = None    # which exception class, for triage
    latency_ms: float = 0.0
    repeat: int = 0                  # which repetition of the case this row is
    slices: dict[str, str] = field(default_factory=dict)  # case tags/metadata, for breakdowns

    def to_json(self) -> str:
        return json.dumps(self.__dict__, default=str)


@dataclass
class RunConfig:
    workers: int = 4                 # hard bound on concurrent task calls
    repeats: int = 1                 # runs per case; >1 exposes run-to-run noise
    keep_output: bool = True         # store raw outputs (needed for debugging,
                                     # costly in storage — turn off for huge runs)
    max_output_chars: int = 4000     # stored outputs are truncated beyond this
    seed: int = 0


class BudgetExceeded(Exception):
    """Raised inside a worker when the run's call/cost budget is spent."""


class Budget:
    """A spend/volume cap for one run, safe to share between worker threads.

    `check()` runs BEFORE each task call: it reserves one call (so `max_calls`
    is a hard cap even with several workers in flight) and refuses once the
    cost already spent has reached `max_cost_usd`. `spend(output)` runs AFTER
    the call, when the price is known (`cost_of(output)`, e.g. from token
    usage). Once the cap is crossed, `check()` stops every later case instead
    of letting it quietly spend more; only calls already in flight on other
    workers still finish."""

    def __init__(self, *, max_calls: int | None = None,
                 max_cost_usd: float | None = None,
                 cost_of: Callable[[Any], float] | None = None):
        # A NaN cap compares False with everything, so it would never fire.
        for name, cap in (("max_calls", max_calls), ("max_cost_usd", max_cost_usd)):
            if cap is not None and (isinstance(cap, bool) or not isinstance(cap, (int, float))
                                    or math.isnan(cap) or cap < 0):
                raise ValueError(f"{name} must be a non-negative number or None, got {cap!r}")
        self.max_calls = max_calls
        self.max_cost_usd = max_cost_usd
        self.cost_of = cost_of or (lambda _out: 0.0)
        self.calls = 0
        self.cost_usd = 0.0
        self._broken: str | None = None   # set when a cost cannot be trusted
        self._lock = threading.Lock()

    def check(self) -> None:
        """Pre-call gate: reserve a call slot or raise BudgetExceeded."""
        with self._lock:
            if self._broken:
                raise BudgetExceeded(f"budget disabled: {self._broken}")
            if self.max_calls is not None and self.calls >= self.max_calls:
                raise BudgetExceeded(
                    f"call budget exhausted: {self.calls} >= {self.max_calls}")
            if self.max_cost_usd is not None and self.cost_usd >= self.max_cost_usd:
                raise BudgetExceeded(
                    f"cost budget exhausted: ${self.cost_usd:.2f} >= ${self.max_cost_usd:.2f}")
            self.calls += 1

    def spend(self, output: Any) -> None:
        """Post-call: book the cost; raise if this call crossed the cost cap."""
        with self._lock:
            try:
                cost = self.cost_of(output)
            except Exception as exc:  # noqa: BLE001 — an unreadable price is not a free call
                cost = exc
            if (isinstance(cost, BaseException) or isinstance(cost, bool)
                    or not isinstance(cost, (int, float)) or not 0 <= cost < math.inf):
                # NaN, infinity, a negative number or an exception: adding it would
                # either never trip the cap (NaN) or refund spend (negative). Stop the
                # whole run instead of guessing, and say why.
                self._broken = f"cost_of returned {cost!r}"
                raise BudgetExceeded(f"cost could not be read ({self._broken}); run stopped")
            self.cost_usd += cost
            if self.max_cost_usd is not None and self.cost_usd > self.max_cost_usd:
                raise BudgetExceeded(
                    f"cost budget exceeded: ${self.cost_usd:.2f} > ${self.max_cost_usd:.2f}")

    def summary(self) -> dict:
        return {"calls": self.calls, "cost_usd": round(self.cost_usd, 6)}


_INFRA_NAME_HINTS = (
    "timeout", "ratelimit", "rate_limit", "overloaded",
    "connection", "apierror", "apiconnection", "internalserver",
    "servererror", "serviceunavailable", "deadlineexceeded",
    "resourceexhausted",
)
_GRPC_TRANSIENT = {"unavailable", "resource_exhausted", "deadline_exceeded",
                   "aborted", "internal", "unknown", "cancelled"}


def _is_infra(exc: BaseException, infra: InfraClassifier | None) -> bool:
    """Default classifier: exceptions that mean 'the provider/environment failed',
    not 'the system under test is bad'. Override per deployment — e.g.
    03.8's error classifier already knows each SDK's exception families.

    Two signals, either sufficient: the exception class name (TimeoutError,
    RateLimitError, InternalServerError, google-genai's ServerError, api_core's
    ServiceUnavailable/ResourceExhausted/DeadlineExceeded ...) or an HTTP/gRPC
    status the SDK attaches (`status_code`/`code`/`status`: 408, 409, 425, 429,
    5xx, or a gRPC status name). Non-transient 4xx — bad model name,
    malformed request, auth failures — stays a task_error: your request is
    wrong, fail loudly. The transient 4xx above (408 timeout, 409 conflict,
    425 too-early, 429 rate limit) count as infra because retrying usually
    clears them.
    """
    if infra is not None:
        return infra(exc)
    name = type(exc).__name__.lower()
    if any(k in name for k in _INFRA_NAME_HINTS):
        return True
    for attr in ("status_code", "code", "status"):
        v = getattr(exc, attr, None)
        if v is None or isinstance(v, bool):
            continue
        if isinstance(v, int):
            if v in (408, 409, 425, 429) or v >= 500:
                return True
        elif isinstance(v, str):
            s = v.strip().lower()
            if s.lstrip("-").isdigit():
                n = int(s)
                if n in (408, 409, 425, 429) or n >= 500:
                    return True
            elif s in _GRPC_TRANSIENT:
                return True
    return False


def _truncate(out: Any, limit: int) -> tuple[Any, bool]:
    if isinstance(out, str) and len(out) > limit:
        return out[:limit] + "…", True
    return out, False


def _case_id(case: Any) -> Any:
    """Case identity for result rows and fingerprints: `.id` first, then
    `.example_id` (the field name 10A.2's `EvalExample` uses), then the case
    itself — plain strings and ints work as their own id."""
    cid = getattr(case, "id", None)
    if cid is None:
        cid = getattr(case, "example_id", None)
    return cid if cid is not None else case


def _case_slices(case: Any) -> dict[str, str]:
    """Slice tags copied onto the result row: `.tags` (10A.2's EvalExample)
    or `.metadata` (10A.1's Example); anything mapping-like, else empty."""
    for attr in ("tags", "metadata"):
        val = getattr(case, attr, None)
        if not val:
            continue
        try:
            return {str(k): str(v) for k, v in dict(val).items()}
        except (TypeError, ValueError):
            continue
    return {}


def _run_one(case: Any, repeat: int, task: Task, scorers: dict[str, Scorer],
             cfg: RunConfig, budget: Budget | None,
             infra: InfraClassifier | None) -> CaseResult:
    cid = str(_case_id(case))
    res = CaseResult(case_id=cid, status="ok", repeat=repeat,
                     slices=_case_slices(case))
    t0 = time.perf_counter()
    try:
        if budget is not None:
            budget.check()
        output = task(case)
        if budget is not None:
            budget.spend(output)
    except BudgetExceeded as e:
        res.status, res.error, res.error_kind = "not_run", str(e), "budget"
        return res
    except Exception as e:                                    # noqa: BLE001
        res.status = "infra_error" if _is_infra(e, infra) else "task_error"
        res.error, res.error_kind = str(e), type(e).__name__
        res.latency_ms = (time.perf_counter() - t0) * 1000
        return res
    res.latency_ms = (time.perf_counter() - t0) * 1000
    if cfg.keep_output:
        res.output, res.output_truncated = _truncate(output, cfg.max_output_chars)
    for name, scorer in scorers.items():
        try:
            res.scores[name] = float(scorer(case, output))
        except Exception as e:                                # noqa: BLE001
            res.status = "scorer_error"
            res.error = f"scorer '{name}': {e}"
            res.error_kind = type(e).__name__
            break
    return res


def run_suite(cases: Sequence[Any], task: Task, scorers: dict[str, Scorer] | None = None,
              *, cfg: RunConfig | None = None, budget: Budget | None = None,
              infra: InfraClassifier | None = None) -> list[CaseResult]:
    """Run every case (x `cfg.repeats`) through `task`, score, collect results.

    Concurrency is a hard bound (`cfg.workers`), never unbounded: provider rate
    limits are per-key, and an eval that melts the quota starves production.
    Results are returned sorted by (case_id, repeat); collection happens in
    completion order, so per-row wall time isn't meaningful — use `latency_ms`.
    """
    cfg = cfg or RunConfig()
    scorers = scorers or {}
    jobs = [(c, r) for c in cases for r in range(cfg.repeats)]
    results: list[CaseResult] = []
    with ThreadPoolExecutor(max_workers=max(1, cfg.workers)) as pool:
        futs = [pool.submit(_run_one, c, r, task, scorers, cfg, budget, infra)
                for c, r in jobs]
        for fut in as_completed(futs):
            results.append(fut.result())
    return sorted(results, key=lambda r: (r.case_id, r.repeat))


# ---------------------------------------------------------------------------
# ResultStore: one JSONL row per case-run + a manifest per run
# ---------------------------------------------------------------------------

def _git_commit(cwd: str | Path = ".") -> str | None:
    try:
        return subprocess.run(
            ["git", "rev-parse", "--short", "HEAD"], cwd=cwd,
            capture_output=True, text=True, timeout=5,
        ).stdout.strip() or None
    except Exception:                                          # noqa: BLE001
        return None


def _case_content(case: Any) -> Any:
    """Best-effort serialisable content of a case, for fingerprinting.
    pydantic models give `model_dump`, dataclasses and plain objects give
    `__dict__`, anything else falls back to `repr` — the fingerprint only
    needs to be stable for a given dataset, not portable across languages."""
    if isinstance(case, dict):
        return case
    for meth in ("model_dump", "to_dict", "dict"):
        fn = getattr(case, meth, None)
        if callable(fn):
            try:
                return fn()
            except Exception:                                  # noqa: BLE001
                pass
    d = getattr(case, "__dict__", None)
    if isinstance(d, dict):
        return d
    return repr(case)


def dataset_fingerprint(cases: Sequence[Any]) -> str:
    """Stable hash of case ids + content + order.

    Catches 'the eval set changed' even when nobody bumped a version file —
    including the sneaky edit: a corrected `expected`/`inputs`/rubric under
    an unchanged `example_id`. Pair it with the dataset's own version for
    provenance; the fingerprint is the change detector, not the changelog.
    """
    h = hashlib.sha256()
    for c in cases:
        h.update(str(_case_id(c)).encode())
        h.update(b"\x00")
        try:
            content = _canonical(_case_content(c))
        except Exception:                                      # noqa: BLE001
            content = repr(c)
        h.update(content.encode())
        h.update(b"\x00")
    return h.hexdigest()[:16]


def save_run(results: Sequence[CaseResult], out_dir: str | Path, *,
             name: str, system: dict[str, Any],
             extra: dict[str, Any] | None = None) -> Path:
    """Write `results.jsonl` + `run.json` (the manifest) under out_dir/name/.

    `system` is the provenance block: dataset version+fingerprint, git SHA,
    model/prompt/judge versions, config — whatever identifies WHAT was measured.
    Every number in a report must be reproducible from a manifest like this.
    """
    out = Path(out_dir) / name
    out.mkdir(parents=True, exist_ok=True)
    (out / "results.jsonl").write_text(
        "".join(r.to_json() + "\n" for r in results))
    manifest = {
        "run": name,
        "created_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
        "git_sha": _git_commit(),
        "python": platform.python_version(),
        "n_results": len(results),
        "system": system,
        **(extra or {}),
    }
    (out / "run.json").write_text(json.dumps(manifest, indent=2, default=str) + "\n")
    return out


def load_run(path: str | Path) -> list[CaseResult]:
    """Read a results.jsonl back (or a run directory containing one)."""
    p = Path(path)
    if p.is_dir():
        p = p / "results.jsonl"
    rows = []
    for line in p.read_text().splitlines():
        if line.strip():
            d = json.loads(line)
            rows.append(CaseResult(**{k: v for k, v in d.items()
                                      if k in CaseResult.__dataclass_fields__}))
    return rows


# ---------------------------------------------------------------------------
# Aggregation helpers used by the report and the gate
# ---------------------------------------------------------------------------

def scores_by_case(results: Sequence[CaseResult],
                   metric: str) -> dict[str, float]:
    """case_id -> mean score across repeats (the unit paired comparisons use)."""
    acc: dict[str, list[float]] = {}
    for r in results:
        if metric in r.scores:
            acc.setdefault(r.case_id, []).append(r.scores[metric])
    return {cid: sum(v) / len(v) for cid, v in acc.items()}


def status_counts(results: Sequence[CaseResult]) -> dict[str, int]:
    counts: dict[str, int] = {}
    for r in results:
        counts[r.status] = counts.get(r.status, 0) + 1
    return counts


def slice_values(results: Sequence[CaseResult], metric: str,
                 *, dim: str | None = None) -> dict[str, list[float]]:
    """Per-slice score lists, shaped for `summarise_metric(slices=...)`.

    `dim` picks one tag dimension copied onto each row by `_case_slices`
    (e.g. `dim="type"` on 10A.2's EvalExample.tags): slices are keyed by the
    tag VALUE ("billing", "edge"). `dim=None` flattens every tag into
    "dim=value" slices so no dimension is silently dropped — a case tagged
    {"type": "billing", "channel": "email"} lands in both.
    """
    out: dict[str, list[float]] = {}
    for r in results:
        if metric not in r.scores:
            continue
        if dim is None:
            pairs = [(f"{k}={v}", r.scores[metric]) for k, v in r.slices.items()]
        elif dim in r.slices:
            pairs = [(r.slices[dim], r.scores[metric])]
        else:
            continue
        for name, val in pairs:
            out.setdefault(name, []).append(val)
    return out

4.3 The demo run (real output)#

The fixture: 12 support-ticket triage cases, a fake "model" that answers deterministically, repeats=3, workers=4, a warm CallCache. Two prompt versions that score identically in aggregate while the failing set moves — v2 fixes edge case t-012 and breaks billing case t-009. Output below is real, produced by running the code in this lesson's work directory:

text
Output:

=== run_suite: 12 cases x 3 repeats = 36 rows per run ===
statuses v1: {'ok': 36} | v2: {'ok': 36}
wall time: v1 9ms, v2 8ms
cache stats: {'hits': 48, 'misses': 24, 'entries': 24}
saved run -> runs/triage-v1-baseline

=== paired comparison v2 - v1 (accuracy) ===
v1 mean 0.833 -> v2 mean 0.833
per-case diffs: [+0, +0, +0, +0, +0, +0, +0, +0, -1, +0, +0, +1]
mean diff +0.000  95% CI [-0.250, +0.250]  p=1.0000  d=+0.00
billing slice mean: 1.000 -> 0.750
edge    slice mean: 0.000 -> 0.500

=== gate: v2 vs v1 (floor 0.75, drop<=5%, billing>=0.9) ===
passed: False
  FAIL: slice 'billing' mean 0.750 < floor 0.900
  warn: mean 0.833 passes floor 0.750 but CI [0.583, 1.000] dips below it
  warn: possible drop -0.000 near tolerance 0.042; CI [-0.250, 0.250] too wide to be sure — investigate

=== MDE: smallest detectable mean diff at n cases (sd_diff=0.426) ===
  n=  12: MDE ~ 0.345
  n=  50: MDE ~ 0.169
  n= 100: MDE ~ 0.119
  n= 300: MDE ~ 0.069

Read it as the lesson's thesis in five lines: the means are identical (0.833 → 0.833), the paired CI says "no detectable difference" ([-0.25, +0.25]), and the gate still fails — because the billing slice dropped below its floor while the edge slice improved. Aggregate metrics average failures away; slices and paired diffs don't. Also note the cache: 24 unique keys for 72 calls — 24 live calls (misses) and 48 replays (hits), and a prompt field inside params is what kept v2 from replaying v1's answers.

If you run this yourself on a fresh runs/ directory, only the wall times (thread scheduling) and the timestamps will differ. The cache counts are deterministic: 24 entries (12 cases × 2 prompt versions), 72 task invocations, 24 live calls (misses, one per unique key) and 48 hits. With workers=4 the three repeats of a case race on the per-key lock, so which repeat pays for the live call varies, but cached_call re-books a call that was coalesced behind the lock as a hit instead of a miss, so the totals do not.

The run.json manifest save_run wrote (abridged) is the experiment record:

text
Output: (abridged — your timestamps, SHA and fingerprint differ)

{
  "run": "triage-v1-baseline",
  "created_at": "2026-11-06T03:31:02Z",
  "git_sha": "<commit>",
  "python": "3.14.6",
  "n_results": 36,
  "system": {"prompt": "ticket-triage@1.0.0", "model": "fake-triage-1",
             "dataset": "support-triage", "dataset_fp": "…"},
  "config": {"workers": 4, "repeats": 3}
}

4.4 demo_regression.py — the fixture, in full#

Everything §4.3 ran is this one stdlib-only script — the 12-case dataset, the deterministic fake model behind cached_call, the two prompt variants and the gate/MDE calls. Save it at the project root beside the evalkit/ package and run python3 demo_regression.py (delete runs/ first if you've run it before — a warm cache replays answers and the hit/miss split changes, which is exactly the caveat in 3.2):

python
"""demo_regression.py — the fixture behind section 4.3's real output.

12 support-ticket triage cases, a deterministic fake "model" behind
cached_call, two prompt versions (ticket-triage@1.0.0 / @1.1.0), repeats=3.
Stdlib only — no keys, no network. Run from the project root:
    python3 demo_regression.py
"""
from __future__ import annotations

import statistics
import time
from dataclasses import dataclass, field

from evalkit.compare import (GateThresholds, evaluate_gate,
                             min_detectable_effect, paired_bootstrap_ci,
                             paired_diffs, paired_effect_size,
                             sign_flip_permutation_p, summarise_metric)
from evalkit.runner import (CallCache, RunConfig, cached_call,
                            dataset_fingerprint, run_suite, save_run,
                            slice_values, status_counts, scores_by_case)

MODEL = "fake-triage-1"
PROMPT_V1 = "ticket-triage@1.0.0"
PROMPT_V2 = "ticket-triage@1.1.0"
DATASET = "support-triage"


# ---------------------------------------------------------------------------
# The dataset: 12 cases. `type` is the slice dimension the gate floors use.
# ---------------------------------------------------------------------------

@dataclass
class TriageCase:
    example_id: str
    inputs: dict
    expected: dict
    tags: dict = field(default_factory=dict)


def _case(cid, kind, subject, body, category):
    return TriageCase(
        example_id=cid,
        inputs={"subject": subject, "body": body},
        expected={"category": category},
        tags={"type": kind, "tier": "full"},
    )


CASES = [
    # billing slice (4): t-009 flips 1 -> 0 under v2's warranty bug
    _case("t-001", "billing", "Duplicate charge on my card",
          "I was charged twice for order 8812 — please refund the duplicate.",
          "billing"),
    _case("t-002", "billing", "Invoice number wrong on receipt",
          "The invoice total doesn't match what I paid.", "billing"),
    _case("t-003", "billing", "Can't pay my invoice this month",
          "Payment keeps failing at checkout.", "billing"),
    _case("t-009", "billing", "Refund for defective headphones",
          "The headphones arrived broken — requesting a refund under warranty.",
          "billing"),
    # edge slice (2): t-012 flips 0 -> 1 (v1's portal bug fixed in v2);
    # t-010 is genuinely ambiguous — fails under both versions
    _case("t-010", "edge", "Quick question",
          "hey, my thing from last week still isn't right — what do I do?",
          "technical"),
    _case("t-012", "edge", "Order status page is down",
          "The status portal returns a 500 error for every parcel lookup.",
          "technical"),
    # the rest pass under both versions
    _case("t-004", "shipping", "Where is my package?",
          "Tracking shows it was delivered but nothing arrived.", "shipping"),
    _case("t-005", "account", "Update my email address on file",
          "I changed jobs and need my login email updated.", "account"),
    _case("t-006", "technical", "App crashes on launch after update",
          "I get a 500 error every time I open it.", "technical"),
    _case("t-007", "shipping", "Delivery never arrived",
          "My package was marked delivered two weeks ago.", "shipping"),
    _case("t-008", "other", "Promo code SAVE10 not applying at checkout",
          "The code was valid on the site but checkout rejects it.", "other"),
    _case("t-011", "account", "How do I reset my password?",
          "I can't log in and the reset link never arrives.", "account"),
]


# ---------------------------------------------------------------------------
# The fake model: a keyword classifier with one deliberate bug per version —
# v1 misroutes 'portal' tickets to 'other'; v2 fixed that but misroutes
# 'warranty' claims. Deterministic: same input, same output, every time.
# ---------------------------------------------------------------------------

CATEGORY_KEYWORDS = (
    ("billing", ("invoice", "charge", "refund", "payment", "receipt",
                 "billing")),
    ("account", ("account", "profile", "password", "email address",
                 "deactivate")),
    ("technical", ("error", "crash", "bug", "timeout", "500", "api",
                   "won't load", "not working")),
    ("shipping", ("delivery", "tracking", "package", "shipping",
                  "where is my order", "lost")),
)


def fake_call_model(inputs: dict, prompt_version: str) -> dict:
    text = f"{inputs['subject']} {inputs['body']}".lower()
    category = "other"
    for cat, keywords in CATEGORY_KEYWORDS:
        if any(k in text for k in keywords):
            category = cat
            break
    if prompt_version == PROMPT_V1 and "portal" in text:
        category = "other"                     # v1 bug: status-portal tickets
    if prompt_version == PROMPT_V2 and "warranty" in text:
        category = "other"                     # v2 bug: warranty claims
    return {"category": category}


def accuracy(case: TriageCase, output: dict) -> float:
    return 1.0 if output.get("category") == case.expected["category"] else 0.0


def _scores(results, metric="accuracy"):
    """case_id -> mean score across repeats, plus per-slice value lists."""
    by_case = scores_by_case(results, metric)
    slices = slice_values(results, metric, dim="type")
    return by_case, slices


def _summarise(by_case, slices):
    return summarise_metric(list(by_case.values()), slices=slices)


def main() -> None:
    cache = CallCache("runs/.call_cache.jsonl")
    cfg = RunConfig(workers=4, repeats=3)

    def task_for(prompt_version: str):
        def task(case: TriageCase) -> dict:
            return cached_call(
                cache, fn="triage", model=MODEL,
                params={"prompt": prompt_version},
                payload=case.inputs,
                call=lambda: fake_call_model(case.inputs, prompt_version))
        return task

    print("=== run_suite: 12 cases x 3 repeats = 36 rows per run ===")

    t0 = time.perf_counter()
    res_v1 = run_suite(CASES, task_for(PROMPT_V1), {"accuracy": accuracy},
                       cfg=cfg)
    ms_v1 = (time.perf_counter() - t0) * 1000
    t0 = time.perf_counter()
    res_v2 = run_suite(CASES, task_for(PROMPT_V2), {"accuracy": accuracy},
                       cfg=cfg)
    ms_v2 = (time.perf_counter() - t0) * 1000

    print(f"statuses v1: {status_counts(res_v1)} | "
          f"v2: {status_counts(res_v2)}")
    print(f"wall time: v1 {ms_v1:.0f}ms, v2 {ms_v2:.0f}ms")
    print(f"cache stats: {cache.stats()}")

    out = save_run(res_v1, "runs", name="triage-v1-baseline",
                   system={"dataset": DATASET,
                           "dataset_fp": dataset_fingerprint(CASES),
                           "prompt": PROMPT_V1, "model": MODEL},
                   extra={"config": {"workers": cfg.workers,
                                     "repeats": cfg.repeats}})
    print(f"saved run -> {out}")

    # ---- paired comparison: is v2 better than v1 on the SAME cases? -------
    s_v1, sl_v1 = _scores(res_v1)
    s_v2, sl_v2 = _scores(res_v2)
    summ_v1, summ_v2 = _summarise(s_v1, sl_v1), _summarise(s_v2, sl_v2)
    diffs = paired_diffs(s_v1, s_v2)
    d_mean, d_lo, d_hi = paired_bootstrap_ci(diffs)
    p = sign_flip_permutation_p(diffs)
    d = paired_effect_size(diffs)

    print("\n=== paired comparison v2 - v1 (accuracy) ===")
    print(f"v1 mean {summ_v1.mean:.3f} -> v2 mean {summ_v2.mean:.3f}")
    print("per-case diffs: [" + ", ".join(f"{x:+.0f}" for x in diffs) + "]")
    print(f"mean diff {d_mean:+.3f}  95% CI [{d_lo:+.3f}, {d_hi:+.3f}]  "
          f"p={p:.4f}  d={d:+.2f}")
    for name in sorted(set(sl_v1) | set(sl_v2)):
        a = statistics.fmean(sl_v1.get(name, [float("nan")]))
        b = statistics.fmean(sl_v2.get(name, [float("nan")]))
        if a != b:
            print(f"{name:<8}slice mean: {a:.3f} -> {b:.3f}")

    # ---- the gate ----------------------------------------------------------
    gate = evaluate_gate(
        summ_v2, diffs,
        GateThresholds(min_overall=0.75, max_drop=0.05,
                       slice_floors={"billing": 0.9}, min_cases=12),
        baseline_mean=summ_v1.mean)
    print("\n=== gate: v2 vs v1 (floor 0.75, drop<=5%, billing>=0.9) ===")
    print(f"passed: {gate.passed}")
    for f in gate.failures:
        print(f"  FAIL: {f}")
    for w in gate.warnings:
        print(f"  warn: {w}")

    # ---- minimum detectable effect ----------------------------------------
    sd_diff = statistics.stdev(diffs)
    print(f"\n=== MDE: smallest detectable mean diff at n cases "
          f"(sd_diff={sd_diff:.3f}) ===")
    for n in (12, 50, 100, 300):
        print(f"  n={n:>4}: MDE ~ {min_detectable_effect(n, sd_diff):.3f}")


if __name__ == "__main__":
    main()

Two things to notice in the fixture itself. The fake model is a keyword classifier with a planted bug per version — v1 misroutes status-portal tickets, v2 fixes that but misroutes warranty claims — which is why the aggregate means tie while the failing set moves. And params={"prompt": prompt_version} is what puts the version inside the cache key: without it, v2 would silently replay v1's cached answers and the comparison would measure nothing.


Part 5: pytest integration#

Evals belong in the same test suite as your code, with the same runner, reporters and CI plumbing. Three patterns, cheapest first:

5.1 Parametrised cases as tests#

Each eval case becomes a pytest test via @pytest.mark.parametrize; markers select the tier; a module-scoped fixture runs the suite once for the gate test.

python
# tests/conftest.py
import os
import pytest


def pytest_addoption(parser):
    parser.addoption("--eval-live", action="store_true",
                     help="call real providers (needs keys); default is the fake")
    parser.addoption("--eval-workers", type=int, default=4)


def pytest_configure(config):
    config.addinivalue_line("markers", "eval_smoke: ~20-case smoke suite")
    config.addinivalue_line("markers", "eval_pr: PR-tier suite (~100 cases)")
    config.addinivalue_line("markers", "eval_nightly: full suite with repeats")


@pytest.fixture(scope="session")
def call_model(request):
    """The system under test. Default: deterministic fake (no keys, CI-safe).
    --eval-live swaps in the real provider client; keys come from .env."""
    if request.config.getoption("--eval-live"):
        from provider_client import live_call_model   # your adapter (03.11 style)
        return live_call_model()
    from fake_model import fake_call_model
    return fake_call_model()

The default model is a deterministic stand-in, so the smoke tier needs no keys. It only has to exercise the plumbing (runner, scorers, gate); a real system is your prompt plus a provider call behind --eval-live:

python
# tests/fake_model.py — a keyword router: no network, no keys, same output every time
_RULES = (                       # first match wins, like a tiny decision list
    ("billing", ("invoice", "charge", "billed", "refund", "payment", "plan")),
    ("technical", ("error", "crash", "500", "403", "api")),
    ("shipping", ("ship", "tracking", "delivery", "package")),
    ("account", ("admin", "log in", "password", "account")),
)


def fake_call_model():
    def call(inputs: dict) -> str:          # 10A.2 stores the text under inputs["ticket"]
        text = str(inputs.get("ticket", "")).lower()
        for category, words in _RULES:
            if any(w in text for w in words):
                return category
        return "other"
    return call
python
# tests/test_eval_smoke.py
import pytest

from evalkit.runner import (RunConfig, load_run, run_suite, scores_by_case,
                            slice_values)
from evalkit.compare import (GateThresholds, evaluate_gate, paired_diffs,
                             summarise_metric)
from evalkit.dataset import load_dataset        # 10A.2 -> EvalDataset[EvalExample]
from evalkit.scorers import (Score, case_value,
                             run_graders)        # 10A.3 -> (case, output) -> Score

DATA = load_dataset("evals/support-triage")
SMOKE = [e for e in DATA.examples if e.tags.get("tier") == "smoke"]
assert SMOKE, "no case has tags['tier'] == 'smoke': tag ~20 cases first"
GATE = GateThresholds(min_overall=0.80, min_cases=len(SMOKE),
                      slice_floors={"billing-dispute": 0.90})


def category_match(case, output) -> Score:
    """One grader in 10A.3's (case, output) -> Score convention — the order
    run_graders invokes it in: the eval case first, the model's output
    second. For real suites pick graders from 10A.3's decision table —
    run_graders combines them, and a hard failure (passed=False) fails the
    example."""
    pred = str(output).strip().lower()
    exp = case_value(case, "expected", default={})
    want = exp.get("category", "") if isinstance(exp, dict) else exp
    want = str(want).strip().lower()
    return Score(name="category_match", value=1.0 if pred == want else 0.0,
                 passed=pred == want, detail={"pred": pred, "want": want})


GRADERS = {"category": category_match}


def triage_score(ex, output) -> float:
    """The runner's scorer contract is (case, output) -> float; 10A.3's
    run_graders returns a Verdict. A hard grader failure scores 0.0,
    otherwise the verdict's mean value — the whole adapter is three lines."""
    case = {"example_id": ex.example_id, "inputs": ex.inputs,
            "expected": ex.expected, "tags": ex.tags}
    v = run_graders(case, output, GRADERS)
    return 0.0 if not v.passed else v.value


@pytest.fixture(scope="module")
def suite(request, call_model):
    cfg = RunConfig(workers=request.config.getoption("--eval-workers"), repeats=1)
    # EvalExample has `inputs` (a dict), not `input`; the runner reads
    # `.example_id` for ids and `.tags` for slices — no case wrapper needed.
    return run_suite(SMOKE, lambda e: call_model(e.inputs),
                     {"triage": triage_score}, cfg=cfg)


@pytest.mark.eval_smoke
@pytest.mark.parametrize("case", SMOKE, ids=lambda e: e.example_id)
def test_case_passes(case, suite):
    row = next(r for r in suite if r.case_id == case.example_id)
    assert row.status == "ok", f"{case.example_id}: {row.error}"
    assert row.scores["triage"] >= 1.0


@pytest.mark.eval_smoke
def test_smoke_gate(suite):
    scores = scores_by_case(suite, "triage")
    summ = summarise_metric(list(scores.values()),
                            slices=slice_values(suite, "triage", dim="type"))
    # paired gate against the accepted baseline, when you have one:
    #   base = scores_by_case(load_run("runs/baseline/latest"), "triage")
    #   diffs = paired_diffs(base, scores)
    #   verdict = evaluate_gate(summ, diffs, GATE,
    #                            baseline_mean=sum(base.values()) / len(base))
    verdict = evaluate_gate(summ, None, GATE)
    assert verdict.passed, "; ".join(verdict.failures + verdict.warnings)

Notes that matter in production:

  • Tag the smoke cases. The 10A.2 fixture has no tier tag, so SMOKE above is empty until you add "tier": "smoke" to the tags of the cases you want in the fast tier (about 20 in a real suite; the tag-based tiering of 3.1). Until you do, the module-level assert SMOKE stops collection with a clear message instead of letting the gate test fail later on an empty list. Keep this key separate from the suite tag that 10A.1, 5.5 uses for capability vs regression: tier says how often a case runs, suite says whether a failure may block.
  • What you should see on the 10A.2 fixture. Save the 16 cases as evals/support-triage/cases.jsonl. Tag all 16 and the toy keyword router in fake_model.py fails 7 of them (the three refusal cases carry no category to match; "second admin on our Team plan" and the account-takeover ticket hit a billing keyword first; the downgrade question matches no keyword), so 9 tests pass, 8 fail and the gate reports mean 0.562 < floor 0.800. That red result is the gate working, not a bug in the plumbing. Tag only the nine cases the router handles (tkt-0002, 0005, 0007, 0008, 0009, 0010, 0013, 0014, 0015) and all ten tests pass (nine cases plus the gate). Either way, replace the stand-in with your real system behind --eval-live before the numbers mean anything.
  • load_dataset, run_graders/Score and EvalExample are the real APIs shipped by lessons 10A.2/10.3 — this example is written against them. The only adaptation is the triage_score shim (Verdict → float, hard fail → 0.0) and passing e.inputs to the task; the runner reads .example_id and .tags directly via _case_id/_case_slices. If your earlier evalkit files differ, the seam is the same: cases need .id/.example_id + .tags, scorers need (case, output) -> float.
  • Slice floors key on tag values. slice_values(..., dim="type") groups by tags["type"], so the floor {"billing-dispute": 0.90} means "cases whose type tag is billing-dispute" — matching how 10A.2 stores slice dimensions as separate tag keys.
  • Per-case tests give you pytest's best feature for free: -k t-009 reruns one case, --lf reruns last failures, and JUnit XML names every failing case.
  • The gate test is separate so pytest -m "not eval_smoke" still runs your unit tests, and pytest -m eval_smoke runs only the eval tier.

5.2 Reports, parallelism and selection#

bash
pytest -m eval_smoke -n auto --junitxml=reports/junit.xml     # xdist + JUnit
pytest -m eval_pr --json-report --json-report-file=reports/eval.json   # needs pytest-json-report
  • pytest-xdist -n auto parallelises across cases; it does not replace RunConfig.workers, which bounds provider concurrency. Use both: xdist for CPU-side scorers, workers for API calls. For LLM-bound suites, xdist mostly adds overhead — the runner's own pool is the right knob.
  • JUnit XML is what GitHub Actions reads to annotate PRs and what pytest --junitxml dashboards consume. The eval-specific report (per-slice table, CIs, gate verdict) is your own report.py output — an artifact, not a pytest plugin.
  • deepeval test run wraps exactly this pytest flow with its own plugin: assert_test(case, metrics) inside a parametrised test, --num-processes for xdist, --repeat for repeats, --use-cache for cached eval results, and --official to mark a run as the baseline on Confident AI (deepeval docs, verified November 2026). The concepts are identical to evalkit; the difference is who owns the dataset and metric definitions. The runner, its flags and exit codes are taught in 10B.2, Part 5, and a keyless GitHub Actions gate in 10B.7, Part 2; Inspect's equivalent, including a gate that cannot go green on a broken eval, is 10B.12, Part 13.

5.3 The pytest-plugin landscape (verified November 2026)#

Tool Licence pytest story What it adds over evalkit
promptfoo MIT (acquired by OpenAI — announced March 2026, open-source continues) Not pytest-native; YAML-driven promptfoo eval, GitHub Action posts PR comments 20+ providers, red-teaming, web viewer; declarative configs
DeepEval (Confident AI) Apache-2.0, v4.3.5 deepeval test run → pytest plugin, assert_test(), EvaluationDataset Hosted Confident AI platform, tracing, --official baselines
Inspect AI (UK AISI + Meridian Labs) MIT, inspect-ai 0.3.x inspect eval CLI, Task/Solver/Scorer model, own runner A large library of prebuilt evals (the companion Inspect Evals collection), sandboxing, model-graded scorers, Inspect View

The lesson's advice is the same one 10A.10 develops: your datasets and gates should be portable JSONL/YAML you own; a tool earns its place by saving you runner code, not by owning your evidence. evalkit's JSONL results + manifest are the portable core any of these can ingest.

5.4 The cheap local gate: pre-push checks#

CI is the enforcement; the fastest feedback is a hook that runs before the push. The smoke tier is the only eval cheap enough to run on every commit — that's what it's for. Two options:

  • A script target (make eval-smoke, just eval-smoke, or a plain alias) you run before pushing. Zero machinery; relies on habit.
  • pre-commit with a pre-push stage — the hook runs the smoke suite automatically:
yaml
# .pre-commit-config.yaml
repos:
  - repo: local
    hooks:
      - id: eval-smoke
        name: eval smoke suite (~20 cases, no keys)
        entry: uv run pytest -m eval_smoke -q
        language: system
        stages: [push]
        pass_filenames: false
        verbose: true

uv add --dev pre-commit, then pre-commit install --hook-type pre-push (run manually any time with pre-commit run --hook-stage pre-push). Three rules keep local gates honest: keep it under ~30 seconds — a slow hook gets bypassed with --no-verify, which is how gates die; never require keys — the smoke tier is fake/replay by design; and treat a hook failure like a CI failure: fix it or bypass it consciously, never normalize a red hook.


Part 6: GitHub Actions#

Two jobs on PRs (offline smoke with no keys; live PR-eval with secrets), one nightly extended run, one manual pre-release, and a model-upgrade gate job that blocks a model swap until the candidate clears the incumbent's baseline. The YAML is illustrative — not executed here — but every action version and pattern follows verified current practice as of November 2026 (03.10, Part 12 covers the secrets model it reuses).

6.1 evalkit/cli.py — the command line CI calls#

The workflow shells out to python -m evalkit.cli — a thin argparse wrapper over run_suite/save_run/load_run and the compare functions. It exists so CI (and humans) get stable subcommands instead of python -c one-liners; about 150 lines, stdlib only, no new concepts. evalkit works as a namespace package — no __init__.py needed on Python 3.11+.

python
# evalkit/cli.py
"""evalkit/cli.py — thin CLI over runner.py + compare.py. Stdlib only.

    # run a suite, store results.jsonl + run.json + a small report.md
    python -m evalkit.cli run --cases evals/pr.jsonl \
        --task app.evals:call_model --scorer app.evals:triage \
        --cost-of app.evals:call_cost --model openai/gpt-6-luna \
        --out runs/pr-123 --name pr-openai-luna --workers 4 --max-cost-usd 5

    # gate a run against thresholds and/or the accepted baseline
    python -m evalkit.cli gate --run runs/pr-123/pr-openai-luna \
        --baseline runs/baseline/latest --metric triage \
        --min-overall 0.80 --max-drop 0.05 --min-cases 50 \
        --slice-dim type --slice-floor billing-dispute=0.90

    # paired comparison report (text, or --markdown for PR comments)
    python -m evalkit.cli compare --run runs/nightly-1/full \
        --baseline runs/baseline/latest --metric triage --markdown

Case files are JSONL, one {"id", "input", "tags"} object per line — the
runner's CaseLike contract, deliberately NOT the 10A.2 dataset schema:
--task/--scorer/--cost-of take `module:function` imports, so your app's
adapter is where the dataset schema, provider client and graders meet (the
bridges shown in 5.1). A scorer's metric name is its function's __name__,
so `--scorer app.evals:triage` is the metric `--metric triage` reads back.
`--model` is recorded in the manifest and exported as EVALKIT_MODEL for the
task to read.
"""
from __future__ import annotations

import argparse
import importlib
import json
import os
import statistics
import sys
import time
from pathlib import Path
from types import SimpleNamespace

from .compare import (GateThresholds, evaluate_gate, min_detectable_effect,
                      paired_bootstrap_ci, paired_diffs,
                      paired_effect_size, sign_flip_permutation_p,
                      summarise_metric)
from .runner import (Budget, RunConfig, dataset_fingerprint, load_run,
                     run_suite, save_run, scores_by_case, slice_values,
                     status_counts)


def _import(spec: str):
    """'module:function' -> the callable. Keeps cli.py dependency-free."""
    mod_name, _, attr = spec.partition(":")
    if not attr:
        raise SystemExit(f"expected module:function, got {spec!r}")
    return getattr(importlib.import_module(mod_name), attr)


def _load_cases(path: str) -> list:
    cases = []
    for line in Path(path).read_text().splitlines():
        if line.strip():
            d = json.loads(line)
            cases.append(SimpleNamespace(id=d["id"], input=d.get("input"),
                                         tags=d.get("tags") or {}))
    return cases


def _mean(values) -> float:
    return sum(values) / len(values) if values else float("nan")


# --------------------------------------------------------------------- run

def cmd_run(args) -> int:
    cases = _load_cases(args.cases)
    task = _import(args.task)
    scorers = {f.__name__: f for f in (_import(s) for s in args.scorer)}
    cost_of = _import(args.cost_of) if args.cost_of else None
    if args.model:
        os.environ["EVALKIT_MODEL"] = args.model
    budget = Budget(max_calls=args.max_calls,
                    max_cost_usd=args.max_cost_usd, cost_of=cost_of)
    results = run_suite(cases, task, scorers,
                        cfg=RunConfig(workers=args.workers,
                                      repeats=args.repeats),
                        budget=budget)
    name = args.name or time.strftime("run-%Y%m%d-%H%M%S", time.gmtime())
    out = save_run(results, args.out, name=name,
                   system={
                       "dataset": str(args.cases),
                       "dataset_fp": dataset_fingerprint(cases),
                       "model": args.model or os.environ.get("EVALKIT_MODEL"),
                       "scorers": sorted(scorers),
                   },
                   extra={"config": {"workers": args.workers,
                                     "repeats": args.repeats},
                          "budget": budget.summary()})
    lines = [f"# eval run `{name}`", "",
             f"- cases: {len(cases)} x repeats {args.repeats} = {len(results)} rows",
             f"- statuses: {status_counts(results)}",
             f"- budget: {budget.summary()}"]
    for m in scorers:
        vals = list(scores_by_case(results, m).values())
        if vals:
            lines.append(f"- {m}: mean {_mean(vals):.3f} (n={len(vals)})")
    (out / "report.md").write_text("\n".join(lines) + "\n")
    print(f"saved {len(results)} rows -> {out}")
    print("statuses:", status_counts(results))
    for m in scorers:
        vals = list(scores_by_case(results, m).values())
        if vals:
            print(f"{m}: mean {_mean(vals):.3f} (n={len(vals)})")
    return 0


# -------------------------------------------------------------------- gate

def _slice_floors(specs: list) -> dict:
    floors = {}
    for spec in specs:
        name, _, val = spec.partition("=")
        if not name or not val:
            raise SystemExit(f"--slice-floor wants name=value, got {spec!r}")
        floors[name] = float(val)
    return floors


def cmd_gate(args) -> int:
    cur = load_run(args.run)
    cur_scores = scores_by_case(cur, args.metric)
    if not cur_scores:
        print(f"no '{args.metric}' scores in {args.run}", file=sys.stderr)
        return 2
    values = list(cur_scores.values())
    slices = (slice_values(cur, args.metric, dim=args.slice_dim)
              if args.slice_dim else None)
    current = summarise_metric(values, slices=slices)
    diffs = baseline_mean = None
    if args.baseline:
        base_scores = scores_by_case(load_run(args.baseline), args.metric)
        if base_scores:
            baseline_mean = _mean(list(base_scores.values()))
            diffs = paired_diffs(base_scores, cur_scores)
    verdict = evaluate_gate(
        current, diffs,
        GateThresholds(min_overall=args.min_overall,
                       max_drop=args.max_drop,
                       slice_floors=_slice_floors(args.slice_floor),
                       min_cases=args.min_cases),
        baseline_mean=baseline_mean)
    print(f"{args.metric}: mean {current.mean:.3f} over {current.n} cases"
          + (f" vs baseline {baseline_mean:.3f}"
             if baseline_mean is not None else ""))
    for f in verdict.failures:
        print("FAIL:", f)
    for w in verdict.warnings:
        print("warn:", w)
    print("GATE", "PASS" if verdict.passed else "FAIL")
    return 0 if verdict.passed else 1


# ----------------------------------------------------------------- compare

def cmd_compare(args) -> int:
    cur = load_run(args.run)
    cur_scores = scores_by_case(cur, args.metric)
    base_scores = scores_by_case(load_run(args.baseline), args.metric)
    diffs = paired_diffs(base_scores, cur_scores)
    if not diffs:
        print("no shared case ids between run and baseline", file=sys.stderr)
        return 2
    mean, lo, hi = paired_bootstrap_ci(diffs)
    p = sign_flip_permutation_p(diffs)
    d = paired_effect_size(diffs)
    sd = statistics.stdev(diffs) if len(diffs) > 1 else float("nan")
    mde = min_detectable_effect(len(diffs), sd)
    cmean = _mean(list(cur_scores.values()))
    bmean = _mean(list(base_scores.values()))
    if args.markdown:
        print("| metric | baseline | candidate | mean diff | 95% CI | p | d | MDE(n) |")
        print("|---|---|---|---|---|---|---|---|")
        print(f"| {args.metric} | {bmean:.3f} | {cmean:.3f} | {mean:+.3f} | "
              f"[{lo:+.3f}, {hi:+.3f}] | {p:.4f} | {d:+.2f} | {mde:.3f} |")
    else:
        print(f"{args.metric}: baseline {bmean:.3f} -> candidate {cmean:.3f}")
        print(f"paired diff {mean:+.3f}  95% CI [{lo:+.3f}, {hi:+.3f}]  "
              f"p={p:.4f}  d={d:+.2f}  MDE={mde:.3f}  (n={len(diffs)})")
    if args.slice_dim:
        cs = slice_values(cur, args.metric, dim=args.slice_dim)
        bs = slice_values(load_run(args.baseline), args.metric,
                          dim=args.slice_dim)
        print(f"\nper-slice means ({args.slice_dim}), candidate vs baseline:")
        for name in sorted(set(cs) | set(bs)):
            cv, bv = cs.get(name, []), bs.get(name, [])
            print(f"  {name:>20}: {_mean(cv):.3f} (n={len(cv)})  vs  "
                  f"{_mean(bv):.3f} (n={len(bv)})")
    return 0


def main(argv=None) -> int:
    ap = argparse.ArgumentParser(prog="python -m evalkit.cli")
    sub = ap.add_subparsers(dest="cmd", required=True)

    p = sub.add_parser("run", help="run a suite and store results + manifest")
    p.add_argument("--cases", required=True, help="JSONL case file")
    p.add_argument("--task", required=True,
                   help="module:function — task(case) -> output")
    p.add_argument("--scorer", action="append", default=[],
                   help="module:function — scorer(case, output) -> float; repeatable")
    p.add_argument("--cost-of",
                   help="module:function — output -> USD cost")
    p.add_argument("--model",
                   help="model id for the manifest + EVALKIT_MODEL env")
    p.add_argument("--out", required=True, help="parent dir for the run")
    p.add_argument("--name", help="run dir name under --out (default: timestamp)")
    p.add_argument("--workers", type=int, default=4)
    p.add_argument("--repeats", type=int, default=1)
    p.add_argument("--max-calls", type=int)
    p.add_argument("--max-cost-usd", type=float)
    p.set_defaults(fn=cmd_run)

    g = sub.add_parser("gate", help="evaluate a run against thresholds/baseline")
    g.add_argument("--run", required=True, help="run dir or results.jsonl")
    g.add_argument("--baseline", help="baseline run dir or results.jsonl")
    g.add_argument("--metric", default="score")
    g.add_argument("--min-overall", type=float)
    g.add_argument("--max-drop", type=float,
                   help="max tolerated drop vs baseline, as a fraction")
    g.add_argument("--min-cases", type=int, default=1)
    g.add_argument("--slice-dim", help="tag dimension for slice floors (e.g. type)")
    g.add_argument("--slice-floor", action="append", default=[],
                   help="slice_value=min_mean, e.g. billing-dispute=0.90")
    g.set_defaults(fn=cmd_gate)

    c = sub.add_parser("compare", help="paired comparison report vs baseline")
    c.add_argument("--run", required=True)
    c.add_argument("--baseline", required=True)
    c.add_argument("--metric", default="score")
    c.add_argument("--slice-dim")
    c.add_argument("--markdown", action="store_true")
    c.set_defaults(fn=cmd_compare)

    args = ap.parse_args(argv)
    return args.fn(args)


if __name__ == "__main__":
    sys.exit(main())

Two design choices worth noticing: --task/--scorer are module:function imports resolved with importlib, so the CLI stays generic — your app's adapter module owns the provider client, prompt rendering and grader choice (the same bridges as 5.1, just packaged for CI). And run writes a small report.md into the run directory next to results.jsonl/run.json — that's the file the PR-comment step posts.

6.2 The workflow#

yaml
# .github/workflows/evals.yml
name: evals
on:
  pull_request:
    types: [opened, synchronize, reopened, labeled]   # "labeled": the model-upgrade label starts the gate
    paths: ["prompts/**", "evals/**", "evalkit/**", "src/**", "pyproject.toml", "uv.lock"]
  schedule:
    - cron: "23 4 * * *"        # nightly 04:23 UTC, off the hour
  workflow_dispatch:
    inputs:
      suite: {description: "cases file stem under evals/", default: "nightly"}
      model: {description: "model override", default: ""}
      upgrade_candidate: {description: "replacement model to gate (model-upgrade job)", default: ""}

permissions:
  contents: read
  pull-requests: write           # only for the PR-comment step

concurrency:
  group: evals-${{ github.ref }}
  cancel-in-progress: true       # a new push supersedes the old eval — saves money

jobs:
  smoke:                          # every PR: no keys, deterministic
    runs-on: ubuntu-latest
    timeout-minutes: 10
    steps:
      - uses: actions/checkout@v7
      - uses: astral-sh/setup-uv@v10.3.3
        with: {python-version: "3.13", enable-cache: true}
      - run: uv sync --frozen
      - run: uv run pytest -m eval_smoke -n auto --junitxml=smoke.xml
        env:
          OPENAI_API_KEY: ""      # explicitly empty: live paths must stay off
          ANTHROPIC_API_KEY: ""
          GEMINI_API_KEY: ""
          OPENROUTER_API_KEY: ""
      - uses: actions/upload-artifact@v7
        with: {name: smoke-results, path: smoke.xml}

  pr-eval:                        # PRs touching AI surfaces: live, gated
    runs-on: ubuntu-latest
    timeout-minutes: 30
    needs: smoke
    environment: eval-ci          # environment-scoped secrets + optional approval
    strategy:
      fail-fast: false
      matrix:
        include:
          - {model: "openai/gpt-6-luna", id: openai-luna}
          - {model: "anthropic/claude-haiku-5.5", id: claude-haiku}
    steps:
      - uses: actions/checkout@v7
      - uses: astral-sh/setup-uv@v10.3.3
        with: {python-version: "3.13", enable-cache: true}
      - run: uv sync --frozen
      - name: map model to provider key
        run: |
          case "${{ matrix.model }}" in
            openai/*)      echo "PROVIDER_KEY=${{ secrets.CI_OPENAI_API_KEY }}" >> "$GITHUB_ENV" ;;
            anthropic/*)   echo "PROVIDER_KEY=${{ secrets.CI_ANTHROPIC_API_KEY }}" >> "$GITHUB_ENV" ;;
            google/*)      echo "PROVIDER_KEY=${{ secrets.CI_GEMINI_API_KEY }}" >> "$GITHUB_ENV" ;;
            *)             echo "PROVIDER_KEY=${{ secrets.CI_OPENROUTER_API_KEY }}" >> "$GITHUB_ENV" ;;
          esac
      - run: uv run python -m evalkit.cli run \
             --cases evals/pr.jsonl \
             --task app.evals:call_model --scorer app.evals:triage \
             --cost-of app.evals:call_cost \
             --model "${{ matrix.model }}" \
             --out "runs/pr-${{ github.sha }}" --name "${{ matrix.id }}" \
             --workers 4 --max-cost-usd 5
        env:
          EVALKIT_API_KEY: ${{ env.PROVIDER_KEY }}
          EVALKIT_LIVE: "1"
      - name: gate
        run: uv run python -m evalkit.cli gate \
             --run "runs/pr-${{ github.sha }}/${{ matrix.id }}" \
             --baseline runs/baseline/latest \
             --metric triage --min-overall 0.80 --max-drop 0.05 \
             --slice-dim type --slice-floor billing-dispute=0.90 --min-cases 50
      - uses: actions/upload-artifact@v7
        with: {name: "eval-${{ matrix.id }}",
               path: "runs/pr-${{ github.sha }}/${{ matrix.id }}"}
      - name: comment results
        if: github.event_name == 'pull_request'
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          gh pr comment "${{ github.event.pull_request.number }}" \
            --body-file "runs/pr-${{ github.sha }}/${{ matrix.id }}/report.md"

  nightly:                        # schedule + manual: the deep run
    runs-on: ubuntu-latest
    timeout-minutes: 120
    needs: pr-eval
    if: github.event_name != 'pull_request'
    steps:
      - uses: actions/checkout@v7
      - uses: astral-sh/setup-uv@v10.3.3
        with: {python-version: "3.13", enable-cache: true}
      - run: uv sync --frozen
      - run: uv run python -m evalkit.cli run \
             --cases "evals/${{ inputs.suite || 'nightly' }}.jsonl" \
             --task app.evals:call_model --scorer app.evals:triage \
             --cost-of app.evals:call_cost \
             --model "${{ inputs.model || 'openai/gpt-6-luna' }}" \
             --out "runs/nightly-${{ github.run_id }}" --name full \
             --workers 8 --repeats 3 --max-cost-usd 25
        env:
          EVALKIT_API_KEY: ${{ secrets.CI_OPENROUTER_API_KEY }}
          EVALKIT_LIVE: "1"
      - run: uv run python -m evalkit.cli compare \
             --run "runs/nightly-${{ github.run_id }}/full" \
             --baseline runs/baseline/latest --metric triage --markdown \
             --slice-dim type > nightly-report.md
      - uses: actions/upload-artifact@v7
        with: {name: nightly-eval, path: "runs/nightly-${{ github.run_id }}"}

  model-upgrade:                  # a model swap: gate the candidate against the incumbent
    runs-on: ubuntu-latest
    timeout-minutes: 120
    needs: smoke
    environment: eval-ci
    if: inputs.upgrade_candidate != '' || contains(github.event.pull_request.labels.*.name, 'model-upgrade')
    env:
      CANDIDATE: ${{ inputs.upgrade_candidate || vars.UPGRADE_CANDIDATE }}   # a repository variable while the upgrade is in flight
    steps:
      - uses: actions/checkout@v7
      - uses: astral-sh/setup-uv@v10.3.3
        with: {python-version: "3.13", enable-cache: true}
      - run: uv sync --frozen
      - name: shadow-run the candidate on the full suite
        run: uv run python -m evalkit.cli run \
             --cases evals/nightly.jsonl \
             --task app.evals:call_model --scorer app.evals:triage \
             --cost-of app.evals:call_cost \
             --model "$CANDIDATE" \
             --out "runs/upgrade-${{ github.sha }}" --name candidate \
             --workers 8 --repeats 3 --max-cost-usd 25
        env:
          EVALKIT_API_KEY: ${{ secrets.CI_OPENROUTER_API_KEY }}
          EVALKIT_LIVE: "1"
      - name: model-upgrade gate          # the explicit gate step: exit 1 fails the job
        run: uv run python -m evalkit.cli gate \
             --run "runs/upgrade-${{ github.sha }}/candidate" \
             --baseline runs/baseline/latest \
             --metric triage --min-overall 0.80 --max-drop 0.02 \
             --slice-dim type --slice-floor billing-dispute=0.90 \
             --slice-floor multilingual=0.85 --min-cases 150
      - name: paired report (runs even when the gate fails)
        if: always()
        run: |
          uv run python -m evalkit.cli compare \
            --run "runs/upgrade-${{ github.sha }}/candidate" \
            --baseline runs/baseline/latest --metric triage --markdown \
            --slice-dim type >> "$GITHUB_STEP_SUMMARY"
      - uses: actions/upload-artifact@v7
        if: always()
        with: {name: model-upgrade-eval, path: "runs/upgrade-${{ github.sha }}"}

Design notes:

  • The model-upgrade gate is a named step, and a red step is the verdict. evalkit.cli gate exits 1 when any threshold fails, so the step (and the job) fails with no extra scripting. This is step 2 and step 3 of the 8.1 model-upgrade playbook wired into CI: shadow-run the candidate on the full suite, then diff against the incumbent's accepted baseline, per slice as well as overall. Mark the model-upgrade job as a required status check in branch protection and the swap cannot merge on a red gate.

  • It is stricter than the PR gate. --max-drop 0.02 (against 0.05 in pr-eval), two slice floors, a larger --min-cases, and --repeats 3 to match a baseline recorded with three repeats (a fresh live run, not a warm call cache: see the CallCache note below). A swap changes everything at once, so it earns the tighter rule. The slice names billing-dispute and multilingual are illustrative: use your own pre-registered slices (10.1).

  • Cost and latency are gate criteria too (8.1 step 5). The CLI above gates quality only. Read cost_usd and the latency summary from the candidate's run.json and the baseline's, and fail a further step if the cost or p95 delta passes your budget (1.3).

  • The labeled trigger has a cost. Adding labeled to the PR types lets the model-upgrade label start the gate, but it also re-runs smoke and pr-eval when any label is added. concurrency.cancel-in-progress keeps that cheap; if it still bothers you, start the gate with workflow_dispatch and the upgrade_candidate input instead.

  • paths: filter means doc-only PRs don't pay for evals; concurrency.cancel-in-progress means a force-push doesn't run three evals.

  • Matrix over models runs the same suite against each candidate model — that is the model-comparison harness; results land as separate artifacts, and the PR comment aggregates them.

  • Secrets via environment: — the eval-ci environment is where spend-limited CI keys live and where you can require a human approval for the nightly job. Same model as 03.10, 12.3.

  • Budget flags map to evalkit.runner.Budget — --max-cost-usd only works alongside --cost-of module:fn, because the runner can't know your pricing; the app's adapter supplies the per-call cost. The run stops at the cap and marks the rest not_run, which the gate treats as underpowered, not failed. app.evals in the YAML is your adapter module — provider client, prompt rendering, graders, cost function — the same bridges as 5.1.

  • Dependency caching — enable-cache: true on setup-uv uploads the uv cache to GitHub's cache (the default auto already covers most events on hosted runners; explicit true documents intent and covers the exceptions). The cache key follows pyproject.toml/uv.lock via cache-dependency-glob.

  • CallCache in CI: don't cache it for gate runs. A restored call cache makes repeat runs replay stale answers and can hide a provider-side model change — exactly what 3.2 warns about. If you want it for ad-hoc workflow_dispatch debugging runs, actions/cache on your cache path plus a short max_age_s is fine; the decision run itself stays live.

  • The PR comment uses the gh CLI (gh pr comment --body-file) rather than actions/github-script — no action version to pin, and the report file is already on disk. Each matrix leg posts its own model's report.md.

  • Fork PRs and secrets. A pull_request workflow from a fork does not receive your repository secrets (GitHub's secrets documentation says secrets other than GITHUB_TOKEN are not passed to the runner for a workflow triggered from a fork), so the live pr-eval job fails or skips for outside contributors, while the keyless smoke job still runs: that is a good reason to keep a strong smoke tier. The tempting fix, switching to pull_request_target, is the dangerous one: it runs with secrets, and GitHub's secure-use guide says such workflows "must not explicitly check out untrusted code, including from pull request forks". Prompt files and eval configs are code that a malicious PR can change to exfiltrate a key. Safe patterns: a maintainer re-runs the live eval after review (workflow_dispatch on the merged-candidate branch, or a label-triggered job guarded by environment: approval), or a separate privileged workflow_run job that only reads artifacts and never executes PR code.

  • Baseline as an artifact, not a branch. runs/baseline/latest is a pointer (a promoted run directory or a downloaded artifact) updated only when a change is accepted — see 1.2.

For teams not on GitHub Actions: GitLab CI, CircleCI and Buildkite all express the same three jobs; the portable parts are the pytest markers, the evalkit CLI, the secrets boundary and the artifact format.


Part 7: Experiment tracking#

Deep-dive

7.1 What to log per run#

An eval number without provenance is a rumour. Every run — smoke, PR, nightly, ad-hoc — records the same manifest fields:

Field Why it exists
run name + created_at + git_sha When, and which code produced it
dataset name, version, dataset_fingerprint Which cases; catches silent set edits — IDs and content
system.prompt name+version+hash, system.model ID+snapshot, params The exact thing under test (04.10 owns prompt versioning)
system.judge name+version+model A judge change re-baselines every score (10A.5)
system.retrieval/tools versions where applicable Index, chunker, reranker, MCP server versions
scores per metric + CIs + per-slice breakdown The result itself
results.jsonl per-case rows (status, scores, truncated output, latency) The evidence; enables paired diffs later
cost_usd, latency summary, cache hit/miss stats The bill and the speed
config (workers, repeats, thresholds) + baseline pointer How to reproduce the verdict

save_run in Part 4 writes exactly this as run.json + results.jsonl. That pair is your tracking record; everything below is about where to keep it and how to compare records.

7.2 Where results live: files first, platforms second#

The honest ladder, cheapest first:

  1. runs/ directory + JSONL (what this lesson builds). Git-ignored or artifact-stored, diffable, zero cost, zero lock-in. Add a runs/index.jsonl append-only catalogue if you want "list all runs" without a tool.
  2. DVC or plain Git LFS for the result files when they grow (per-case outputs get large). DVC (Apache-2.0) versions data alongside code without bloating the repo — overkill for JSONL manifests, right-sized for output corpora.
  3. An eval platform when you need the UI: run comparison views, leaderboards, annotation queues, tracing correlation. See the table below.

The non-negotiable either way: your canonical record is the open format (JSONL + manifest). Platforms are views over it; if you ever leave one, you take your data with you. This is the same "own your datasets" rule as 10A.10.

7.3 The tool landscape (verified November 2026)#

Tool Licence / hosting What it gives you for this lesson's needs
MLflow Apache-2.0, self-host or managed mlflow.evaluate() + tracking server: params/metrics/artifacts per run, run comparison UI, model registry linkage. General MLOps platform; GenAI evals are a feature, not the whole product
Weights & Biases Weave Open-source SDK (weave); self-managed platform needs commercial licence; W&B Cloud hosted Tracing + Evaluation API: dataset rows, scorers, experiment tables comparing runs side by side — closest fit to "compare prompt variants"
Langfuse MIT core (all product features), self-host free; enterprise modules commercial Traces + datasets + experiments + LLM-as-judge evaluators + prompt versioning; strong open-source story, ClickHouse-backed
LangSmith Closed, commercial (LangChain) The most turnkey: datasets, experiments, annotation queues, online evals, tight LangChain integration; you pay for the polish and the lock-in
Braintrust Closed platform; SDKs open (npm MIT, Py braintrust/autoevals Apache-2.0) Eval() datasets+scorers+experiments, tracing, PR-comment CI integration, human review; strong for prompt-iteration loops
Arize Phoenix Elastic License 2.0 (ELv2) — free self-host, no feature gates, but not OSI-open OpenInference tracing + evals on traces/datasets, strong notebook UX; ELv2 restricts offering it as a hosted service
Comet Opik Apache-2.0, full platform self-host Traces, datasets, experiments, LLM judges, prompt management, online eval rules
DVC Apache-2.0 Data/code versioning only — no eval UI; pairs with any of the above or with plain files
JSONL + notebook/pandas — Zero deps, fully yours; what evalkit emits natively. The right answer until run volume or collaboration demands a UI

Decision rule: start with JSONL+evalkit (this lesson). Adopt a platform when you need run-comparison UI at scale, annotation workflows, or trace-correlation — and pick by licence comfort (MIT/Apache vs ELv2 vs closed) and by whether your team already lives in LangChain/LangGraph (LangSmith) or wants fully self-hosted (Langfuse, Opik, Phoenix, MLflow).

7.4 Run comparison, leaderboards, reproducibility, retention#

  • Run comparison is the core operation: overlay two manifests, diff per-case scores (paired), render the slice table. evalkit's compare.py does the statistics; a platform does the pictures. Whatever you use, compare paired on shared case IDs — never compare aggregate-vs-aggregate across different case sets.
  • Leaderboards for your own variants are just "all runs of suite X, sorted by metric Y with CI". Keep them per-suite; a leaderboard mixing suites is meaningless.
  • Reproducibility means a run can be re-executed: manifest gives you dataset version + git SHA + prompt/model/judge versions + config; uv.lock pins deps; the call cache (with TTL off for replay) gives you the recorded responses. A run you can't re-run is an anecdote.
  • Retention: keep every accepted baseline forever; keep rejected runs for ~90 days (they're debugging evidence); expire raw per-case outputs on a schedule but keep manifests+scores indefinitely — they're small and they're the audit trail. Eval datasets containing user-derived text inherit the privacy rules of 02.9, Part 9 and Module 12.

Part 8: Change playbooks#

Deep-dive

8.1 The model-upgrade playbook#

Providers retire models on published schedules (02.9, Part 8: OpenAI ≥6 months' notice for GA models, Anthropic ≥60 days, Gemini ≥2 weeks for preview). Treat each deprecation notice as a scheduled engineering task, not an emergency:

  1. T-notice: freeze the incumbent. Pin the current snapshot explicitly (never a -latest alias) and record the full eval baseline on it — per-case scores, not just the mean.
  2. Shadow eval the replacement on the full suite before any traffic moves: same dataset, same scorers, repeats matched. This is the 05.9 blue/green shadow-eval pattern applied to models — run the candidate, compare, decide, then cut over. In CI this is the model-upgrade job in 6.2: its model-upgrade gate step runs the comparison and fails the job on a regression.
  3. Diff per slice, not just overall. New models regress unevenly: a model that's +2% overall can be −15% on your multilingual slice. The slice table decides, not the headline.
  4. Port prompts deliberately. Prompt behaviour doesn't transfer 1:1 (04.9, Part 4); re-run the dev loop on the new model and keep prompt+model as one versioned unit.
  5. Measure cost and latency deltas — a "better" model that doubles p95 latency or triples cost may still lose; they're gate criteria (1.3).
  6. Roll out with canary + rollback. Small traffic share first, watch the same metrics online (10A.9 owns online eval; Module 11C owns the rollout machinery), keep the old snapshot warm until the canary proves out, and document the decision in the run manifest.

8.2 The prompt-change playbook#

Prompt changes are the most frequent trigger and the most dangerous because they're easy to ship casually. The pipeline is 04.9's dev loop promoted to CI:

  1. Dev-set iteration happens offline with evalkit — never iterate against production traffic.
  2. On PR: prompt diff + rendered-output snapshot diff + smoke eval (no keys) + PR eval (live) — 04.10, Part 7 owns the prompt-library side; this lesson's gate decides pass/fail.
  3. Changelog entry: version → hash → score before/after → what changed and why (the 04.9 changelog format).
  4. Ship via alias (staging → production) so rollback is a pointer move, not a deploy (04.10, 4.4).

8.3 The retrieval/index-change playbook#

Chunking, embedding-model or index changes alter what the model sees, so they need the two-level check:

  1. Retrieval metrics first — recall@k, MRR, context precision are deterministic and cheap (06.10); a retrieval regression should be caught before any generation eval runs.
  2. Blue/green index rebuild + shadow eval (05.9, Part 5): build the new index alongside, replay the eval query set against both, compare recall and top-k diffs on real logged queries, flip the alias only on evidence, keep blue as rollback.
  3. Corpus content changes (new docs, deletions) go through ingestion data-quality checks (05.10) plus a spot RAG eval — you don't need the full suite for a content update, but you do need the cases that touch the changed topics.

8.4 The dependency-upgrade playbook#

SDK bumps, judge-model changes and scorer-library upgrades are the quiet regressors:

  • SDK/provider bumps: the cassette/snapshot diffs from 03.10 show request-level changes; run the offline suite plus a fresh live smoke (a warm cache would hide the SDK's changed wire format — the key covers the payload, and if the SDK serialises differently the request genuinely changed).
  • Judge upgrades: a new judge re-baselines every historical score. Version the judge in every manifest, keep a fixed "judge canary set" with known verdicts, and re-measure judge↔human agreement before trusting new numbers (10A.5).
  • Scorer/library bumps: pin versions in uv.lock; a metric-definition change (e.g. a library's F1 variant) is a silent re-baseline — check changelogs for metric semantics, not just API breaks.

Part 9: Test hygiene#

Deep-dive

The suite is a production artefact with its own failure modes:

  • Keep eval cases out of prompts. Few-shot examples and eval items must never overlap — a case that appears in the prompt isn't measuring generalisation, it's measuring recall. 10A.2 owns the split discipline; in CI, assert dataset_fingerprint of the held-out set differs from anything rendered into prompts.
  • Held-out test set. Iterate on dev cases; gate on a held-out set the prompt-tuning loop never sees (04.9, 1.6). A gate on the dev set measures memorisation.
  • Rotating canary cases. A fixed public suite gets "taught to": prompts accumulate rules that name test cases. Keep a small set of secret canaries — cases not in the repo, run only in CI with keys — rotated quarterly. They cost almost nothing and they're the only honest detector of overfitting-to-the-test.
  • Teaching-to-the-test detection. If the suite score rises while production metrics fall, the suite is being gamed — either by prompt rules naming cases or by dataset leakage. The fix is always more held-out data, never a higher threshold.
  • Dataset versioning in CI. Every manifest carries dataset_fingerprint; a PR that edits evals/*.jsonl shows a fingerprint diff in the PR comment — the hash catches added, removed, reordered and content-edited cases (a corrected label under an unchanged ID included). Pair it with the dataset's own version/changelog for the human-readable "what changed".
  • Flaky-test triage. infra_error/scorer_error/not_run statuses are quarantined, not averaged in. A case flaky >5% of runs gets investigated: is it model variance (expected — measure with repeats), judge variance (fix the judge), or infra (fix the client)? Quarantine with an expiry and an owner, same as the allow-list rule in 1.3.

Reference

10.1 Decision table: configuring the gate#

Decision Choose this when Avoid this when
Blocking vs advisory Hard floors, proven regressions (paired CI clears the tolerance), must-pass contract/safety cases The evidence is a point estimate inside noise — make it advisory, investigate, don't block
Threshold type Absolute floor for "good enough, period"; slice floors for segments that must never regress; max_drop for drift vs baseline; budgets for cost/latency Mean-only gating — it averages slice failures away (the 4.3 demo)
Slice floors 3–5 pre-registered slices that matter to the business Dozens of exploratory slices — multiple-comparison noise (2.6)
repeats repeats=1 live for gates; repeats=3–5 on a fresh cache for variance characterisation repeats>1 against a warm cache — every repeat replays the same answer
Cache mode Live calls or an hours-TTL cache for gate runs; warm cache for iteration and offline dev A fully cached gate run — it can't see provider-side changes
Baseline Last accepted run, stored per-case + manifest "Whatever ran last", or a bare aggregate number
Sampling Stratified seeded sample sized by the MDE table, for iteration tiers Sampling the pre-release decision run, or an under-powered sample presented as full-set evidence
Allow-list Named failing case + reason + owner + review date, reported separately Silent skips and expiry-less xfails — known issues become invisible issues
Infra errors Classify, retry or exclude; not_run counts as underpowered Scoring provider outages as quality zeros
Failure What you see Root cause Fix
Warm-cache vacuous comparison v2 "matches" v1 exactly; gate green; production regressed anyway Cache key omits prompt/model version, or the gate run replayed a warm cache Key on (fn, model, params, payload); live-call or TTL-hours cache for the decision run (3.2)
Infra outage counted as quality failure Red gate during a provider 5xx/429 storm; "quality dropped to zero" Exceptions scored 0 or bucketed as task errors Infra classifier + retry/exclude; only real verdicts reach the gate (3.4)
Gate flapping on noise Fails Monday, passes Tuesday, no code changed Point-estimate threshold on a noisy metric with small n CI-based non-regression rule, min_cases, advisory band for straddling CIs (2.5)
Baseline drift Scores slowly "improve" or comparisons stop meaning anything Baseline = last run (possibly a slipped regression); dataset or judge changed silently Promote baselines deliberately; dataset_fingerprint + judge version in every manifest (1.2)
Teaching-to-the-test Suite score rises while production metrics fall Prompt rules name eval cases; the dev set became the gate Held-out set, secret rotated canaries, disjointness check (Part 9)
Allow-list rot "3 known failures" becomes 30 permanent reds nobody reads Exclusions without expiry, owner or separate reporting Expiry + review date + always-visible count (1.3)
Budget cap mid-run Run stops at case 40/100; gate sees an underpowered run max_calls/max_cost_usd sized below suite×repeats, or a retry storm Size caps to the suite; treat not_run as underpowered and investigate spend (3.5)
Judge re-baseline Every historical score shifts after a judge upgrade Judge version not pinned; new judge never recalibrated Pin judge in the manifest; judge canary set; re-measure agreement (8.4, 10A.5)
Overconfident interval on grouped cases A "significant" win on 300 cases that vanishes on the next dataset version Cases from the same document, conversation or customer are correlated, so the per-case bootstrap undercounts uncertainty Resample whole groups (2.7); size by groups
Fork PR breaks or leaks the eval job Live job fails for outside contributors, or a pull_request_target fix lets a PR read a key Secrets are withheld from fork PRs; the workaround runs untrusted prompt/eval files with secrets Keep smoke keyless; run live evals after review via workflow_dispatch or environment approval (6.2)
Under-powered "no difference" "v2 is fine — no significant difference" on 30 cases MDE larger than the effect being ruled out Report MDE next to every null result; grow n or accept "can't tell" (2.4)

What this means for you#

A regression gate is a statistical instrument, not a switch: it needs triggers, an accepted baseline, thresholds and a noise model before it can block anything honestly. Paired per-case comparisons with bootstrap CIs answer "is B better than A?" far better than any aggregate delta, and knowing your minimum detectable effect stops "no significant difference" from being misread as "no difference". Cache model calls to iterate cheaply — but never let the gate run fully cached, because a replayed answer can't see a provider-side change. And own the records: JSONL results plus a manifest per run is the whole experiment-tracking stack; platforms are views over it, not the other way round.


Common misconceptions#

Misconception Reality
"Run the eval once; if it passes, ship it." One run on a noisy metric is a sample, not a verdict. Gate on CIs, use paired diffs, set min_cases.
"The eval score went up 2%, so v2 is better." Without a paired test and effect size, a 2% move on 50 cases is noise. Report CI + d, not the delta.
"Cache the model calls to make CI fast and free." A warm cache replays old answers — it hides provider-side changes and makes repeats measure zero variance. Cache for iteration; live-call the gate.
"A red gate means the code is bad." Distinguish infra_error (provider/quota — retry, don't score) from task_error (your bug — fail loudly) from quality failures (the actual signal).
"More eval cases always = better gate." Past ~300 cases you hit diminishing returns per dollar; past your MDE needs, buy slices and repeats instead of raw n.
"The baseline is last week's score." Baseline = last accepted run, stored as per-case results + manifest. Comparing aggregates across different datasets is meaningless.
"If the suite is green, the product is good." The suite measures what it measures. Production drift, novel inputs and judge blind spots live outside it — that's 10A.9's whole subject.
"Flaky tests should be retried until green." Pre-registered single-confirm rules are honest; retry-until-pass is p-hacking. Fix flakes at the source: infra classification, judge determinism, or quarantine.
"We need a platform before we need evals." JSONL + manifest + pytest + a gate covers most teams for a long time. Platforms buy UI and workflow, not correctness.

Key takeaways#

  • A regression gate = triggers + baseline + thresholds + statistics. Decide what change forces an eval, what the last accepted run was, which floors/budgets block, and how noise is handled — in that order.
  • Paired comparisons beat aggregate deltas. Per-case diffs + bootstrap CI + permutation p + effect size answer "is B better than A?" honestly; means alone average failures away.
  • Know your MDE before you run. A 12-case suite can't see a 5% change; write the detectable effect next to every "no significant difference".
  • Grouped cases need grouped statistics. When cases share a document, conversation or customer, resample whole groups; the per-case bootstrap is too narrow.
  • Tier the suite. Smoke on every commit, live PR eval on AI-surface changes, nightly extended, pre-release exhaustive — each tier sized to its decision.
  • Cache at the call seam, keyed by everything that changes the answer — and never let the gate run fully cached. TTL it, lock per key, never cache exceptions.
  • Infra failures are not quality failures. Classify, retry or exclude; only real verdicts reach the gate.
  • Every run is a manifest + JSONL. Dataset fingerprint, git SHA, prompt/model/judge versions, config, cost — reproducibility is a file format, not a vibe.
  • Platforms are views over your open-format records. Own the JSONL; adopt Langfuse/Weave/Braintrust/Phoenix/MLflow/Opik when you need the UI, not before.
  • Playbooks beat heroics. Model deprecations, prompt changes, index rebuilds and dep bumps each have a rehearsed sequence ending in canary + rollback.
  • The suite is a product artefact. Version the dataset, hide canaries, quarantine flakes with expiry, and never let the gate become the thing everyone ignores.

Terms introduced in this lesson#

Term One-line definition
Regression gate The rule that blocks shipping when eval scores regress vs an accepted baseline
Baseline The last accepted run's stored per-case results + manifest, not a single number
Absolute floor / relative non-regression / slice floor / operational budget The four threshold types: minimum acceptable score, max tolerated drop vs baseline, per-segment minimums, cost/latency caps
Allow-list (known failures) Named excluded cases with reason + expiry, reported separately so they can't hide
Paired comparison Comparing systems on per-case score differences so case difficulty cancels
Bootstrap CI Resample observations with replacement to estimate a mean's uncertainty interval
Sign-flip permutation test Label-free significance test for paired differences via random sign flips
Effect size (paired Cohen's d) mean(diff)/sd(diff): how big the difference is, independent of sample size
Minimum detectable effect (MDE) Smallest true effect a study of n cases can reliably detect
Flaky gate A gate that fails non-deterministically, usually from noise treated as signal
Tiered suite Smoke / PR / nightly / pre-release eval tiers of increasing cost and depth
Call cache / record-replay JSONL store of model-call responses keyed by (fn, model, params, payload)
Cache TTL (max_age_s) Record expiry so stale replays can't hide provider-side changes
Infra error vs task error Provider/environment failure (excluded) vs bug in the system under test (fails loudly)
Budget cap max_calls/max_cost_usd limit that stops a run before the invoice does
Result store / manifest results.jsonl per-case rows + run.json provenance record per run
Dataset fingerprint Stable hash of case IDs + content + order, catching silent eval-set edits including label corrections
Canary case Two senses: a high-value case run on every change, and a secret held-out case rotated to catch teaching-to-the-test (a third sense — canary rollouts of live traffic — is Module 11C's)
Stratified sample A subset drawn proportionally within each slice so small important segments aren't missed; seeded for reproducibility
Cluster bootstrap A bootstrap that resamples whole groups of correlated cases (documents, conversations) instead of single cases, giving honest intervals
Capability vs regression eval Capability evals report progress on unsolved cases; regression evals gate on cases that already pass
Pre-push hook A git hook (e.g. pre-commit's pre-push stage) running the smoke eval tier locally before CI
Shadow evaluation Running a candidate (model/index) on the full suite without serving it
Model-upgrade gate The named CI step that runs a candidate model against the incumbent's accepted baseline and fails the job on a regression (overall, per slice or over budget)
Experiment tracking Logging every run's dataset/prompt/model/judge versions, scores, cost, latency

Exercises#

  1. Gate calibration: using the demo fixture, change GateThresholds(min_overall=..., max_drop=..., slice_floors=...) until the v2 run passes and explain why that's the wrong fix (hint: the billing slice really did regress).
  2. MDE planning: compute min_detectable_effect for n ∈ {20, 50, 100, 300} with sd_diff measured from two real runs of your own suite; decide the smallest n your next A/B can use.
  3. Cache trap: run the demo twice — once with "prompt": prompt_version in params, once with params left out of cached_call — and confirm the second produces identical v1/v2 scores. Write down which key fields must be in your real cache key.
  4. Infra classification: make the fake task raise TimeoutError for one case and a ValueError for another; verify statuses infra_error vs task_error and that the gate ignores the former.
  5. pytest wiring: adapt tests/test_eval_smoke.py to your evalkit dataset; run pytest -m eval_smoke -n auto --junitxml=out.xml and inspect the XML.
  6. Playbook rehearsal: pick your production model's deprecation date from the provider's lifecycle page; write the T-minus checklist from 8.1 with your suite's actual sizes and costs.
  7. Grouped statistics: extend demo_regression.py so each case carries a doc tag (give the 12 cases 4 documents of 3 cases), group the paired differences by doc, and compare paired_bootstrap_ci with paired_cluster_bootstrap_ci from 2.7. How much wider is the cluster interval, and why?

Check yourself#

  1. Name four kinds of change that should trigger an eval, and the cheapest sufficient suite for each.
  2. Why is "last week's score" a bad baseline, and what should replace it?
  3. What are the four threshold types, and which one catches "overall fine but billing broke"?
  4. Why compare systems paired on the same cases instead of comparing two means?
  5. A 30-case suite shows "no significant difference" between v1 and v2. What does that actually mean?
  6. What does repeats=5 measure, and why does a warm cache break it?
  7. List three things that must be in a cache key for model calls.
  8. What is the difference between an infra_error and a task_error, and how should the gate treat each?
  9. What does the paired bootstrap CI rule do when the CI straddles the tolerance — fail, pass, or warn?
  10. Which suite tier should run on every commit, and why can't it use live provider calls?
  11. What three fields make an eval run reproducible that a bare score lacks?
  12. Why is a fully-cached gate run dangerous even when the cache key is correct?
  13. What is an allow-listed failure, and why does it need an expiry?
  14. Name two ways a suite gets "taught to" and the defence for each.
  15. Ten questions come from each of eight documents. Why is the per-case bootstrap CI too narrow, and what do you resample instead?
  16. Why does the live pr-eval job fail on a fork PR, and why is switching the trigger to pull_request_target the wrong fix?
  17. Why should a CI gate read only the regression slice of your eval set?

Further resources#


← 10A.7 — Evaluating Agents, Tool Use and Multimodal Systems | Module 10A overview | 10A.9 — Offline vs Online Evaluation →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close