Free lesson · Trust Engineering

18 of 18 passed. Lower bound: 82.4%.

Every eval case run five times, on two real models. Charafeddine on what a perfect score on a small eval set proves, then the run. No sign-up.

1 min 49 s · Charafeddine on camera, from lesson 4.1 of the course · captions in the video.

See it run

Lesson 4.2 runs every case five times and asks how likely five tries in a row all pass: pass^k. Then it runs the contract suite on two real models, five trials per case. Both pass 18 of 18 cases on every trial, and the gate still reads a lower bound of 82.4%, because eighteen questions can't prove more. The same day turned up a gateway fallback: one request was answered by another model, and nothing in the eval showed it. The report now prints a line when that happens.

7 min 45 s · captions in the video, transcript below the lesson · narrated by an AI version of Charafeddine's voice, from his script.

The run on screen is a saved live run from 12 November 2026, two models through the course gateway. The failing example at the start of the video is a hand-written fixture, written that way on purpose; neither real model produced it.

Lesson 4.2 of 25 in Trust Engineering · €197, lifetime access · Enroll

Test your own evals

The same arithmetic on your results: pass@1, pass^k, and the cases that passed every trial, with their interval. One file, standard library only.

python3 pass_k.py results.csv      # one row per trial: case_id,passed (1 or 0)
python3 pass_k.py --cases 18 18    # or only the interval

Download pass_k.py or copy it below.

The script (106 lines)
"""Read your own eval results the way lesson 4.2 does: pass@1, pass^k, and the share of cases that passed every trial,
with a Wilson interval on cases.

    python3 pass_k.py results.csv      # your runs: one row per trial (case_id,passed with 1 or 0)
                                       #        or one row per case  (case_id,passes,trials)
    python3 pass_k.py --cases 18 18    # just the interval: 18 of 18 cases passed every trial

A case is one question with its checks; a trial is one run of it. pass^k is the chance that k tries in a row all pass.
The gate reads the last line: the cases that passed every trial, and the bottom of their 95% interval.
Standard library only. Python 3.9 or later.
"""
# From lesson 4.2 of Cohorte's Trust Engineering (cohorte.co/trust-engineering).
import argparse
import csv
import math
import sys
from collections import defaultdict
from statistics import NormalDist

Z = NormalDist().inv_cdf(0.975)                  # 1.96 for a 95% interval
YES, NO = ("1", "true", "pass"), ("0", "false", "fail")


def wilson(passes: float, n: float) -> tuple:
    """Wilson score interval: honest at 0 and at n, where the school formula says 'plus or minus nothing'."""
    if n == 0:
        return 0.0, 1.0
    p = passes / n
    centre = (p + Z * Z / (2 * n)) / (1 + Z * Z / n)
    half = Z * math.sqrt(p * (1 - p) / n + Z * Z / (4 * n * n)) / (1 + Z * Z / n)
    return max(0.0, centre - half), min(1.0, centre + half)


def pass_hat_k(cases: list, k: int) -> float:
    """Mean over cases of C(c, k) / C(n, k): the chance that k trials drawn from a case's n all passed."""
    return sum(math.comb(c, k) / math.comb(n, k) for c, n in cases) / len(cases)


def read(path: str) -> list:
    per_trial, per_case = defaultdict(lambda: [0, 0]), []
    with open(path, newline="", encoding="utf-8") as f:
        for row in csv.reader(f):
            row = [x.strip() for x in row if x.strip()]
            if not row or row[0].startswith("#"):
                continue
            try:
                if len(row) == 2:
                    v = row[1].lower()
                    if v not in YES + NO:
                        if per_trial or per_case:
                            sys.exit(f"Can't read {row[1]!r} as a pass or a fail (use 1/0, true/false or pass/fail).")
                        continue                      # a header row
                    per_trial[row[0]][0] += v in YES
                    per_trial[row[0]][1] += 1
                elif len(row) == 3:
                    per_case.append((int(row[1]), int(row[2])))
                else:
                    sys.exit(f"Each row needs 2 columns (case_id,passed) or 3 (case_id,passes,trials): {row}")
            except ValueError:
                continue                              # a header row
    cases = per_case + [tuple(v) for v in per_trial.values()]
    if not cases:
        sys.exit(f"No results found in {path}.")
    if any(not 0 <= c <= n or n == 0 for c, n in cases):
        sys.exit("Each case needs 0 <= passes <= trials and at least one trial.")
    return cases


def report(cases: list) -> None:
    n = len(cases)
    k = min(t for _, t in cases)
    if len({t for _, t in cases}) > 1:
        print(f"Trials per case differ; pass^k uses k up to {k}, the smallest count.")
    print(f"{n} cases, {k} trials per case")
    print(f"pass@1   {sum(c / t for c, t in cases) / n:6.1%}   (the average over trials)")
    for j in range(2, k + 1):
        print(f"pass^{j}   {pass_hat_k(cases, j):6.1%}")
    full = sum(c == t for c, t in cases)
    lo, hi = wilson(full, n)
    print(f"all {k} trials passed   {full}/{n}   95% interval {lo:.1%} to {hi:.1%}")
    print(f"Gate on {lo:.1%}, the bottom of that interval.")
    if full == n:
        need = math.ceil(0.95 * Z * Z / 0.05)
        print(f"With no failures, {need} cases are needed before that bottom reaches 95%.")


def main() -> None:
    ap = argparse.ArgumentParser(description="pass@1, pass^k and a Wilson interval on cases, from your eval results.")
    ap.add_argument("csv", nargs="?", help="results: case_id,passed per trial, or case_id,passes,trials per case")
    ap.add_argument("--cases", nargs=2, type=int, metavar=("PASSED", "TOTAL"),
                    help="only the interval: cases that passed every trial, out of all cases")
    a = ap.parse_args()
    if a.cases:
        full, n = a.cases
        if not 0 <= full <= n or n == 0:
            sys.exit("Need 0 <= PASSED <= TOTAL and TOTAL > 0.")
        lo, hi = wilson(full, n)
        print(f"{full}/{n} cases passed every trial: 95% interval {lo:.1%} to {hi:.1%}. Gate on {lo:.1%}.")
        return
    if not a.csv:
        ap.error("give a results file, or --cases PASSED TOTAL")
    report(read(a.csv))


if __name__ == "__main__":
    main()

What it prints for the lesson’s live run, written as one row per trial (18 cases, five trials each, all passed):

$ python3 pass_k.py results.csv
18 cases, 5 trials per case
pass@1   100.0%   (the average over trials)
pass^2   100.0%
pass^3   100.0%
pass^4   100.0%
pass^5   100.0%
all 5 trials passed   18/18   95% interval 82.4% to 100.0%
Gate on 82.4%, the bottom of that interval.
With no failures, 73 cases are needed before that bottom reaches 95%.

pass@1 and pass^k read 100% here. A release gate reads the last lines: the cases that passed every trial, and the bottom of their interval.

Where your evals go next

The course turns evals into evidence a release can stand on: failure categories counted from real traces, an eval set with hard and not-found cases, code checks before an LLM judge validated against human labels, paired comparisons between two versions, agent scenarios, and a gate in CI that blocks a worse release. Here is the whole course, in order.

Trust Engineering · the whole course

25 lessons in six modules, plus a Start Here section: 8 films with Charafeddine (lesson 0.2 opens the course), 14 screencasts, 5 labs and a capstone.

Module 1 · The confidence problem

  1. 1.1Why trust is harder than in classic MLfilm · 6 min
  2. 1.2Same format, right or wrong: why vibes, benchmarks and unchecked judges misleadfilm · 9 min
  3. 1.3What an eval must answer before you build itfilm · 8 min

