Sub topic 15
Regression Tests and Production Monitoring
This chapter closes the tutorial. You already have retrieval metrics, claim-level faithfulness scoring, a validated judge, and confidence intervals. Here you turn them into two habits: a regression test that runs before every change ships, and monitoring that runs after it ships.
It assumes you have read the earlier chapters, can read Python, and know what a per-question score and a bootstrap interval are.
Why one evaluation run is not enough
A RAG system changes constantly. Someone edits the prompt, the embedding model is upgraded, the chunk size changes, the corpus is re-ingested, or the generator provider ships a new model version. Any of these can quietly move retrieval quality or faithfulness.
A single evaluation tells you where you are today. A regression test tells you whether a specific change made things worse. Monitoring tells you whether the live system is still behaving like the one you tested.
The two need different tools because they see different data:
- Regression tests use a fixed, labelled dataset. You have relevance labels, so you can compute precision@k, recall@k, and nDCG.
- Production monitoring sees real, unlabelled traffic. You rely on judge-based scores, cheap deterministic checks, and user signals.
Building a regression suite
Freeze everything except the change
A regression comparison is only meaningful if the two runs differ in one thing. Record and pin the following for both the baseline and the candidate:
- The corpus snapshot and the index built from it
- The embedding model, chunking settings, and
k - The prompt template and generator model version
- Generator settings such as temperature
- The judge model and judge prompt
If the judge changes between runs, a score difference may come from the judge, not from your system. Treat the judge as part of the test fixture, and re-validate it against human labels (see the chapter on judge validation) whenever you change it.
Layer the suite by cost
A full run with claim extraction and a judge call per claim is slow and costs money. Use tiers:
| Tier | Contents | Runs when | What it catches |
|---|---|---|---|
| Smoke | 20 to 50 questions, retrieval metrics only | Every commit | Broken pipelines, empty retrievals, wrong index |
| Full | The whole labelled set, all metrics | Before merge or release | Real quality shifts |
| Adversarial | Unanswerable, ambiguous, and out-of-date questions | Before release | Hallucination when context is missing |
Include questions whose correct answer is "the documents do not say." A system that always produces a confident answer can score well on every answerable question and still fail these.
Grow the set from failures
Every production failure that a human reviews should become a test case, with its relevance labels. This keeps the suite aligned with real usage and prevents the same bug from returning. Keep the original questions too, so you can see long-term trends.
Deciding whether a change is a regression
Comparing two means with no uncertainty leads to two errors. You block good changes because of noise, or you ship bad ones because the drop looked small. Use a paired comparison instead. Both systems answer the same questions, so you can take the per-question difference and bootstrap that.
import random
def paired_bootstrap_delta(baseline, candidate, n_resamples=2000, alpha=0.05, seed=0):
"""Mean change (candidate - baseline) with a percentile bootstrap interval."""
if len(baseline) != len(candidate) or not baseline:
raise ValueError("need equal-length, non-empty score lists")
diffs = [c - b for b, c in zip(baseline, candidate)]
n = len(diffs)
rng = random.Random(seed)
means = sorted(
sum(diffs[rng.randrange(n)] for _ in range(n)) / n
for _ in range(n_resamples)
)
lo = means[int((alpha / 2) * n_resamples)]
hi = means[int((1 - alpha / 2) * n_resamples) - 1]
return sum(diffs) / n, lo, hi
def gate(baseline, candidate, tolerance=0.02):
delta, lo, hi = paired_bootstrap_delta(baseline, candidate)
if hi < 0:
verdict = "fail" # the whole interval is below zero: a real drop
elif lo < -tolerance:
verdict = "warn" # a drop larger than the tolerance cannot be ruled out
else:
verdict = "pass"
return verdict, delta, lo, hi
baseline = [1.0, 0.5, 1.0, 0.0, 1.0, 0.75, 1.0, 0.5]
candidate = [1.0, 0.5, 0.5, 0.0, 0.75, 0.5, 1.0, 0.5]
print(gate(baseline, candidate)) # mean change is -0.125The gate has three outcomes on purpose. A fail means the data shows a drop. A warn means the evaluation set is too small to be sure, and someone should look at the per-question differences. With eight questions you will mostly get warn, which is the honest answer. The fix is more questions, not a looser threshold.
Paired comparison is tighter than comparing two separate intervals. Hard questions are hard for both systems, so subtracting per question removes that shared variation.
Gate on more than one number
Set a rule per metric, and make some of them hard floors:
- Retrieval: no significant drop in recall@k or nDCG@k.
- Faithfulness: no significant drop, and an absolute floor on the share of answers with at least one unsupported claim.
- Unanswerable questions: the refusal rate on them must not fall.
- Cost and latency: a budget, because a change that improves recall by retrieving twice as many chunks may break both.
Common failure modes of regression suites
- Overfitting to the golden set. If you tune prompts against the same questions you gate on, the scores rise without real improvement. Keep a held-out slice that nobody tunes against.
- Non-determinism. Generator and judge outputs vary even at low temperature. Run flaky comparisons more than once, or fix seeds where the provider supports them. A gate that fails at random trains people to ignore it.
- Stale labels. When the corpus changes, a document labelled relevant may be gone or rewritten. Re-check labels for any question whose relevant documents were modified.
- Averages hiding slices. A flat mean can hide a drop on one document type or one question category. Report metrics per slice for the categories you care about.
Monitoring in production
Production has no relevance labels, so you measure proxies. Group them by where in the pipeline they look.
| Signal | Stage | How it is computed | What a shift suggests |
|---|---|---|---|
| Share of queries with empty or low-score retrieval | Retriever | Threshold on top-1 similarity | Queries outside the corpus, or index problems |
| Distribution of top-1 similarity scores | Retriever | Compare weekly histograms | Embedding drift, corpus change |
| Judge-scored faithfulness on a sample | Generator | Claim extraction and verifier | Prompt or model change, noisy context |
| Judge-scored context relevance on a sample | Retriever | Judge, no labels needed | Retrieval degrading |
| Citation validity rate | Generator | Deterministic check that cited IDs exist in the retrieved set | Formatting or prompting bugs |
| Refusal rate | Generator | Pattern or classifier | Too cautious or too permissive |
| Thumbs-down and escalation rate | Whole system | User feedback | Real dissatisfaction, but biased and sparse |
You cannot run a judge on every request without a large bill, so sample. Sample uniformly for an unbiased estimate, and add a second, targeted sample (for example, low retrieval scores or thumbs-down) to find failures worth adding to the regression suite.
Judge-scored metrics on a sample are noisy, so alert on an interval rather than a point. The Wilson interval works well for rates, including small samples.
import math
def wilson_interval(failures, n, z=1.96):
"""95% Wilson interval for a failure rate. Returns None if n == 0."""
if n == 0:
return None
p = failures / n
denom = 1 + z**2 / n
center = (p + z**2 / (2 * n)) / denom
half = z * math.sqrt(p * (1 - p) / n + z**2 / (4 * n**2)) / denom
return center - half, center + half
def should_alert(failures, n, budget=0.10):
interval = wilson_interval(failures, n)
if interval is None:
return False
lo, _ = interval
return lo > budget # the failure rate is credibly above the budget
print(should_alert(failures=6, n=40)) # 15% observed: interval still includes 10%
print(should_alert(failures=30, n=100)) # 30% observed: credibly above 10%This alerts only when the lower end of the interval exceeds the budget, which avoids pages from a handful of unlucky samples. The cost is slower detection of small increases. If that is too slow, raise the sample size.
Drift has more than one cause
When a monitored metric moves, the cause is usually one of these:
- The query mix changed. Users ask about a new product or in a different style.
- The corpus changed. Documents were added, removed, or re-chunked.
- A dependency changed. The provider updated a model behind a stable name.
- Your judge changed. The same caveat applies in production as in testing.
Log the version identifiers from the freeze list on every request. Without them you cannot separate these causes after the fact.
The important arrow is the one from human review back into the suite. Monitoring finds problems, and the regression suite makes sure they stay fixed.
Summary of working rules
- Pin every component, including the judge, and change one thing per comparison.
- Compare candidate and baseline per question, and decide with an interval.
- Choose blocking metrics ahead of time, and hold out data from tuning.
- Monitor retrieval and generation signals separately so an alert points at a component.
- Feed reviewed production failures back into the labelled set.
Exercise
Your team upgrades the embedding model. The full regression run shows mean recall@5 rising by 0.03, but mean faithfulness falling by 0.04, with a paired bootstrap interval of [-0.09, +0.01]. What does your gate decide, and what do you do next?
Show answer
The faithfulness interval includes zero, so the drop is not statistically established, but it is large enough that a meaningful drop cannot be ruled out. The gate should return warn, not pass or fail. Next, look at the per-question differences for faithfulness, check whether the drops cluster in one slice or question type, and read a few affected answers and their retrieved context. A new embedding model may retrieve different but still relevant passages, which can change what the generator says. If the evaluation set is small, add more questions and rerun before deciding.
Exercise
In production you judge 50 sampled answers per day and find 7 with unsupported claims. Your budget is 10% of answers. Should this page someone? Why or why not?
Show answer
Probably not. The observed rate is 14%, but with n = 50 the 95% Wilson interval for 7 failures is roughly 7% to 26%, which includes the 10% budget. The lower bound is below the budget, so the alert rule does not fire. Watch the trend, pool several days of samples, or increase the sample size to tell a real shift from noise.