Sub topic 13
Regression Tests and Evaluation in CI
A regression is a change that makes something that used to work stop working. In ordinary software, a unit test catches it. In an LLM application, the code can stay the same while a prompt edit, a model upgrade, or a retrieval setting change shifts behavior. This chapter shows how to run your evaluation harness automatically on every change and block changes that make quality worse.
It assumes you have a harness like the one in the earlier chapter, with per-case scores. It also assumes you know basic Python, the idea of a bootstrap confidence interval, and how a CI system such as GitHub Actions runs jobs.
What counts as a change worth testing
Anything that can alter outputs should trigger an evaluation:
- Prompt templates and system messages.
- The model name or version, and sampling parameters.
- Retrieval settings such as chunk size, index contents, and top-k.
- Tool definitions and the code that parses model output.
- The judge prompt or judge model, when you use an LLM judge.
Version these items in the repository, so a diff shows what changed. A model name like latest is a hidden change you cannot review, so pin an explicit version where the provider allows it.
Tiers: what runs when
A full evaluation can take many minutes and cost real money. Running it on every commit teaches the team to ignore it. Split the work into tiers.
| Tier | Trigger | Contents | Purpose |
|---|---|---|---|
| Smoke | Every pull request | 20 to 50 cases, mostly deterministic checks | Catch broken formatting, crashes, and obvious failures quickly |
| Full | Merge to main, or on PRs that touch prompts or models | Whole dataset, judge scoring, repeated runs | Decide whether quality changed |
| Scheduled | Nightly or weekly | Full dataset plus extra slices | Detect drift from provider-side model changes |
Put the cheap programmatic checks (schema validity, required fields, length limits) in the smoke tier. They fail fast and cost nothing. Reserve judge calls and repeated sampling for the full tier.
Baselines
A regression test needs something to regress from. The baseline is the per-case result of a known-good version, stored as a file in the repository or in an artifact store. Store per-case scores, not only the overall pass rate. Per-case data lets you pair the two runs, so you compare the same question under both versions.
Pairing matters because cases vary in difficulty. If both versions fail the same hard cases, that shared variance cancels out in the paired difference, and the interval around it gets narrower. An unpaired comparison of two pass rates has to absorb all of that variance, so it needs a larger gap before it can claim a difference.
Update the baseline deliberately. When a pull request improves quality, a reviewer commits the new baseline file as part of the change. If the pipeline updates the baseline automatically after every merge, slow degradation never trips the gate, because each step is compared only with the previous one.
Setting gate rules
A gate turns scores into a pass or fail decision. Three rules cover most needs.
- Absolute floor. The candidate pass rate must stay above a fixed minimum, for example 0.80, whatever the baseline says.
- Critical cases. Some cases must never fail, such as a refusal that protects users or a format that downstream code depends on. List them by ID.
- Statistical regression. Block when the confidence interval for the paired difference lies entirely below zero. This means the candidate is credibly worse, not just unlucky.
The third rule is deliberately lenient. With 40 cases the interval is wide, so only large drops will be flagged. If your product cannot tolerate a drop of two points, you need a larger dataset, more repeated runs, or a stricter margin, and each of those costs more. Pick the margin by deciding what loss you are willing to ship, then size the dataset to detect it.
The script below implements these rules. It reads two JSON files that map case IDs to 0 or 1 scores, and it exits with a nonzero status when the gate fails, which is what makes a CI job turn red.
import json
import random
import sys
def paired_bootstrap_diff(base, cand, n_resamples=2000, alpha=0.05, seed=0):
"""Return (mean difference, lower bound, upper bound) for cand - base."""
rng = random.Random(seed)
diffs = [c - b for b, c in zip(base, cand)]
n = len(diffs)
means = sorted(
sum(rng.choices(diffs, k=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, floor=0.80, critical_ids=()):
reasons = []
if set(baseline) != set(candidate):
reasons.append("case sets differ; regenerate the baseline for this dataset version")
return False, reasons
ids = sorted(baseline)
base = [baseline[i] for i in ids]
cand = [candidate[i] for i in ids]
rate = sum(cand) / len(cand)
if rate < floor:
reasons.append(f"pass rate {rate:.3f} is below floor {floor:.2f}")
for cid in critical_ids:
if candidate.get(cid) != 1:
reasons.append(f"critical case failed: {cid}")
mean_diff, lo, hi = paired_bootstrap_diff(base, cand)
if hi < 0:
reasons.append(
f"credible regression: diff {mean_diff:+.3f}, 95% CI [{lo:+.3f}, {hi:+.3f}]"
)
return not reasons, reasons
def load_scores(path):
with open(path) as f:
return json.load(f)
if __name__ == "__main__":
baseline = load_scores(sys.argv[1])
candidate = load_scores(sys.argv[2])
critical = sys.argv[3:]
ok, reasons = gate(baseline, candidate, critical_ids=critical)
for reason in reasons:
print("FAIL:", reason)
print("gate passed" if ok else "gate failed")
sys.exit(0 if ok else 1)The check that both files cover the same cases is intentional. If someone edits the dataset, old and new scores are no longer comparable, and the gate should force a new baseline instead of comparing mismatched runs.
Wiring it into CI
The workflow below runs the smoke suite on pull requests and a scheduled run each night. The file run_eval_cli.py is a placeholder for your own entry point. It should call your harness and write the {case_id: 0 or 1} JSON file.
name: llm-eval
on:
pull_request:
schedule:
- cron: "0 3 * * *"
jobs:
eval:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- name: Run evaluation
run: python run_eval_cli.py --suite smoke --out candidate.json
env:
LLM_API_KEY: ${{ secrets.LLM_API_KEY }}
- name: Gate against baseline
run: python gate.py baseline.json candidate.json
- uses: actions/upload-artifact@v4
if: always()
with:
name: eval-results
path: candidate.jsonUploading results with if: always() keeps the per-case output available when the gate fails, so the reviewer can open the failing cases instead of rerunning the job.
Making runs stable enough to gate on
A gate that fails randomly gets disabled. Reduce noise before you tighten thresholds.
- Set temperature to 0, but do not trust it. Many providers still return slightly different outputs for identical requests. Treat any single run as one sample.
- Repeat the run. Run each case two or three times and score the mean, or require a majority. This costs more but narrows the interval.
- Pin the judge. A changed judge model or prompt shifts every score. Store the judge version beside the baseline and treat a change as a baseline reset.
- Cache with care. Caching model responses keyed by the full request makes reruns of unchanged code free and exact. Include the prompt, model, and parameters in the key, or a stale cache will hide a regression.
- Handle API failures separately. A timeout is not a wrong answer. Retry, then report errored cases in their own count, so an outage does not look like a quality drop.
- Quarantine flaky cases. If a case flips between runs with no change in the code, move it to a tracked list and fix its expected output or criteria. Do not delete it silently.
Reading a failure
When the gate fails, start with the per-case difference between baseline and candidate. List the cases that went from pass to fail and the ones that went from fail to pass. A net drop of two points can hide ten new failures and eight fixes, and those ten are where the cause is. Group them by the slices you defined in your dataset, such as topic or input length. If a single slice accounts for the drop, the change probably affected one behavior, and the error analysis steps from the previous chapter apply directly.
Common mistakes
- Gating on a single pass rate with no interval, so noise blocks good changes or lets bad ones through.
- Letting the dataset change without resetting the baseline.
- Running the full suite on every commit until the team bypasses it.
- Treating the nightly drift job as optional. Provider model updates are the one change your pull requests never show.
- Tuning prompts against the same cases the gate uses, so the gate measures memorization. Keep a held-out set that prompt authors do not see.
Exercise
Your gate compares a candidate to a baseline on 40 cases. The candidate pass rate is 0.85 against 0.90 for the baseline, and the paired bootstrap interval for the difference is [-0.15, +0.05]. Your gate blocks only when the upper bound is below zero. Does it block? Name two ways to make the gate able to detect a drop of this size.
Show answer
It does not block, because the upper bound (+0.05) is above zero, so the data are consistent with no change or a small gain. The interval is wide because 40 cases give little precision. To detect a five-point drop you can add more cases, repeat each case several times and average the scores, or reduce variance with deterministic scoring where possible. You can also decide that a lower bound beyond an agreed margin, such as -0.05, should trigger a human review instead of a hard block.
Exercise
A teammate proposes updating baseline.json automatically after every merge to main, so the baseline is always current. What failure does this allow?
Show answer
Gradual degradation. Each merge is compared only with the one before it, so a series of small drops, each within noise, never trips the gate, yet the total quality loss can be large. Updating the baseline through a reviewed commit keeps a fixed reference point and makes each quality change a visible decision.