IamBishal

Module 2Lesson 2 of 2Hands-on

2.2 Comparing two versions without fooling yourself

Runs prompt v1 and v2 of the drafter on the same 40 golden cases and compares them by case: per-criterion paired differences, a discordant list read before counting, and a paired bootstrap confidence interval. Adds a planning table for case counts, the TPR + TNR - 1 shrinkage factor for judge differences, and a pairwise judge run in both orders to expose position bias. The honest result: no improvement shown on 40 cases.

You have a golden set, four code graders and a calibrated judge. Now the question that started this tutorial: you changed the prompt, so is the new version better? This lesson writes prompt v2, runs it on the same 40 cases as v1, and compares the two honestly. The answer turns out to be "no improvement you can show with 40 cases", and the lesson explains why that is the right answer.

By the end you will be able to:

  • compare two versions case by case, and find the discordant cases that carry all the signal;
  • put a bootstrap confidence interval on a change in pass rate;
  • estimate how many cases a decision needs;
  • correct a judge-measured change for the judge's errors;
  • run a pairwise judge in both orders and spot position bias.

Before you start. You need Lesson 3's folder and its ideas: the golden set and code graders from Lesson 2, and TPR, TNR and FAIL as the positive class from Lesson 3. Python 3.12+ and uv 0.12, as before. No statistics background is assumed; the two ideas used here, a confidence interval and a sample-size estimate, are explained where they appear. Then:

bash
cd tutorials-code/build-an-llm-eval-suite/02-judging/04-comparing-two-versions
uv sync
uv run python compare_versions.py     # replays the recorded comparison; no key
uv run pytest tests                   # 42 passed

The script prints runs/comparison.json. Its first block is the code graders' result, "v1": 39, "v2": 40, with G26 the only case in v2_only. Every model call behind it was made once, on 2026-11-21, with --live --record, and saved as a line of runs/calls.jsonl. The line holds a key hashed from the model, the prompts and the schema, plus the answer and the token usage. ReplayModel answers each call by looking up its key, and raises NotRecorded rather than calling the API when the key is missing. Lesson 5 builds its gate on this. Only --live --record calls the API, and only that needs ANTHROPIC_API_KEY. Further down, the same output holds the judge and pairwise results discussed below:

json
"judges": {
  "claude-haiku-5-5": {"v1": 40, "v2": 39, "diff": -0.025, "ci95": [-0.075, 0.0], "youden": 1.0, "corrected_diff": -0.025},
  "claude-sonnet-5-5": {"v1": 38, "v2": 40, "diff": 0.05, "ci95": [0.0, 0.125], "youden": 0.967, "corrected_diff": 0.052}
},
"pairwise": {
  "claude-haiku-5-5": {"pairs": 40, "consistent": 32, "v2_won_both_orders": 2, "v1_won_both_orders": 30, "position_a_won_both": 5},
  "claude-sonnet-5-5": {"pairs": 40, "consistent": 24, "v2_won_both_orders": 7, "v1_won_both_orders": 17, "position_a_won_both": 3}
}

(Each entry also lists its split and flipped cases; they are trimmed here.)

The companion folder is Lesson 3's code plus prompt v2, evals/compare.py, compare_versions.py and the recorded runs, with 42 tests. Every number below comes from it. The runs were recorded on 2026-11-21.

1. Prompt v2

Prompt v1 said only "If you can't help, set escalate to true". Prompt v2 writes the policy down:

python
PROMPT_V2 = """You draft replies to customer tickets for Helpline's support team.

Escalation policy. Set escalate to true when any of these holds:
1. The ticket reports a suspected security incident: an account takeover, a leaked
   token or secret, or one customer's data shown to another.
2. The customer asks for a refund, a credit, a discount or a contract change.
   Support can't grant these.
3. The service is down or data is lost for the customer right now.
4. The knowledge base doesn't answer the question.
When you escalate, say in the reply that the ticket has been passed to the right
team. Don't try to answer what the knowledge base doesn't cover.

Promise rules:
- State only facts that appear in the articles you cite, and cite every article you use.
- Never promise refunds, credits, discounts, fix dates or new features.
- If the customer quotes a wrong number, correct it from the article."""