Module 2 · Error analysis

  1. 2.1From traces to failure categoriesscreencast · 7 min
  2. 2.2Building the eval setscreencast · 4 min
  3. 2.3Lab: categorize 100 flagged failureslab
  4. 2.4Eval data that matches real trafficscreencast · 5 min

Module 3 · Graders

  1. 3.1Code first: deterministic checksscreencast · 6 min
  2. 3.2LLM judges, validated against human labelsscreencast · 7 min
  3. 3.3Human review that doesn't rubber-stampfilm · 6 min
  4. 3.4Lab: a judge you can defendlab

Module 4 · Statistics that matter

  1. 4.1What 20 out of 20 proves: intervals for small eval setsThe film at the top of this pagefilm · 5 min
  2. 4.2Repeated runs and pass^kThis lessonscreencast · 8 min
  3. 4.3Comparing two versions: paired differences and the regression vetoscreencast · 7 min
  4. 4.4Lab: write the 100-line statistics modulelab
  5. 4.5Correcting LLM labels with a small human auditscreencast · 5 min

Module 5 · Agents and uncertainty

  1. 5.1Agent evals: outcome, trajectory and safety scenariosscreencast · 7 min
  2. 5.2Consensus is not correctness: self-consistency, semantic entropy, conformal methods and their real scopefilm · 5 min
  3. 5.3Abstention: when the system should say "I don't know"screencast · 5 min
  4. 5.4Lab: an agent suite with a safety vetolab
  5. 5.5Multi-turn scenarios and a simulated userscreencast · 5 min
  6. 5.6Lab: a tool-selection evallab

Module 6 · Evals in the release process, and capstone

  1. 6.1Gates in CI, online evals, drift and recalibrationscreencast · 6 min
  2. 6.2Model migration: evaluate before you switchscreencast · 5 min
  3. 6.3Capstone: the Larkfield gatescreencast · 7 min
Enroll · €197

One-time, lifetime access, with 3 months in the Engine Room. Or the six courses for €797.

Read the full lesson 4.2

Course 2 of 6 in the Engineering Series, which builds one AI platform in Python for Larkfield Supply, a fictional company. In the lesson, E1 to E6 are the six courses; you can skip mentions of other lessons on a first read. Reading needs no setup. To run the code, you need the course repository (tag e2-m4-l2) and lessons 2.2, 3.1, 3.2 and 4.1, and the statistics primer.

You'll leave with pass^k and the rule that the case, not the trial, is the unit, in code, and a pass^2 you computed by hand. Part 2 builds the runner and the per-suite summary, and reads the first numbers from two real models.

In one screen

  • Use it on Monday: Run each eval case five times, gate on the share of cases that passed all five, and put the interval on cases, never on trials.
  • The picture: The case is the unit, not the trial: run every case k times, and pass^k asks how likely k tries in a row all pass.
  • The decision: Five trials per case, and the gate reads the share of cases that passed all five, with a Wilson interval on cases. pass@1 gets reported and never gated.
  • You'll run: uv run python -c "from aip.evals.stats import pass_hat_k; print(pass_hat_k([(3, 5)], 2))", which prints 0.3: a case that passed 3 of 5 trials has a 30% chance that two tries in a row both pass.

Why this matters

In a replay file I wrote for this course, Larkfield's answerer gets 82 of 90 answers right on the nominal suite: 91%. Inside that average sits a case it gets wrong five times out of five, with the same sentence each time: "EUR 2.5 million". The contract says EUR 5,000,000. A 91% average and a customer who gets the wrong cap every single time: that's what repeated runs are for. The pattern is real: in 2024 tau-bench showed gpt-4o solving about 61% of retail tasks on one try, and under 25% when all eight tries had to succeed.

One thing I'd rather you hear from me. I wrote that EUR 2.5 million failure by hand. On 12 November 2026 two real models, GPT-6 Luna and GPT-6.1 Sol, never produced it, or any other wrong figure, in 180 nominal trials. The fixture (a hand-written file of answers, played back instead of calling a model) shows you what the numbers do; part 2, step 6, shows what real models did.

The idea

A case is one question with its checks. A trial is one run of one case. Running each case k times measures what an average over cases can't: whether the system does the same thing twice. Your users feel that, even when the average looks fine.

From k trials per case you read two numbers. Call c the trials that passed for one case and n the trials run for it.

pass@1   mean success per trial                     "how often is one answer right"
pass^k   mean over cases of C(c,k) / C(n,k)         "chance that k tries in a row all pass"

C(c,k) is "c choose k", the number of ways to pick k items out of c. Here's pass^k on one case. It passed 4 of its 5 trials. Pick any 2 of the 5 trials: there are C(5,2) = 10 ways, and C(4,2) = 6 of them land on two passing trials. So this case contributes 6/10 = 0.6 to pass^2. Average that over all cases and you have the suite's pass^2. At k = 1 it equals pass@1; at k = n it's the share of cases that passed every trial.

pass^k is tau-bench's definition: "the chance that all k i.i.d. task trials are successful, averaged across tasks" (i.i.d.: each try a fresh, independent draw from the same system). The C(c,k)/C(n,k) form comes out right on average, neither high nor low. You'll also meet pass@k, the chance that at least one of k tries passes. It fits when someone picks the best of k tries. For a support answerer nobody picks, so I report pass^k.

The unit is the case, not the trial. Five trials of one case are five draws from one answer distribution. They tell you how stable that case is. They don't tell you about five different questions. So every interval is computed over cases.

Take four cases at 4/5, 4/5, 5/5 and 5/5. The gate reads the strictest number: 2 of the 4 cases passed every trial, and Wilson on 4 cases says the true share could be anywhere from about 15% to 85%.

The tempting mistake is to forget the cases and say "18 of 20 trials passed": that treats 20 trials as 20 questions and claims a lower bound of 69.9%, far more certainty than four questions can give you.

At k = n, pass^k is exactly that share: the cases that passed every trial. So the one interval to watch in this lesson is the share of cases that passed all k trials, with a Wilson interval on cases ("95% CI" in the reports: a 95% confidence interval). Lesson 4.3 adds two vetoes on top.

Build it

Part 1 has one new function to read, pass_hat_k, and then you compute it by hand on the fixture before any runner exists. That way, when part 2's runner prints pass^2, you already know where the number comes from. Everything in part 1, and part 2 through Step 5, runs offline on replay files: no stack, no key.

Go to this lesson's tag:

git checkout e2-m4-l2 && uv sync

Pinned: Python 3.12, inspect-ai 0.3.289, scipy 1.18.1, pydantic 2.14.3 (docs/VERSIONS.md). What the tag adds: Going deeper, at the end of this page.

Step 1: the intervals you already have

stats.py arrived in lesson 3.2 for the judge's intervals, and you've already read its wilson there. It takes a number of passes and a number of cases, and returns the 95% interval lesson 4.1 recommends for small sets. That's the only interval this lesson needs. The module's other two intervals from lesson 4.1, and wilson itself, are in Full code at the end of part 2.

Step 2: pass^k

What to notice. Both estimators take a list of (c, n) pairs, one per case, and average a per-case number. That's "the unit is the case" in code. pass_hat_k raises on a case with fewer than k trials instead of skipping it: skipping would bias the mean toward the cases that ran more.

From src/aip/evals/stats.py:

def pass_hat_k(trials: list[tuple[int, int]], k: int) -> float:
    """Unbiased pass^k: mean over tasks of C(c,k)/C(n,k). trials = [(c, n), ...]."""
    if any(n < k for _, n in trials):
        raise ValueError("every task needs at least k trials")
    return mean(comb(c, k) / comb(n, k) for c, n in trials)


