Module: L1-M06 · Duration: ~210 min (estimate, including the independent exercise) · Previous: L03 · Next: L05 - Reporting regressions and triaging flaky AI tests
1. Introduction
The team has just changed the system prompt, or wants to move to a new model. The question for the tester: has any case got worse? With ordinary software, rerunning the test suite is enough. With an LLM feature, both the baseline and the new version fluctuate, so "the pass rate dropped by 4%" can be a real regression, or just randomness.
This lesson teaches how to compare two versions on the same golden dataset, how to use a simple statistical test to tell a real change from a fluctuation, and how to understand the limits of the test: not seeing a difference does not mean there is no difference.
2. Learning objectives
- Compare two versions case by case, on the same dataset and with the same number of runs.
- Explain the p-value of Fisher's exact test for a 2×2 table, and how to read it correctly.
- Classify each case: REGRESSION, IMPROVEMENT, NO_SIGNIFICANT_CHANGE.
- Explain statistical power: why few runs miss real changes.
- Recognise the problem of comparing many cases at once.
3. Prerequisites and tools
4. Concepts
4.1 The 2×2 table and Fisher's exact test
For one case, put the results of the two versions into a table:
| Pass | Fail | |
|---|---|---|
| Baseline | 49 | 1 |
| Candidate | 20 | 30 |
The question: if the two versions are truly the same, how likely is it to see a table this unbalanced (or more so)? That figure is the p-value. Fisher's exact test computes it directly. According to the SciPy documentation, for a 2×2 table "the null hypothesis is that the true odds ratio of the populations underlying the observations is one" [R1], that is, the two versions have the same pass rate.
The lab uses the threshold α = 0.05: p < 0.05 counts as a change; the direction of the change tells whether it is a REGRESSION or an IMPROVEMENT.
Everyday example. Toss a coin 4 times and get 3 heads: nobody would claim the coin is biased. Toss it 40 times and get 30 heads: now it looks suspicious. The same 75%, but with more tosses chance finds it harder to explain.
Worked example: Fisher's test with 8 runs. Baseline 3 passes, 1 fail; candidate 1 pass, 3 fails.
- Totals: 4 runs on each side; 4 passes and 4 fails in all.
- If the two versions are the same, the 4 passes could fall on any 4 of the 8 runs: there are C(8, 4) = 70 ways, each equally likely.
- The number of ways for the baseline to get exactly a passes is C(4, a) × C(4, 4 − a). For a = 0, 1, 2, 3, 4: 1, 16, 36, 16, 1 ways (70 in total).
- The observed table has a = 3, probability 16/70. The tables that are no more likely are a = 0, 1, 3, 4. Add them up: (1 + 16 + 16 + 1)/70 = 34/70 ≈ 0.4857.
- p ≈ 0.49: 3/4 against 1/4 looks like a big difference, but with 8 runs chance explains it very easily.
Check it with code (save as try_l04.py in the lab folder, run python try_l04.py, then delete the file):
from math import comb
from lab.compare import fisher_two_sided
# baseline 3 pass / 1 fail, candidate 1 pass / 3 fail: 4 passes in total, 8 runs
for a in range(5):
print(f"a={a}: probability {comb(4, a) * comb(4, 4 - a)}/{comb(8, 4)}")
print(f"p for [[3, 1], [1, 3]]: {fisher_two_sided(3, 1, 1, 3):.4f}")
print(f"p for [[30, 10], [10, 30]]: {fisher_two_sided(30, 10, 10, 30):.6f}")
Output (copied from a real run on Python 3.14.6 and 3.12.3, Linux, 2026-11-06; both versions gave identical output):
a=0: probability 1/70
a=1: probability 16/70
a=2: probability 36/70
a=3: probability 16/70
a=4: probability 1/70
p for [[3, 1], [1, 3]]: 0.4857
p for [[30, 10], [10, 30]]: 0.000015
The last line has the same two rates, 75% and 25%, but 40 runs on each side: p drops from 0.4857 to 0.000015. "An odds ratio of one" in SciPy's definition only means that the two versions have the same pass rate.
4.2 Reading a p-value correctly
- A small p: the data is hard to explain by randomness, so there is evidence of a change.
- A large p: there is not enough evidence. That is not evidence that the two versions are the same. The
lab calls this class
NO_SIGNIFICANT_CHANGE, not "unchanged". - A p-value does not tell you how large or how important a change is. A high-risk case that drops from 100% to 92% may not be "statistically significant" with 50 runs, but it is still worth running more.
Everyday example. A court ruling "not enough evidence to convict" does not mean the court has proved the defendant innocent. A large p is the same: there is just not enough evidence yet.
Good vs bad. Q-REFUND in the L05 demo: 50/50 down to 46/50, p = 0.117.
| Weak report sentence | Good report sentence | |
|---|---|---|
| Wording | "Q-REFUND unchanged, safe to release" | "Q-REFUND: 50/50 → 46/50, p = 0.117: not enough evidence to conclude. High-risk case, so run more once under the rule for running more before release" |
| Why | Turns "no evidence" into "evidence of no change" | States the numbers, the right level of certainty, and a next step based on risk |
4.3 Statistical power
Power is the probability that a comparison detects a change that is real. Power depends on the size of the change and on the number of runs. The exercise in section 9 measures this directly: repeat the same comparison with 20 seed pairs and count how many times it detects a real improvement. With few runs, it almost never detects it.
Consequence: before running, decide the smallest change you care about for each risk level, and choose a number of runs that is large enough to see it.
Everyday example. Look for a hairline crack with a weak magnifying glass: not seeing a crack does not mean there is none. Few runs are a weak magnifying glass.
Good vs bad.
| Weak plan | Good plan | |
|---|---|---|
| Before running | "Run 10 times on each side and see whether anything changed" | "The order-cancellation case is high risk: to see a change of 20 percentage points, choose the number of runs from the measured power (exercise in section 9)" |
| When nothing shows | "No regression" | "No significant change with N runs; with this N, the power to see a 20-point change is low/high" |
4.4 Comparing many cases
With α = 0.05, each case that has not changed still has up to about a 5% chance of being labelled "changed" by randomness (Fisher's exact test is conservative, so the real figure is usually lower; a case at 100% on both sides is never labelled). With 100 cases, you may see a few false "regressions". The lab does not correct for comparing many cases, and the report says so explicitly. The practical treatment at Level 1: rerun the labelled cases following the rule for running more (L02 section 4.3): the number of runs decided in advance, a new seed, the conclusion from the new run only, at most once. Level 2 teaches correction methods.
Everyday example. Buy 100 lottery tickets and winning a few small prizes is normal, not a sign of a "lucky number". Comparing many cases is the same: a few false "regressions" are almost certain to appear.
Worked example: an A/A comparison. Compare a configuration with itself (only the seed differs). Every change
label here is a false alarm. Save the following as try_l04.py in the lab folder, run python try_l04.py, then
delete the file:
from lab import baseline, compare, dataset
from lab.simulated_model import SimulatedFAQModel
cases = dataset.load()
base = baseline.build(SimulatedFAQModel(), cases, n=50, seed=53)
cand = baseline.build(SimulatedFAQModel(), cases, n=50, seed=54) # the SAME configuration
for row in compare.compare(base, cand):
if row["change"] != "NO_SIGNIFICANT_CHANGE":
print(f"{row['case']}: {row['base_rate']:.2f} -> {row['cand_rate']:.2f} p={row['p_value']:.4f} {row['change']}")
Output (copied from a real run on Python 3.14.6 and 3.12.3, Linux, 2026-11-06; both versions gave identical output):
Q-HOTLINE: 0.86 -> 0.62 p=0.0113 REGRESSION
- Both sides are the same configuration,
faq-v1@sim-2026-09, so there is no real regression. - Yet Q-HOTLINE is labelled REGRESSION with p = 0.0113, below α = 0.05.
- The reason: 8 cases, each with its own chance of a wrong label. Q-HOTLINE has a pass rate of about 80%, so its pass count moves a lot between two runs.
- The treatment: run only the labelled case again, once, with a new seed, and conclude from the new run. The exercise in section 9.1 does exactly this.
4.5 A model change is a change that needs testing
Anthropic's deprecations page recommends "thorough testing of your applications with the new models well before the retirement date" [R2]. The golden dataset and the comparison in this lesson are exactly that "thorough testing": run the baseline with the old model, run the candidate with the new model, on the same dataset, with the same number of runs.
Everyday example. A rice-meal shop plans to change its rice supplier. The owner cooks the new rice for the same menu and the same number of portions, and compares it with the old rice, weeks before the old contract ends, instead of waiting for the day the old rice runs out.
Good vs bad.
| Weak model switch | Good model switch | |
|---|---|---|
| When | The day the old model is retired, when requests start to fail | A few weeks before the retirement date |
| What | Try a few questions by hand on the new model | Run the baseline (old model) and the candidate (new model) on the same golden dataset, with the same number of runs, and compare case by case |
5. Technical deep dive
5.1 lab/compare.py
fisher_two_sided(a, b, c, d)for the table[[a, b], [c, d]]: adds up the probabilities of every table with the same row and column totals that is no more likely than the observed table. The lab writes it itself withmath.combso that no external library is needed; the test compares it with known values (for example[[3, 1], [1, 3]]gives 0.4857).compare(base, candidate, alpha)callscheck_comparablefirst (L03), then returns one row per case. Each row is a dict{"case", "base_rate", "cand_rate", "p_value", "change", "base_errors", "cand_errors", "base_valid", "cand_valid"}. Environment errors do not go into the 2×2 table.
5.2 Two different seeds
The baseline and the candidate use different seeds (1 and 2). In the lab, the random sequences already differ by configuration, so the more important point is not to reuse the same samples: an extra run with the same seed would repeat exactly the first runs of the previous one, so it is not an independent confirmation (L02, the rule for running more). With a real API, every run at a new time is a new sample.
6. The QA perspective
- Process: fix the dataset (fingerprint); choose the number of runs by risk; run the baseline and the candidate; compare; rerun the labelled cases; only then triage (L05).
- What can go wrong: comparing rates without a test; treating a large p as "safe"; using the same seed; forgetting that many cases produce false regressions; comparing two different datasets.
- Reporting: the rates on both sides, N, the p-value, α, and the sentence "no correction for multiple cases" if that is the case.
7. Real-world scenarios
Scenario 1 (fictional): a regression hidden behind the overall rate. The pass rate of the whole dataset drops from 93% to 90%, and the team calls it a "fluctuation". When the cases are compared one by one, a high-risk case about cancelling orders drops from 97% to 60%, while two other cases rise. Lesson: compare by case, not only by the overall rate.
Scenario 2 (fictional): 3 false regressions in 60 cases. A comparison of 60 cases reports 3 regressions with p around 0.03-0.04. When they are rerun with a new seed and twice the number of runs, all three disappear. That is exactly what section 4.4 predicts.
8. Hands-on tutorial
8.1 Running the demo
python -m lab.demo l04
Output (copied from a real run, 2026-10-31):
candidate faq-v2@sim-2026-09:
Q-CANCEL 0.68 -> 1.00 p=0.0000 IMPROVEMENT
Q-SHIP 0.98 -> 0.40 p=0.0000 REGRESSION
no significant change: Q-ADDR, Q-COD, Q-FREE-RETURN, Q-HOTLINE, Q-REFUND, Q-WARRANTY
candidate faq-v1@sim-2026-10:
Q-FREE-RETURN 0.84 -> 0.32 p=0.0000 REGRESSION
no significant change: Q-ADDR, Q-CANCEL, Q-COD, Q-HOTLINE, Q-REFUND, Q-SHIP, Q-WARRANTY
Reading the output:
- Prompt change (
faq-v2): Q-SHIP is a regression (98% down to 40%), Q-CANCEL is an improvement (68% up to 100%). One change can fix a defect and create one at the same time. - Snapshot change (
sim-2026-10): only Q-FREE-RETURN is a regression. Q-REFUND changes its wording (L01) but is not labelled, because its pass rate does not change.
8.2 Running the tests
python -m pytest tests/test_l04_compare.py -v
Read test_a_visible_drop_is_not_always_evidence: 100% down to 92% with 50 runs is not statistically significant.
8.3 Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
ValueError: ... fingerprints differ |
The two sides use different datasets | Run both on the same dataset |
Every case is NO_SIGNIFICANT_CHANGE although you see a difference |
Too few runs (low power) | Increase the number of runs for the important cases |
| Every case is identical on both sides | The same seed and the same configuration are used | Check the configuration and use different seeds |
9. Independent exercise
Problem: Measure the power of the comparison.
Requirements: complete exercises/test_l04_power.py:
- The change to detect: Q-CANCEL,
faq-v1@sim-2026-09→faq-v2@sim-2026-09(the new prompt really improves this case). - For n = 5, 10, 20, 50, repeat the comparison with 20 seed pairs (baseline
100 + 2*i, candidate101 + 2*i) and count how many times the result isIMPROVEMENT. - Write the results into
DETECTED, then write a loop that recomputes them and asserts each figure. - Write 3-5 sentences: for this case, how many runs do you choose, and why?
Deliverable: the test file and the explanation paragraph.
Acceptance criteria: the test passes; the explanation paragraph uses your figures.
Hint: a dataset with one case is enough: [c for c in dataset.load() if c["id"] == "Q-CANCEL"].
9.1 Extra exercise: run more, by the rules
Time: 15-30 minutes. File: exercises/test_l04_extra_follow_up.py.
Problem: The first comparison labels a few cases. Some are real changes, some are false alarms (§4.4). Write the function that runs more by the rule for running more (L02 section 4.3): the labelled cases only, once, new seeds, and the conclusion from the new run only.
Requirements:
- Run
python -m pytest exercises/test_l04_extra_follow_up.py. Untouched, 5 tests fail with a message starting withFailed: TODO. - Write
follow_up(first_base, first_cand, cases, n, seed)following the four steps in the docstring. - Run again until you get
5 passed. Write 2 sentences: intest_an_a_a_false_alarm_goes_away, if you added the first run's passes/fails to the follow-up run, how could the conclusion about Q-HOTLINE go wrong? Why?
Acceptance criteria: 5 tests pass; the answer to step 3 says that the first run's data were picked out because they looked like a regression, so pooling them pulls the conclusion towards the false alarm.
Hint: model_of(first_base["config"]) rebuilds exactly the configuration; {seed, seed + 1} & {...} is the
intersection of two sets.
9.2 Real-world scenario: switching the model of a university admissions chatbot (fictional)
Binh Minh University (fictional) has a chatbot that answers applicants. The model it uses will be retired in 60 days. The team ran the golden dataset 40 times per case on the old and the new model:
| Case | Topic | Risk | Old model (pass/fail) | New model (pass/fail) | Timeouts (new model) |
|---|---|---|---|---|---|
| A1 | Last year's admission score for Information Technology | high | 39/1 | 31/9 | 0 |
| A2 | Application deadline | high | 40/0 | 38/0 | 2 |
| A3 | Tuition fees | medium | 36/4 | 39/1 | 0 |
| A4 | Dormitory | low | 30/10 | 24/16 | 0 |
| A5 | Scholarships | medium | 34/6 | 34/6 | 0 |
The team lead asks: "Can we switch the model yet?"
Your task (45-60 minutes):
- Compute the p-value of each case with
compare.fisher_two_sided, and label it with α = 0.05. - For each case, write one sentence that reads the result correctly (§4.2), including the cases that are not significant.
- Choose the cases to run again, say why, and by which rule.
- Write a decision note (5-8 sentences) for the team lead.
A good answer has:
- Five p-values computed with the lab, a label per case, and timeouts kept out of the 2×2 table
- No sentence that turns "not significant" into "unchanged" or "safe"
- At least one remark on power for a case whose number of runs is too small to conclude
- A mention of false alarms when many cases are compared, and a follow-up plan that follows the rule
- A decision note with a clear conclusion, conditions, and a timeline against the retirement date
10. Knowledge check
0/19 done · Results are kept in this browser only.
P02 · True or false
P03 · Short answer
What is power, and which two factors increase it?
P04 · Short answer
You compare 100 unchanged cases with α = 0.05. About how many cases may be falsely labelled as changed, and how do you handle it?
P05 · Essay
(Scenario) The team wants to move to a new model because the old model is about to be retired. Write a five-step regression test plan.
P06 · Match
P08 · Multiple choice
P09 · Spot the bug
The excerpt below is copied from compare() in lab/compare.py, with one line modified. Find the bug.
if rb is None or rc is None:
change = "NO_DATA"
elif p < alpha and rc > rb:
change = "REGRESSION"
elif p < alpha and rc > rb:
change = "IMPROVEMENT"
else:
change = "NO_SIGNIFICANT_CHANGE"P10 · Recall
Lesson: L1-M06-L03P11 · Select all that apply
P12 · True or false
P13 · Short answer
To confirm a REGRESSION, you rerun the candidate with the same seed 2 and the same 50 runs. Why is this not a confirmation?
P15 · Fill in the blank
P16 · True or false
P17 · Apply now
In code-labs/l1-m06, do the extra exercise of §9.1 in exercises/test_l04_extra_follow_up.py, then run python -m pytest exercises/test_l04_extra_follow_up.py.
P18 · Multiple choice
P19 · True or false
11. Summary
- Concepts: comparing by case; the 2×2 table and Fisher's exact test; the p-value and how to read it; power; multiple comparisons; a model change is a change that needs testing.
- Skills: comparing two configurations; measuring power; rerunning the labelled cases.
- Pitfalls: treating a large p as safe; looking only at the overall rate; the same seed; forgetting false regressions when there are many cases.
- You can now: decide whether a prompt or model change makes any case worse, with a level of certainty you can state.
12. References
| ID | Title | Publisher | URL | Accessed | Relevance |
|---|---|---|---|---|---|
| R1 | scipy.stats.fisher_exact (SciPy v1.18.0 Manual) | SciPy | https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.fisher_exact.html | 2026-10-31 | The null hypothesis of Fisher's exact test for a 2×2 table |
| R2 | Model deprecations | Anthropic | https://platform.claude.com/docs/en/about-claude/model-deprecations | 2026-10-31 | Testing with the new model before the retirement date |
Key terms (English ↔ Vietnamese)
| English | Tiếng Việt |
|---|---|
| Regression | Thay đổi làm kết quả tệ đi |
| p-value | Xác suất thấy chênh lệch như vậy hoặc lớn hơn, nếu hai phiên bản thật sự như nhau |
| Null hypothesis | Giả thuyết không (hai phiên bản như nhau) |
| Statistical power | Khả năng phát hiện một thay đổi có thật |
| Multiple comparisons | So sánh nhiều case cùng lúc |
| Significance level (α) | Ngưỡng ý nghĩa |