compare_versions.py drafts all 40 golden cases with v2, with the same drafter model (claude-sonnet-5-5), the same effort (low), the same structured output through output_config.format and the same tickets. It then grades both versions every way the suite can: the code graders, both judges, and a pairwise judge. The 40 v2 drafts cost $0.1015.

2. Compare cases, not totals

Two pass rates side by side, 39/40 against 40/40, throw away what you know: that both versions saw the same 40 tickets. Treated as two independent samples, most of the variation in each rate comes from which tickets happen to be hard, and that variation is the same for both versions. Compare them case by case instead, and the shared difficulty cancels out. The change is then (cases only v2 passes − cases only v1 passes) / 40. Every case lands in one of four cells:

python
def paired(a: dict[str, bool], b: dict[str, bool]) -> dict[str, list[str]]:
    """Split case ids by (passed under A, passed under B)."""
    out: dict[str, list[str]] = {"both_pass": [], "a_only": [], "b_only": [], "both_fail": []}
    for case_id in sorted(a):
        key = {
            (True, True): "both_pass",
            (True, False): "a_only",
            (False, True): "b_only",
            (False, False): "both_fail",
        }[(a[case_id], b[case_id])]
        out[key].append(case_id)
    return out

Cases that pass under both versions, or fail under both, say nothing about the difference. Only the discordant cases, those that pass under one version and fail under the other, move it. List them, and read every one.

Only cases that pass under one version and fail under the other move the difference, so read each one.

3. Read every discordant case

The first comparison, with Lesson 2's code graders, came out level:

json
{"v1": 39, "v2": 39, "split": {"both_pass": 38, "a_only": 1, "b_only": 1, "both_fail": 0},
 "v1_only": ["G02"], "v2_only": ["G26"], "diff": 0.0, "ci95": [-0.075, 0.075]}

One case improved and one regressed. G26 now escalates. v2's draft says "Support can't grant or promise service credits, so I've passed your ticket to the right team to review" and sets escalate: true. That is a real fix.

G02 "regressed" on numbers_supported. The v2 draft says "filter by date range (for example January 1 to December 31, 2025)". Lesson 2's date pattern handled "31 December", not "December 31". The draft is fine and the grader is wrong again. One more pattern goes into NOT_CLAIMS in evals/graders.py, from one more false alarm read in a real run. test_us_style_dates_are_not_claims pins it, and re-running compare_versions.py regrades both versions from the same recorded drafts:

python
re.compile(  # US-style dates: "December 31" (found in lesson 4's v1/v2 comparison)
    r"\b(?:January|February|March|April|May|June|July|August|September"
    r"|October|November|December) \d{1,2}\b"
),

Had you looked only at the totals, 39 against 39, you'd have concluded "no change" and missed both a real fix and a grader bug. The first read is kept in runs/comparison-before-grader-fix.json. With the fix:

Code graderv1v2DiscordantChange95% interval
All four pass3940G26 (v2 only)+0.025[0.000, 0.075]
escalation_correct3940G26 (v2 only)samesame
numbers_supported4040none0[0, 0]
schema_valid, cites_required4040none0[0, 0]

4. A confidence interval from the cases you have

bootstrap_diff asks how much the change could move if you'd drawn a different 40 tickets from the same kind of traffic. It resamples cases with replacement 10,000 times, keeping each case's v1 and v2 results together, and reads off the middle 95% of the differences:

python
def bootstrap_diff(
    a: list[bool], b: list[bool], reps: int = 10_000, seed: int = 0
) -> tuple[float, float, float]:
    """Pass rate of B minus A, with a 95% percentile interval from resampling cases (pairs kept)."""
    n = len(a)
    rng = random.Random(seed)
    diff = (sum(b) - sum(a)) / n
    draws = []
    for _ in range(reps):
        idx = [rng.randrange(n) for _ in range(n)]
        draws.append(sum(b[i] - a[i] for i in idx) / n)
    draws.sort()
    return diff, draws[int(0.025 * reps)], draws[int(0.975 * reps) - 1]