def pass_at_k(trials: list[tuple[int, int]], k: int) -> float:
    """Unbiased pass@k: 1 - mean of C(n-c,k)/C(n,k). At least one success in k."""
    return 1 - mean(comb(n - c, k) / comb(n, k) for c, n in trials)

The same file holds standard_error and clustered_standard_error. In this lesson they feed only a secondary column you'll meet in part 2, so they're read in Going deeper, at the end of part 2 (lab 4.4 has you write both); standard_error returns in lesson 4.3 as the paired comparison's SE.

Try it 1 (5 min). Compute pass^2 by hand. Here are the 18 nominal cases of the baseline fixture after five trials each: 15 passed 5 of 5, northgate-liability-cap passed 0 of 5, northgate-breach-notice 3 of 5 and halden-liability-cap 4 of 5. What does each case add, and what's the mean? Then do pass^3 the same way. To check one case in code: uv run python -c "from aip.evals.stats import pass_hat_k; print(pass_hat_k([(3, 5)], 2))" prints 0.3.

Try it 2: decide (1 min). Larkfield's support answerer is asked the same contract question by many customers, and nobody picks the best of several answers. Which number goes on the dashboard: pass@1, pass^k or pass@k?

Both answers are in Check yourself, just below.

Check yourself

  1. Try it 1. pass^2: the fifteen perfect cases add 1 each, the 3/5 case C(3,2)/C(5,2) = 3/10, the 4/5 case 6/10, the 0/5 case nothing. (15 + 0.3 + 0.6) / 18 = 0.883. pass^3: C(3,3)/C(5,3) = 1/10 and C(4,3)/C(5,3) = 4/10, so (15 + 0.1 + 0.4) / 18 = 0.861. Part 2's runner prints the same two numbers.
  2. Try it 2. pass^k, next to pass@1. pass@k would credit the system for a right answer nobody sees.

Part 2: the runner, the summary, and two real models

Why this matters

In part 1 you worked out by hand that one case at 0 of 5 and two shaky ones pull pass^2 down to 0.883. Nobody does that for a hundred cases. In this part the runner does it for every case and every trial, the summary turns it into the one interval the gate reads, and then the same code meets two real models, which turn out to be far more consistent than my fixture.

Build it, continued

Step 3: the runner, cases times trials

The runner plays every case k times and grades every trial. Its full file is in Full code; two pieces carry the idea.

What to notice. A trial passes only if every check returned True, so a check that couldn't decide (None) counts as a failure. And each trial records model, the served model the gateway reports, and fell_back, true when the gateway's fallback alias answered instead of the model under test.

From src/aip/evals/runner.py:

@dataclass
class Trial:
    trial: int
    output: str
    checks: list[CheckResult]
    cost_usd: float | None = None
    latency_s: float = 0.0
    metrics: dict = field(default_factory=dict)  # tracked, not graded: tool calls, steps
    model: str = ""            # the model that answered, as the gateway says (not the alias asked for)
    fell_back: bool = False    # answered by the fallback alias: this trial did not test the model under test

    @property
    def passed(self) -> bool:
        return all(c.passed is True for c in self.checks)

metrics holds what we track and never grade; lesson 5.1 fills it. fell_back is there because of a real miss: on 12 November 2026 the gateway quietly answered one smart request with fast, and nothing in the eval showed it. Now the report names any trial like that, so a smart report can't quietly hold fast answers.

What to notice. run_suite is a plain double loop: cases outside, trials inside. It hands each trial's number t to respond, so a replay file can return the answer recorded for that exact trial. And respond doesn't care where the answer comes from.

def run_suite(cases: list[EvalCase], respond: Responder, trials: int = 5,
              judge_model: ChatModel | None = None) -> list[CaseResult]:
    results = []
    for case in cases:
        result = CaseResult(case.id, case.suite, case.cluster_key, case.tags)
        for t in range(trials):
            out = respond(case, t)
            reply, extra = out if isinstance(out, tuple) else (out, {})
            text = reply.text or ""
            checks = grade(case, text, judge_model, extra)
            result.trials.append(Trial(t, text, checks, reply.cost_usd, reply.latency_ms / 1000,
                                       extra.get("metrics", {}), reply.model, reply.fell_back))
        results.append(result)
    return results

A Responder is anything that maps (case, trial number) to an answer. Three kinds feed this same loop: a live model, a replay file of recorded answers, and, in lesson 5.1, an agent transcript. That's why you can run the whole lesson offline and then point the same code at a real model.

respond can also return a pair, the reply and extra state the checks need, such as an agent scenario's final state in lesson 5.1; that's the isinstance line. grade runs the code checks first, then any judges. A judge's UNKNOWN becomes None, which fails the trial.

Step 4: the summary per suite

The summary is where trials become the one number the gate reads. This lesson reads summarize and one line of the report; lesson 4.3 reads the gate decision.

What to notice. Each case becomes one number, its share of passing trials (case_means). counts feeds pass_hat_k for every k from 1 to the number of trials. strict counts the cases that passed every trial.

The start of summarize, from src/aip/evals/report.py:

def summarize(results: list[CaseResult], suite: str) -> SuiteSummary:
    rows = [r for r in results if r.suite == suite]
    k = min(len(r.trials) for r in rows)
    case_means = [r.passes / len(r.trials) for r in rows]

And the two lines the gate's number comes from, a few lines further down:

    counts = [(r.passes, len(r.trials)) for r in rows]
    strict = sum(c == n for c, n in counts)

The summary then returns stats.wilson(strict, len(rows)). That's the Wilson interval from lesson 4.1, a range built by a procedure that captures the true rate in 95% of repeated samples, not a 95% chance that the true rate is in this one range, which stays honest even at 18 out of 18. It's on cases, never on trials.

The lines in between feed a secondary pass@1 column that the gate never reads. Going deeper covers it, and the whole function is in Full code.

Try it (1 min). Three cases come back with counts of (5, 5), (4, 5) and (5, 5). What's strict, and what n goes into Wilson? (Answer in Check yourself.)

Step 5: run it

Every replay file in data/larkfield/evals/ is a hand-written fixture, and the builder's docstring says so: "Hand-written fixture outputs, NOT model runs." Here's the baseline's, with one case wrong the same way every time.

What to notice. The liability-cap case gets the same wrong sentence in all five trials (for t in range(5)). The other two cases fail only on some trials, which is what makes pass^k fall as k grows.

From data/larkfield/evals/_build/make_contract_replays.py:

# Version v1 (baseline). The liability cap is wrong in every trial, in the same confident format:
# 90 days right, EUR 2.5M wrong. A stable hallucination: five out of five agree, all wrong.
V1_WRONG = {
    "northgate-liability-cap": {t: "Northgate's total liability is capped at EUR 2.5 million per contract year (clause 6)." for t in range(5)},
    "northgate-breach-notice": {1: "Larkfield must give 90 days written notice (clause 2).",
                                3: "90 days written notice, under clause 2."},
    "halden-liability-cap": {2: "Liability is capped at EUR 400,000 per year (clause 7)."},
}

Now run the baseline replays, five trials per case. The command is long, but it only does four things: load the cases, replay v1's answers five times each, summarize the nominal suite, and print pass@1, pass^k, the all-trials count with its Wilson interval, and the liability-cap case's answers. Read the output, not the command:

uv run python -c "from aip.evals.case import load_cases; \
from aip.evals.runner import replay_responder, run_suite; \
from aip.evals.report import summarize; \
r = run_suite(load_cases('data/larkfield/evals/contract_qa/cases.yaml'), \
replay_responder('data/larkfield/evals/contract_qa/replays/answerer-v1.jsonl'), 5); \
s = summarize(r, 'nominal'); \
print('pass@1', round(s.pass_at_1, 3), 'clustered SE', round(s.pass_at_1_se, 3)); \
print('pass^k', {k: round(v, 3) for k, v in s.pass_hat_k.items()}); \
print('all 5 trials passed', s.all_trials_passed, 'of', s.cases, 'Wilson', tuple(round(x, 3) for x in s.all_trials_ci)); \
cap = next(x for x in r if x.id == 'northgate-liability-cap'); \
print(cap.id, cap.passes, '/ 5', set(t.output for t in cap.trials))"
pass@1 0.911 clustered SE 0.042
pass^k {'1': 0.911, '2': 0.883, '3': 0.861, '4': 0.844, '5': 0.833}
all 5 trials passed 15 of 18 Wilson (0.608, 0.942)
northgate-liability-cap 0 / 5 {"Northgate's total liability is capped at EUR 2.5 million per contract year (clause 6)."}

These numbers are on the fixtures: a fixture lets you watch every number move without a key, and is never a measurement of a model. pass^k falls from 91.1% to 83.3% as k grows, because three cases have a failing trial. Fifteen of 18 cases passed every trial, Wilson 60.8% to 94.2%. The last line is the stable failure: five trials, one distinct answer, wrong.

Compare with your part 1 try-it: the printout's pass^2 and pass^3, 0.883 and 0.861, are the sums you did by hand. (The clustered SE on the first line feeds the secondary column; skip it.)

The tests for this step, all offline (one of them runs Inspect AI, an optional framework: Going deeper):

uv run pytest tests/evals/test_inspect_adapter.py tests/evals/test_report.py tests/evals/test_judge_prompt_identity.py -q
8 passed

Your turn (10 min)

Change the fixture and predict the numbers before the code does. In data/larkfield/evals/contract_qa/replays/answerer-v1.jsonl, find the line for halden-liability-cap, trial 2 (the EUR 400,000 answer). Replace its output with the right answer, copied from trial 1 of the same case. Now predict three numbers: pass^2, pass^5, and how many cases passed all five trials. Then rerun the Step 5 command.

Undo the edit with git checkout -- data/larkfield/evals/contract_qa/replays when you're done, because the tests pin the fixture. Check yourself has the answer.

Step 6: the same summary on two real models

Predict first (2 min). The fixture had a case that was wrong in all five trials. Before you read on: will two real models show a stable wrong answer like that, a few shaky cases, or none? Write it down.

On 12 November 2026 I ran the contract suite through the gateway, five trials per case, with GPT-6 Luna (gpt-6-luna) behind fast and GPT-6.1 Sol (gpt-6.1-sol) behind smart, no sampling parameters. Same summarize as this lesson's, through aip-eval release, the command you build in lesson 4.3. The contract set has two suites: nominal holds the 18 questions the contracts answer, and escalation the 3 they don't, where the right reply is to say so. Both runs print Result: **PASS**. The full tables are in Going deeper; these are the columns the gate reads:

Model Suite All trials passed (95% Wilson) Cost USD
fast nominal 18/18 (82.4% to 100.0%) 0.0044
fast escalation 3/3 (43.9% to 100.0%) 0.0009
smart nominal 18/18 (82.4% to 100.0%) 0.0873
smart escalation 2/3 (20.8% to 93.9%) 0.0155

Only nominal has a threshold in this gate.

So, the answer to your prediction: no stable wrong answer on either model. Both pass all 18 nominal cases on all five trials, so pass^5 is 100%, far more consistent than my fixture. The one shaky case is on smart: an escalation case at 4 of 5 trials (pass^5 66.7% on that suite). It has no threshold, so smart still passes. That miss is a correct answer scored wrong by a check; lesson 4.3 reads it.

18 of 18 gives a Wilson lower bound of 82.4%. That bound treats 18 questions I wrote, about two contracts, as independent: read it as "no failure seen here", not "at least 82% on your traffic".

The 105 trials cost USD 0.0053 on fast and USD 0.1028 on smart.

What breaks

pass@1 as the headline. You see 91% with a case at 0/5 inside, because trials were averaged across cases. Report pass^k next to it, and list every case that failed a trial (lesson 4.3 prints them).

Trials counted as independent items. Ninety trials of 18 cases are not 90 pieces of evidence. 18 cases are 18 pieces of evidence, however many trials ran; counting the trials claims far more certainty than you have (Going deeper has the numbers). Keep the case as the unit (Step 4).

A gate judge that isn't the validated judge. Without its few-shot examples under the same id, lesson 3.2's TPR and TNR describe another judge. The gate builds the prompt with the same function the validation used, and a test checks that the two send the same prompts (Going deeper).

Trials that aren't independent draws. Five trials through a response cache, or on a provider that's deterministic at its default, are one answer copied five times, and pass^k measures nothing. Turn caching off for eval traffic at the gateway, and check that trials of a free-text case differ at least sometimes.

A trial answered by a model you didn't ask for. A fallback inside an eval run makes a smart report partly a fast report. Each trial records the served model and the flag, and the report names the cases (Step 3).

Decide

Default: five trials per case, pass^k reported for every k, the gate reading the share of cases that passed all k with a Wilson interval on cases. pass@1 with its cluster-adjusted interval (Going deeper) is reported, never gated.

More trials when the product retries or users ask the same thing many times, and you want pass^8 for real. Cost grows linearly: cases × trials × (system tokens + judge tokens).

One trial for a grader-only regression check on a deterministic step (a parser, a router with fixed rules). Say so on the eval card.

You now have the instrument that sees inconsistency. Lesson 4.3 uses it to compare two versions and block the worse one.

Check yourself

  1. A case passed 3 of 5 trials. What does it add to pass^2, and to pass^5? C(3,2)/C(5,2) = 0.3 to pass^2, before averaging over cases. Zero to pass^5.
  2. Your suite has 30 cases run 5 times. What's n for the gate's interval? 30. The gate's interval is on cases. Five trials of one case tell you about that case, not about five new questions.
  3. pass@1 is 95% and pass^5 is 70%. What happened? Failures are spread across many cases, each failing now and then. The system is inconsistent, which users feel even when the average looks fine.
  4. All five trials of every case are identical, character for character, on a free-text task. What do you check first? That trials aren't served from a cache, and what the provider's default sampling does for that model. If every trial is a copy, k = 5 is k = 1.

Try it. strict is 2: only the cases at 5 of 5 count. n is 3, the cases, never the 15 trials. So the gate reads Wilson on 2 out of 3.

Your turn. The halden case now adds 1 instead of 0.6 to pass^2, so pass^2 = (16 + 0.3) / 18 = 0.906, and pass^5 = 16/18 = 0.889. The printout says all 5 trials passed 16 of 18 Wilson (0.672, 0.969). Fixing one trial of one case moved the gate's lower bound by more than six points. With 18 cases, every case counts.

Transcript

Today every case runs several times, and we read what comes back. Here's why. Larkfield's answerer gets ninety-one percent of its answers right on the contract suite, and I want to show you what that number hides. Everything you'll see for the next few minutes runs on replay files. I wrote them by hand, with failures placed on purpose, so we can watch the statistics work without a model or a key.

At the end I'll show you what two real models did on the same cases, and, well, it's a different story from the fixture. All right, top line: ninety-one percent per answer. Second line: pass-hat-k. It's the chance that k tries in a row all pass, and it falls from ninety-one to eighty-three as k grows. Third line: fifteen of eighteen cases passed all five trials, and with eighteen cases the honest interval on that runs from sixty-one to ninety-four percent.

And the last line. Five trials, one distinct answer, wrong every time. The contract says five million. Five out of five agree on two and a half. Now, the statistics module arrived in the judge lesson, because the judge's rates needed intervals. These are the three from lesson four point one. Wilson is the default. Clopper-Pearson when someone needs a bound that holds by construction.