Resample cases, not individual drafts or judge repeats. The case is the unit you'd draw again. Breaking the pairs would throw away the pairing and widen the interval for nothing.

For v2 the change is +0.025, one case out of 40, and the interval is [0, 0.075]. It touches zero. That doesn't mean v2 isn't better. It means 40 cases can't show it.

Keep two kinds of uncertainty apart. G26's v2 draft really does escalate; reading it settled that. But each version drafted each ticket once, and drafts vary between runs, so v1 might have escalated G26 on another day. The bootstrap answers "how much would this change move with different tickets?". It doesn't answer "how much does one ticket's draft move between runs?". Repeating each draft a few times would measure that. A row with no discordant cases gets an interval of [0, 0] because there is nothing to resample, not because the change is known to be exactly zero.

5. How many cases would it take?

cases_needed is the usual sample-size estimate for a paired yes/no comparison (McNemar's test). It aims for 95% confidence, so a change this size would rarely appear by chance, and 80% power, so a real change this size is detected four times in five:

python
def cases_needed(delta: float, discordant: float, z: float = 1.96, z_power: float = 0.84) -> int:
    """Cases for a paired comparison to detect a change of `delta` (95% confidence, 80% power).

    `discordant` is the share of cases whose result differs between versions. This is the
    usual normal approximation for McNemar's test (Connor, 1987).
    """
    top = z * math.sqrt(discordant) + z_power * math.sqrt(discordant - delta * delta)
    return math.ceil((top / delta) ** 2)

You give it the change you want to detect and the share of cases you expect to flip between versions. The share that flips must be at least the change: a 0.10 change with 10% flipping means every flip goes the same way.

Change to detect10% of cases flip20% of cases flip
0.10 (4 in 40)77 cases155 cases
0.05 (2 in 40)312 cases625 cases

Halving the change you want to see roughly quadruples the cases you need. A 40-case golden set is enough to catch a regression that breaks a whole category, like Lesson 5's seeded one. It can't show that a prompt edit improved things by a few percent. Plan the size of the golden set from the smallest change you need to act on.

6. The judges, and what their errors do to a change

Both judges, claude-haiku-5-5 and claude-sonnet-5-5, graded every v1 and v2 reply against Lesson 3's sharpened judge criterion (criterion v2, not to be confused with prompt v2), one verdict each. Lesson 3 calibrated with a majority of three; one verdict here is cheaper, and runs/calibration.json in this folder records a self_consistency of 1.0 for every judge: all three repeats agreed on every item.

Judgev1v2DiscordantChange95% intervalTPR + TNR − 1
Haiku 5.54039G10 (v1 only)−0.025[−0.075, 0.000]1.000
Sonnet 5.53840G16, G37 (v2 only)+0.050[0.000, 0.125]0.967

The two judges disagree about which way v2 moved, and both intervals touch zero. Read the discordant cases. Haiku failed v2's G10, which begins "Hi, yes, in many cases." before correctly quoting the 30-day restore window. Sonnet failed v1's G16 and G37. Each adds advice the knowledge base doesn't hold, such as "another admin on your workspace will need to re-enable it". No case here is a clear regression.

There is one more correction to make. A judge that misses failures or fails good replies blurs every difference it measures. Say a fraction p of replies really fail. The judge flags TPR × p of them correctly, and also flags (1 − TNR) × (1 − p) good replies by mistake. Its measured failure rate is therefore

(1 − TNR) + (TPR + TNR − 1) × p.

The false alarms add a floor that doesn't move with p. Only the second term moves, so if the true failure rate changes by Δ, the judge measures about (TPR + TNR − 1) × Δ. Because FAIL is the positive class, a pass-rate change shrinks by the same factor.

python
def corrected_delta(measured: float, youden: float) -> float:
    """A judge with TPR + TNR - 1 = youden reports youden x the real change in failure rate."""
    return measured / youden

Lesson 3 measured Haiku at TPR 1.00 and TNR 1.00 against its 60 labels known by construction, so Haiku's factor is 1.000 and its change stands at −0.025. Sonnet measured TPR 1.00 and TNR 0.967, a factor of 0.967, so its +0.050 corrects to about +0.052. Those factors come from only 60 blatant items and carry their own uncertainty. The correction matters when the factor is small. A judge with TPR 0.80 and TNR 0.70 has a factor of 0.5, so it halves every change. The AI Lab's llm-judge-calibration-benchmark simulated such gates with Haiku 5.5 and Sonnet 5.5 judges. For every one of the ten judges in that benchmark, the measured change was ≈ (TPR + TNR − 1) × the true change, to within 0.2 percentage points.

Two cautions. Don't apply the correction to code graders: they're deterministic and weren't calibrated, so there's nothing to correct. And dividing by a small factor amplifies noise along with the signal.

7. Pairwise judging, in both orders

A pairwise judge sees both replies to one ticket and picks the better one. It is tempting because it asks directly "is v2 better?". It uses the same complete() as every other call, so structured output, effort low and the stop_reason check all apply:

python
PAIR_SCHEMA = {
    "type": "object",
    "properties": {"better": {"type": "string", "enum": ["A", "B"]}},
    "required": ["better"],
    "additionalProperties": False,
}

def pair_system(kb: dict[str, Article]) -> str:
    return (
        "You compare two draft replies to the same Helpline support ticket.\n"
        "Pick the reply that better answers the question the ticket asked while promising "
        "nothing the knowledge base doesn't support. A reply that says the ticket was passed "
        "to another team can be the better one.\n\n"
        f"Knowledge base:\n\n{kb_text(kb)}"
    )

def pair_judge(
    model: Model, ticket: str, reply_a: str, reply_b: str, kb: dict[str, Article]
) -> str | None:
    c = model.complete(pair_system(kb), pair_user(ticket, reply_a, reply_b), PAIR_SCHEMA)
    better = str((c.value or {}).get("better", "")).upper()
    return better if better in ("A", "B") else None

It also has a known weakness: the answer can depend on which reply comes first. So swap_test asks twice, once in each order. compare_versions.py passes v1's reply as first and v2's as second:

python
def swap_test(
    model: Model, ticket: str, first: str, second: str, kb: dict[str, Article]
) -> dict[str, object]:
    """Judge (first, second) and then (second, first); report which reply won each time."""
    ab = pair_judge(model, ticket, first, second, kb)
    ba = pair_judge(model, ticket, second, first, kb)
    win_ab = {"A": "first", "B": "second"}.get(ab or "")
    win_ba = {"A": "second", "B": "first"}.get(ba or "")
    return {
        "order_1": win_ab,
        "order_2": win_ba,
        "consistent": win_ab is not None and win_ab == win_ba,
        "position_a_won_both": ab == "A" and ba == "A",
    }

A verdict that flips when the order flips isn't a preference. It is position bias, and it counts as no answer. On the 40 pairs:

A verdict that changes when the order changes is position bias, not a preference.
JudgeSame winner in both ordersv1 won bothv2 won bothFirst position won both times
Haiku 5.532 of 403025
Sonnet 5.524 of 401773

Sonnet's verdict depended on the order for 16 of the 40 pairs. In 3 of those the first reply won both times, so in the other 13 the second reply won both times: Sonnet leaned towards whichever reply it read last. Haiku's 8 order-dependent pairs split 5 to the first position and 3 to the second. No pairwise call came back without a verdict. Where the verdict was stable, both judges preferred v1, Haiku by 30 to 2. The code graders and Sonnet's pass/fail judge leaned slightly towards v2, so the pairwise result points the other way.

Why? The pairwise question is "which is better?", not "does this meet the criterion?". v1's replies average 502 characters and v2's 334; this run doesn't show why. A longer reply with more detail can look better side by side even when both pass, and even when, as with G16, some of that detail is unsupported. That fits a preference for length but doesn't prove one: this run didn't vary length on its own. What it does show is that a pairwise "win" and a criterion PASS measure different things. Decide which one your product needs before you count wins.

8. So, is v2 better?

On these 40 cases, v2 fixed the one escalation v1 missed and changed nothing else that the code graders or a calibrated judge could show. The interval for that fix touches zero. Haiku's −0.025, with an interval of [−0.075, 0], doesn't rule out a small loss either, and the pairwise judges preferred v1's longer replies. The honest result is "no difference shown on 40 cases, in either direction". You might still choose v2 because its policy is written down and easier to review. If you do, record that as a judgement about the prompt, not a measured improvement.

9. Common problems

  • compare_versions.py raises NotRecorded. You changed v2's prompt, a judge criterion or the knowledge base. Re-record with --live --record; that makes about 360 calls.
  • The bootstrap interval changes between runs. It won't with the fixed seed=0. Without a seed the bounds can only move in steps of 1/40, because every resampled difference is a whole number of cases out of 40.
  • The intervals look too narrow. With one discordant case they can't be anything else: the interval is built from the cases you have. That is a reason to grow the golden set, not to trust the interval more.

10. Exercise

Using the recorded drafts, compute the paired split and bootstrap interval for escalation_correct alone, restricted to the 15 cases that expect escalation. Load runs/drafts-v1.jsonl and runs/drafts-v2.jsonl with read_jsonl from evals/runner.py, and pick the escalation cases with [c.id for c in load_golden() if c.escalate]. paired takes two dicts from case id to row["grades"]["escalation_correct"]. bootstrap_diff takes two lists of those booleans; build both lists by looping over the same sorted case ids, or the pairing is meaningless. Then use cases_needed to find how many escalation cases you'd need to detect a 0.10 change when 10% of them flip.

Verify. The split has one discordant case (G26, v2 only), the change is +0.067 (1 of 15), the interval is [0.0, 0.2], and cases_needed(0.10, 0.10) is 77. With a test for it, uv run pytest tests reports 43 passed.

11. The checklist so far

GapStatus
No written expectation per ticketClosed in Lesson 2
No mechanical checksClosed in Lesson 2
Prose: answers the question, promises nothing unsupportedClosed in Lesson 3
"v2 looks better" is an opinionClosed: paired splits, intervals, sample size, judge correction, swap test
Nothing stops a regression; nobody looks at real trafficLesson 5

12. What comes next

Lesson 5 turns the suite into a gate that runs in CI without an API key and fails on a seeded regression. It adds a review queue that brings production failures back into the golden set, and works out what one full eval run costs.

Key Takeaways

  • Write prompt v2 and run v1 and v2 on the same 40 golden cases, changing only the prompt.
  • Compute per-criterion paired differences as (wins − losses) / 40 and produce a list of discordant cases.
  • Explain why comparing two independent pass rates throws away the pairing and makes the comparison noisier than the data.
  • Read each discordant case before counting it, as with G02, where a code grader raised a false alarm on the US date "January 1 to December 31".
  • Bootstrap a 95% confidence interval by resampling cases with replacement, keeping v1 and v2 paired, never resampling outputs or judge repeats.
  • Explain why +0.025 with a 95% CI of [0, 0.075] supports "no improvement shown on 40 cases" and not a win for v2.
  • Use the planning table (95% confidence, 80% power) to show why 40 cases catch only large changes: 77 cases for a 0.10 change and 312 for a 0.05 change, with 10% of cases flipping.
  • Explain why an imperfect judge makes a real change look smaller: measured difference ≈ (TPR + TNR - 1) × true difference.
  • Apply the shrinkage correction only to judge-measured differences, never to code graders, and recognise that a small factor amplifies noise.
  • Explain why Haiku's 40 → 39 and Sonnet's 38 → 40 are both within noise.
  • Build a pairwise judge that judges each pair in both orders and reports flipped verdicts as position bias, not preference.
  • Explain why Haiku's v1 preference fits a length preference (502 vs 334 characters on average) but doesn't prove one.

Discussion

Ask questions, share what you learned, and help others.

    Loading discussion…

    Bishal SahaLet's build together

    Have a system to design, or an AI feature to get right?

    Tell me about the problem. You'll get a clear, honest view of the best way forward.

    • Reply within 24 hoursOn business days, with my honest view and a next step.
    • Accepting select engagementsArchitecture, AI features and full builds.
    • Remote, worldwideWorking with startups, SMEs and enterprises.