And the Beta interval if you want a Bayesian reading. Notice that Wilson takes a float for n? In a minute you'll see why: we feed it an effective number of cases, which isn't a plain count. So this is tau-bench's estimator. For each case, you count the ways to pick k passing trials out of the ones that passed, over the ways to pick any k, and you average over cases.

At k equals one it's the plain pass rate; at k equals the number of trials, it's the share of cases that never failed. Below it, the error bar. Ten questions about one contract aren't ten independent items, right? So Miller's clustered error adds the products of deviations between every pair inside a cluster: square of the sum, minus the sum of squares.

When scores in a cluster move together, the error grows. All right, the runner. A trial is one run of one case. A responder is anything that turns a case and a trial number into an answer: a live model, a replay file, later an agent transcript. And that one signature is why the same runner serves all three. A trial passes only if every check said yes; a check that couldn't decide counts as a failure.

Each trial also keeps the model the gateway says answered, and whether a fallback did. And the model responder sends the system prompt and the document, with no sampling setting, so whatever varies between trials is the provider's default. Now, when a case uses a judge, grading builds the prompt with the same render function the validation used, few-shot examples included, the worked examples we put in the judge's prompt.

The check is named after the prompt id, and that id hashes the examples too. This test sends the seventy-six test items both ways, through the validation and through the gate, and requires the prompts to be identical, byte for byte. Why does that matter? If they weren't, every error rate you measured in lesson three point two would describe some other judge.

So here's where the wrong answer came from. The first line of this file says it: hand-written fixture outputs. No model ran here. Same sentence, all five trials. I wrote it that way on purpose, because a confident wrong figure, identical every time, is the failure that agreement can't catch. Keep that in mind for the end of this video. Now, the unit is the case.

Each case's five trials become one number, its share of passes, and only then do we compute an error, clustered by source document. Then the question: how many independent cases is this suite worth? Cases on the same contract count for less. The floor at one means clustering can only shrink that number. And when every case has the same score, there's nothing to compare, so it falls back to the number of documents.

Remember that sentence. Wilson goes on that number. The gate reads something else, by the way: the count of cases that passed every trial, with a Wilson interval on cases. Let's check one number by hand. Fifteen cases passed all five, and they count one each. The case at three of five adds three tenths. The one at four of five adds six tenths.

The one at zero adds nothing. Fifteen point nine over eighteen is point eight eight three, same as the output. So here's what that floor is for. With only two contracts in the set, the clustered error comes out smaller than the plain one, on both versions. Taken literally, eighteen cases would count as more than eighteen. Two clusters can't estimate a correlation, so that number is noise, and the floor keeps it from inflating the evidence.

Both versions count as eighteen cases, at most. If you want clustering to mean something, add documents. Now, our runner is enough for the gate. On a real model you'll want Inspect AI too: parallel epochs, every transcript logged, a viewer. The adapter keeps our checks as the scorer, so a grade means the same thing whichever runner produced it. Epochs come back as our trials, so the same summary applies.

When it reaches the gateway, it uses the eval-runner's key, like every other eval call. And the tests run offline: Inspect's mock model, the effective cases, the fallback line, the judge prompt. All right, now the real thing. On the twelfth of November I ran these twenty-one cases, five trials each, on two real models through the gateway. GPT-6 Luna behind fast, GPT-6.1 Sol behind smart.

Nominal suite: eighteen out of eighteen cases passed every trial, on both. Neither model produced the two-and-a-half-million answer, or any wrong figure, in a hundred and eighty trials. So the stable failure is a fixture. And look at the pass-at-one interval on a perfect run: thirty-four percent to a hundred. That's the fallback: no variance, so the effective number of cases is the number of documents, two.

Read the cases column instead: lower bound eighty-two. One more thing from that day. One smart request was answered by Luna, after a gateway fallback, and nothing in the eval showed it. Now each trial records who answered, and the report prints this line whenever a fallback did. Lesson three point two has the full story. So, what to keep. Five trials per case.

Report pass-hat-k next to the average, always. Put the binomial interval on cases, never on trials. And when a fixture tells a good story, check it on a real model before you believe it. Next up, we turn this into an eval gate, and compare two versions properly. See you there.

Going deeper

What the tag adds

git diff --stat=72 e2-m3-l2..e2-m4-l2
 .../evals/_build/make_contract_replays.py     |  92 ++++++++++++
 .../contract_qa/replays/answerer-v1.jsonl     | 105 ++++++++++++++
 .../contract_qa/replays/answerer-v2.jsonl     | 105 ++++++++++++++
 .../contract_qa/replays/answerer-v3.jsonl     | 105 ++++++++++++++
 .../0202-release-gate-reads-a-lower-bound.md  |  11 ++
 .../0206-inspect-needs-openai-package.md      |  11 ++
 src/aip/evals/inspect_adapter.py              |  64 ++++++++
 src/aip/evals/report.py                       | 137 ++++++++++++++++++
 src/aip/evals/runner.py                       |  96 ++++++++++++
 [...]
 14 files changed, 902 insertions(+)

Where the rules are written down

  • Decision record 0202 in docs/decisions/, which lands at this tag, states this page's rule (the gate reads the Wilson lower bound on the share of cases that passed every trial) and the two vetoes of lesson 4.3.
  • Decision record 0201 in docs/decisions/ says why scipy is in the module: the Beta quantile behind Clopper-Pearson.

Going deeper: the pass@1 column, Inspect AI, and the numbers

This part is depth. The gate never reads it, so skip it on a first read.

One caution the gate doesn't fix. Questions about the same contract tend to fail together, so 18 cases drawn from two contracts are worth less than 18 independent questions, and even this interval is optimistic; with only two contracts we can't measure by how much. The summary prints a secondary column, pass@1 with a cluster-adjusted interval, that tries to account for it. It's never gated, and the rest of this section shows why two contracts are too few for it to work.

Cases on one document count for less. Ten questions about one contract fail together when the model misreads that contract. They're closer to one piece of evidence than to ten. Miller's clustered standard error handles this, with one cluster per source document. A standard error (SE) is how far the measured rate typically sits from the true rate if you reran on fresh cases (the statistics primer gives the picture); the clustered version grows when cases in one cluster move together.

The pass@1 column turns the clustered SE into an interval through an effective number of cases. Here's the chain:

  1. Compute the SE over case means, and Miller's clustered SE with one cluster per source document.
  2. The design effect is how much clustering inflates the variance: (clustered SE / SE over cases)², floored at 1, because clustering never adds information.
  3. Divide the number of cases by the design effect. That's the effective number of cases.
  4. Put a Wilson interval on that smaller number.

This is our choice, a Kish-style effective n, not a formula from the papers. It keeps Wilson's behavior at 100%, where an interval from the central limit theorem has zero width.

What to notice. Miller adds, for each cluster, the sum over pairs i ≠ j of the product of deviations from the mean. The loop computes it as (Σd)² − Σd². When the cases on one document fail together, those products are positive and the SE grows. With singleton clusters the cross terms vanish and you get the plain SE back, which test_clustered_se_with_singleton_clusters_equals_naive checks.

From src/aip/evals/stats.py:

def clustered_standard_error(scores: list[float], clusters: list[str]) -> float:
    """Miller eq. 4: add the within-cluster cross terms to the naive variance.

    Ten questions about one contract are not ten independent items.
    """
    n, m = len(scores), mean(scores)
    by_cluster: dict[str, list[float]] = defaultdict(list)
    for s, c in zip(scores, clusters, strict=True):
        by_cluster[c].append(s - m)
    cross = 0.0
    for devs in by_cluster.values():
        total = sum(devs)
        cross += total * total - sum(d * d for d in devs)  # sum over i != j
    return sqrt(standard_error(scores) ** 2 + cross / n**2)

What to notice. In effective_cases, the floor at 1 means clustering can only shrink the count. And when every case has the same score, there's no variance to compare, so it falls back to the number of sources.

From src/aip/evals/report.py:

def effective_cases(case_means: list[float], clusters: list[str]) -> float:
    """How many independent cases the suite is worth. The unit is the case: its K trials are averaged
    first (Miller sec. 3), so trials never count as items. Cases sharing a source count for less:
    design effect = clustered variance (Miller eq. 4) / per-case variance, floored at 1, because
    clustering never adds information. With no variance to compare (all cases equal), fall back
    to the number of sources (conservative)."""
    m = len(case_means)
    se_case = stats.standard_error(case_means) if m > 1 else 0.0
    if se_case == 0:
        return float(len(set(clusters)))
    design_effect = max(1.0, (stats.clustered_standard_error(case_means, clusters) / se_case) ** 2)
    return m / design_effect

That fallback explains Step 6. A perfect run prints an interval from 34.2% to 100.0%, while the v1 fixture, with three failing cases, gets 69.9% to 97.8%. With every case at 1.0 there's no variance, so effective_cases returns the number of sources, 2, and Wilson on 2 out of 2 has a lower bound of 34.2%. test_no_variance_falls_back_to_the_number_of_sources pins it. It's conservative on purpose, and one more reason the gate reads the cases column.

The other surprise goes the opposite way. With only two documents, the cross terms can come out negative and the clustered SE smaller than the plain one. On the replays that's what happens:

uv run python -c "
from aip.evals.case import load_cases; from aip.evals.runner import replay_responder, run_suite; from aip.evals.report import summarize, effective_cases; from aip.evals import stats
cases = load_cases('data/larkfield/evals/contract_qa/cases.yaml')
for v in ('v1', 'v3'):
    r = [x for x in run_suite(cases, replay_responder(f'data/larkfield/evals/contract_qa/replays/answerer-{v}.jsonl'), 5) if x.suite == 'nominal']
    means = [x.passes / len(x.trials) for x in r]; clusters = [x.cluster for x in r]
    naive, clustered = stats.standard_error(means), stats.clustered_standard_error(means, clusters)
    s = summarize(r, 'nominal')
    print(v, 'SE over cases', round(naive, 3), 'clustered SE', round(clustered, 3), 'effective cases', round(effective_cases(means, clusters), 1), 'of', len(r), 'pass@1 CI', tuple(round(x, 3) for x in s.pass_at_1_ci))
"
v1 SE over cases 0.059 clustered SE 0.042 effective cases 18.0 of 18 pass@1 CI (0.699, 0.978)
v3 SE over cases 0.024 clustered SE 0.008 effective cases 18.0 of 18 pass@1 CI (0.773, 0.996)

Two clusters can't estimate a correlation; the floor at 1 keeps both versions at 18 cases. More documents come before you trust a clustered SE, which Miller warns "can be over 3X larger than naive standard errors".

The live run in full (Step 6)

The two aip-eval release runs of 12 November 2026, as printed:

$ uv run aip-eval release --gate data/larkfield/evals/contract_qa/gate.yaml --model fast --out reports/live-fast
Model: `fast`. Result: **PASS**
| Suite | Cases | Trials | pass@1 (95% CI, cluster-adjusted) | pass^k | All trials passed (95% Wilson) | Cost USD |
|---|---|---|---|---|---|---|
| escalation | 3 | 5 | 100.0% (34.2% to 100.0%) | 100.0% (k=5) | 3/3 (43.9% to 100.0%) | 0.0009 |
| nominal | 18 | 5 | 100.0% (34.2% to 100.0%) | 100.0% (k=5) | 18/18 (82.4% to 100.0%) | 0.0044 |

$ uv run aip-eval release --gate data/larkfield/evals/contract_qa/gate.yaml --model smart --baseline reports/live-fast/report.json --out reports/live-smart
Model: `smart`. Result: **PASS**
| escalation | 3 | 5 | 93.3% (38.3% to 99.7%) | 66.7% (k=5) | 2/3 (20.8% to 93.9%) | 0.0155 |
| nominal | 18 | 5 | 100.0% (34.2% to 100.0%) | 100.0% (k=5) | 18/18 (82.4% to 100.0%) | 0.0873 |

The pass@1 column's 34.2% on a perfect run isn't a bug: with no variance to measure, it counts the 2 contracts as its cases (the effective_cases fallback above walks through it).

The run used an earlier version of the E2 code, from before it was split into one tag per lesson; "Which code" in docs/LIVE_RUNS_E2.md lists what changed since.

Plumbing of the live responder

The replay file is JSONL (one JSON object per line), one line per case and trial. The live responder sends the system prompt and the document and no sampling parameter: sampling is opt-in per alias in the platform's settings (AIP_SAMPLING), never something an eval sets.

Optional: the same cases on Inspect AI

Our runner is enough for the gate. Inspect AI adds parallel epochs (its word for trials), a log of every transcript, and a viewer. src/aip/evals/inspect_adapter.py keeps our checks as the scorer, so the grades don't depend on the runner, and run_inspect turns epochs back into our Trial objects, so summarize applies unchanged. The two reducers per case are the core of it:

def eval_task(cases: list[EvalCase], trials: int = 5, system: str = DEFAULT_SYSTEM) -> Task:
    # Reducers: "mean" is pass@1 per case; at_least(trials) is 1 only if every trial passed.
    return Task(dataset=to_dataset(cases), solver=[system_message(system), generate()],
                scorer=aip_checks(), epochs=Epochs(trials, ["mean", at_least(trials)]))

With the stack up, the eval key from lesson 2.1 and the inspect-gateway extra installed, two tests go through the gateway. On the offline config the sim answers, so they prove plumbing: a case comes back with a cost and a latency, and Inspect reaches the gateway.

uv sync --extra inspect-gateway
uv run pytest tests/integration/test_evals_gateway.py -q
2 passed

Inspect's setup, in full. Inspect's own stderr(cluster=...) applies a finite-cluster correction that Miller's formula doesn't, so its number can differ slightly; we follow the paper. gateway_model reaches the gateway through Inspect's OpenAI-compatible provider on the eval-runner's key, which needs the optional openai package (uv sync --extra inspect-gateway, decision record 0206 in docs/decisions/). It also loads ./.env into the process environment when it runs.

Not built yet: an Inspect log of the answerer on a real model, for the viewer. The commands are run_inspect(cases, gateway_model("fast"), trials=5, log_dir="logs/inspect"), then uv run inspect view --log-dir logs/inspect.

The fallback line in the report

The gateway once answered a smart request with fast, on 12 November 2026 (the story is in lesson 3.2, part 2, Going deeper). From src/aip/evals/report.py:

    if fell := [c for c in report["cases"] if c.get("fallbacks")]:
        lines += ["", f"{sum(c['fallbacks'] for c in fell)} trial(s) answered by the gateway's fallback alias, "
                  f"not `{report['model']}`: {', '.join(c['id'] for c in fell)}."]

It prints only when a trial fell back. A test (test_a_trial_the_fallback_alias_answered_is_in_the_report) scripts one such trial and checks the flag, the count and this line.

What breaks in the secondary column

A clustered SE that adds cases. With two documents the clustered SE came out smaller than the plain one. The design-effect floor at 1 stops it from inflating the count, and the real fix is more documents.

Numbers behind the core

The core of this lesson states these in plain words; here are the exact figures.

Three ways to count four cases (4/5, 4/5, 5/5, 5/5). The gate: 2 of the 4 cases passed every trial, Wilson on 4 cases. Averaging each case first, as Miller does, gives 0.8, 0.8, 1 and 1, so 3.6 out of 4, and a Wilson lower bound of 41.7%: still four cases, so still honest. Counting 18 passes out of 20 trials as if they were 20 questions claims 69.9%: it pretends to have 20 questions.

The judge the runner runs. It's the one lesson 3.2 validated, prompt for prompt, and its validated rates come with lesson 3.2's limit: they hold on inputs like the validation items, which were short excerpts. The judge prompt in the gate. The judge check is named judge:<prompt id>, the id the validation recorded in lesson 3.2, and the prompt behind it is the same: judge.grade builds it with Judge.render, few-shot examples included, exactly as validate_judge does. A gate that sent a different prompt would carry a TPR and TNR that describe some other judge. So a test (test_gate_sends_the_validated_prompt) checks that the validation and the gate send the same 76 prompts, byte for byte, all 16 examples in each.

A question for this section. A real model passes 18 of 18 cases on every trial, and the pass@1 interval runs from 34.2% to 100%. Bug? No. With no variance the effective number of cases falls back to the number of source documents, here 2. Read the cases column instead: 18/18, lower bound 82.4%.

Full code

src/aip/evals/stats.py, the three intervals (from lesson 4.1):

def z_for(confidence: float = 0.95) -> float:
    """Two-sided normal quantile: 1.96 for 95%."""
    return NormalDist().inv_cdf(1 - (1 - confidence) / 2)


def wilson(passes: float, n: float, confidence: float = 0.95) -> tuple[float, float]:
    """Wilson score interval for a pass rate. Sane at 0/n and n/n. Takes a fractional n (effective cases)."""
    z = z_for(confidence)
    center = (passes + z * z / 2) / (n + z * z)
    half = z * sqrt(passes * (n - passes) / n + z * z / 4) / (n + z * z)
    return max(0.0, center - half), min(1.0, center + half)


def clopper_pearson(passes: int, n: int, confidence: float = 0.95) -> tuple[float, float]:
    """Exact (conservative) interval from Beta quantiles. Coverage never below nominal."""
    a = 1 - confidence
    low = 0.0 if passes == 0 else beta.ppf(a / 2, passes, n - passes + 1)
    high = 1.0 if passes == n else beta.ppf(1 - a / 2, passes + 1, n - passes)
    return float(low), float(high)


def beta_interval(passes: int, n: int, confidence: float = 0.95) -> tuple[float, float]:
    """Bayesian interval: uniform Beta(1,1) prior, posterior Beta(1+S, 1+N-S)."""
    a = 1 - confidence
    posterior = beta(1 + passes, 1 + n - passes)
    return float(posterior.ppf(a / 2)), float(posterior.ppf(1 - a / 2))

src/aip/evals/stats.py, the estimators and standard errors:

def pass_hat_k(trials: list[tuple[int, int]], k: int) -> float:
    """Unbiased pass^k: mean over tasks of C(c,k)/C(n,k). trials = [(c, n), ...]."""
    if any(n < k for _, n in trials):
        raise ValueError("every task needs at least k trials")
    return mean(comb(c, k) / comb(n, k) for c, n in trials)


def pass_at_k(trials: list[tuple[int, int]], k: int) -> float:
    """Unbiased pass@k: 1 - mean of C(n-c,k)/C(n,k). At least one success in k."""
    return 1 - mean(comb(n - c, k) / comb(n, k) for c, n in trials)


def standard_error(scores: list[float]) -> float:
    """CLT standard error of the mean: sqrt(sample variance / n)."""
    n, m = len(scores), mean(scores)
    return sqrt(sum((s - m) ** 2 for s in scores) / (n - 1) / n)


def clustered_standard_error(scores: list[float], clusters: list[str]) -> float:
    """Miller eq. 4: add the within-cluster cross terms to the naive variance.

    Ten questions about one contract are not ten independent items.
    """
    n, m = len(scores), mean(scores)
    by_cluster: dict[str, list[float]] = defaultdict(list)
    for s, c in zip(scores, clusters, strict=True):
        by_cluster[c].append(s - m)
    cross = 0.0
    for devs in by_cluster.values():
        total = sum(devs)
        cross += total * total - sum(d * d for d in devs)  # sum over i != j
    return sqrt(standard_error(scores) ** 2 + cross / n**2)

src/aip/evals/runner.py, the whole file:

"""Run a suite: every case, k independent trials, every check on every trial."""
import json
from collections.abc import Callable
from dataclasses import dataclass, field
from pathlib import Path

from aip.evals.case import EvalCase
from aip.evals.checks import CheckResult, run_checks
from aip.evals.judge import load_judge
from aip.evals.model import ChatModel, Completion, completion

# (case, trial number) -> completion, or (completion, extra) when the checks need more than the text,
# for example an agent scenario's final state.
Responder = Callable[[EvalCase, int], Completion | tuple[Completion, dict]]

DEFAULT_SYSTEM = ("You answer questions about Larkfield Supply documents. Use only the document given. "
                  "If the document does not state the answer, say that it does not.")


@dataclass
class Trial:
    trial: int
    output: str
    checks: list[CheckResult]
    cost_usd: float | None = None
    latency_s: float = 0.0
    metrics: dict = field(default_factory=dict)  # tracked, not graded: tool calls, steps
    model: str = ""            # the model that answered, as the gateway says (not the alias asked for)
    fell_back: bool = False    # answered by the fallback alias: this trial did not test the model under test

    @property
    def passed(self) -> bool:
        return all(c.passed is True for c in self.checks)


@dataclass
class CaseResult:
    id: str
    suite: str
    cluster: str
    tags: list[str]
    trials: list[Trial] = field(default_factory=list)

    @property
    def passes(self) -> int:
        return sum(t.passed for t in self.trials)


def model_responder(model: ChatModel, system: str = DEFAULT_SYSTEM) -> Responder:
    def respond(case: EvalCase, trial: int) -> Completion:
        user = f"Document:\n{case.context}\n\nQuestion: {case.input}" if case.context else case.input
        return model.complete([{"role": "system", "content": system}, {"role": "user", "content": user}])
    return respond


def replay_responder(path: str | Path) -> Responder:
    """Recorded outputs, one JSONL line per {case_id, trial, output}. For offline gates and tests."""
    rows = [json.loads(line) for line in Path(path).read_text().splitlines() if line.strip()]
    table = {(r["case_id"], r["trial"]): r for r in rows}
    name = f"replay:{Path(path).stem}"

    def respond(case: EvalCase, trial: int) -> Completion:
        row = table[(case.id, trial)]
        return completion(row["output"], name, cost_usd=row.get("cost_usd"))
    respond.model_name = name  # type: ignore[attr-defined]
    return respond


def grade(case: EvalCase, output: str, judge_model: ChatModel | None, extra: dict | None = None) -> list[CheckResult]:
    code_checks = [c for c in case.checks if c.type != "judge"]
    results = run_checks(code_checks, output, {"case": case, **(extra or {})})
    for spec in (c for c in case.checks if c.type == "judge"):
        if judge_model is None:
            results.append(CheckResult(f"judge:{spec.value}", None, "no judge model configured"))
            continue
        judge = load_judge(spec.value, int(spec.params.get("version", 1)))
        verdict = judge.grade(judge_model, case.context or "", case.input, output)
        ok = None if verdict.label == "unknown" else verdict.label == "pass"
        results.append(CheckResult(f"judge:{judge.prompt_id}", ok, verdict.critique))
    return results


def run_suite(cases: list[EvalCase], respond: Responder, trials: int = 5,
              judge_model: ChatModel | None = None) -> list[CaseResult]:
    results = []
    for case in cases:
        result = CaseResult(case.id, case.suite, case.cluster_key, case.tags)
        for t in range(trials):
            out = respond(case, t)
            reply, extra = out if isinstance(out, tuple) else (out, {})
            text = reply.text or ""
            checks = grade(case, text, judge_model, extra)
            result.trials.append(Trial(t, text, checks, reply.cost_usd, reply.latency_ms / 1000,
                                       extra.get("metrics", {}), reply.model, reply.fell_back))
        results.append(result)
    return results

data/larkfield/evals/_build/make_contract_replays.py, the docstring:

"""Writes the contract Q&A replay files. Hand-written fixture outputs, NOT model runs.

They stand in for three versions of the answerer so the gate, the paired
comparison and the regression veto can be shown offline. Each failure is
placed on purpose and listed in contract_qa/README.md.
Run: uv run python data/larkfield/evals/_build/make_contract_replays.py
"""

tests/evals/test_judge_prompt_identity.py, the prompt-identity test:

def test_gate_sends_the_validated_prompt(evals_dir):
    rows = load_labeled(evals_dir / "judge_labels" / "grounded_figures.jsonl")
    test = [r for r in rows if r["split"] == "test"]
    validation_prompts: list[str] = []
    v = validate_judge(load_judge("grounded_figures", 1), recording_judge(validation_prompts), rows, "test")

    gate_prompts: list[str] = []
    for item in test:
        case = EvalCase(id=item["id"], input=item["question"], context=item["source"],
                        checks=[Check(type="judge", value="grounded_figures", params={"version": 1})])
        results = grade(case, item["answer"], recording_judge(gate_prompts))
        assert results[0].name == f"judge:{v.judge}"

    assert gate_prompts == validation_prompts  # byte-identical, few-shot examples included
    assert all(p.count("<example>") == 16 for p in gate_prompts)
    assert v.judge == VALIDATED_PROMPT_ID

src/aip/evals/report.py, from the top through summarize:

"""Release report: per suite, intervals and pass^k; then the gate decision and its vetoes."""
import json
from dataclasses import asdict, dataclass
from pathlib import Path

from aip.evals import stats
from aip.evals.runner import CaseResult


@dataclass
class SuiteSummary:
    suite: str
    cases: int
    trials: int  # per case
    pass_at_1: float  # mean over all trials
    pass_at_1_se: float  # clustered SE over case means (Miller eq. 4; clusters = shared source)
    pass_at_1_ci: tuple[float, float]  # Wilson on the effective number of cases (never trials)
    pass_hat_k: dict[str, float]  # unbiased pass^k for k = 1..trials
    all_trials_passed: int  # cases that passed every trial
    all_trials_ci: tuple[float, float]  # Wilson interval on that count: the number the gate reads
    cost_usd: float | None


def effective_cases(case_means: list[float], clusters: list[str]) -> float:
    """How many independent cases the suite is worth. The unit is the case: its K trials are averaged
    first (Miller sec. 3), so trials never count as items. Cases sharing a source count for less:
    design effect = clustered variance (Miller eq. 4) / per-case variance, floored at 1, because
    clustering never adds information. With no variance to compare (all cases equal), fall back
    to the number of sources (conservative)."""
    m = len(case_means)
    se_case = stats.standard_error(case_means) if m > 1 else 0.0
    if se_case == 0:
        return float(len(set(clusters)))
    design_effect = max(1.0, (stats.clustered_standard_error(case_means, clusters) / se_case) ** 2)
    return m / design_effect


def summarize(results: list[CaseResult], suite: str) -> SuiteSummary:
    rows = [r for r in results if r.suite == suite]
    k = min(len(r.trials) for r in rows)
    case_means = [r.passes / len(r.trials) for r in rows]
    clusters = [r.cluster for r in rows]
    mean = sum(case_means) / len(case_means)  # equals the mean over trials when every case has k trials
    se = stats.clustered_standard_error(case_means, clusters) if len(rows) > 1 else 0.0
    # A CLT interval collapses to zero width at 0% or 100%. Use Wilson instead, on the effective
    # number of cases, never on the number of trials.
    n_eff = effective_cases(case_means, clusters)
    counts = [(r.passes, len(r.trials)) for r in rows]
    strict = sum(c == n for c, n in counts)
    costs = [t.cost_usd for r in rows for t in r.trials if t.cost_usd is not None]
    return SuiteSummary(
        suite, len(rows), k, mean, se, stats.wilson(mean * n_eff, n_eff),
        {str(j): stats.pass_hat_k(counts, j) for j in range(1, k + 1)},
        strict, stats.wilson(strict, len(rows)), sum(costs) if costs else None)
Sources
  • Yao et al., "τ-bench: A Benchmark for Tool-Agent-User Interaction in Real-World Domains", 2024 (pass^k definition, estimator, gpt-4o retail numbers): https://arxiv.org/abs/2406.12045 , https://arxiv.org/html/2406.12045 (checked 12 Nov 2026)
  • Miller, "Adding Error Bars to Evals", 2024 (clustered standard errors, averaging trials per item): https://arxiv.org/abs/2411.00640 (checked 12 Nov 2026)
  • Anthropic, "Demystifying evals for AI agents", 9 Jan 2026 (task, trial, grader vocabulary): https://anthropic.com/engineering/demystifying-evals-for-ai-agents (checked 12 Nov 2026)
  • Bowyer, Aitchison and Ivanova, ICML 2025 (Wilson over CLT on small sets): https://arxiv.org/abs/2503.01747 (checked 12 Nov 2026)
  • Inspect AI 0.3.289, scorer reference (Epochs, at_least, stderr(cluster=...)): https://inspect.aisi.org.uk/reference/inspect_ai.scorer.html , https://pypi.org/project/inspect-ai/ (checked 12 Nov 2026)
  • Reference repository ai-platform, branch series, tag e2-m4-l2: src/aip/evals/{stats,runner,report,inspect_adapter}.py, tests/evals/{test_report,test_judge_prompt_identity,test_inspect_adapter}.py, tests/integration/test_evals_gateway.py; decision records 0201, 0202, 0204 and 0206 in docs/decisions/; offline commands and the gateway tests run at the tag on 13 Nov 2026
  • Live run, 12 Nov 2026 (docs/LIVE_RUNS_E2.md, an earlier version of the E2 code: see "Which code" there): LiteLLM 1.108.5 gateway, fast = openai/gpt-6-luna, smart = openai/gpt-6.1-sol (from the x-litellm-model-name header), five trials per case on the 21-case contract suite, costs from the gateway's cost header and spend log

That was one lesson of 25.
The rest builds on it.

The other 24 build the rest of the evidence: failures counted from real traces, an eval set with hard and not-found cases, an LLM judge validated against human labels, paired comparisons between two versions, agent scenarios, and a gate in CI that blocks a worse release.

Start here
Trust Engineering
€197
One-time · lifetime access · all future updates included.
  • 25 lessons, 8 films and 14 step-by-step screencasts
  • The course code as git bundles, labs with tests and a capstone
3 months in the Engine Room, Cohorte's community of people who put AI to work. What's inside the Engine Room
The Engineering Series
€797
All six courses, one payment, lifetime access. €1,182 if bought separately.
  • Trust Engineering and the five other courses: 138 lessons, one codebase
  • 38 films and 75 step-by-step screencasts
3 months in the Engine Room, Cohorte's community of people who put AI to work.
14-day money-back guarantee if you haven't completed the first module.

Refunds, company invoices and client use of the code: see the FAQ.

A free lesson from each courseCourse 1 · A key and a budget per agent
Course 2 · An LLM judge, checked against human labels
Course 3 · A tamper-evident audit trail for agents
Course 4 · An agent that asks when it could leak
Course 5 · Retrieval that knows who is asking
Course 6 · A model outage you've already rehearsed