Evaluation-Driven Development
Build an offline evaluation harness for language systems: versioned task suites, traces, slice scores, and regression gates that block hidden drops.
Language AI HandbookAll chapters Evaluation-Driven Development
A support assistant answers a refund question correctly after you edit its prompt. Before you ship, you want to see whether the same change drops the receipt requirement, breaks Spanish answers, or leaves the original retrieval fault untouched. A saved task suite lets you repeat the comparison. A trace helps you decide which step to investigate.
This chapter builds an offline evaluation harness for a fictional support assistant. It compares two configurations on matched cases, records intermediate events, and blocks a regression that the aggregate score misses. The six tasks are teaching fixtures. Use independent data to support claims about production behavior.
From Benchmark Theater to Evidence
A dashboard score can be reproducible and still answer the wrong question. Decide what the result should allow you to do before choosing a score. To approve a prompt edit, you need evidence about what changed on representative tasks, where failures appeared, and which cases the team must protect.
- Choose tasks and specify what counts as successful behavior.
- Run the system and record the intermediate events needed for diagnosis.
- Report scores by slice and inspect representative failures.
- Apply a predeclared regression gate and separately confirm the result on held-out tasks when needed.
CheckList is one example of bringing behavioral software tests to language models. It helps designers specify capabilities and observable behaviors to test. Ribeiro et al. (2020)
Why a task suite, not a checklist
A task suite is a set of executable, recorded cases. Each case includes the request and any context, an expected behavior, a grading policy, and metadata for comparing groups. Preserve the suite version and grading configuration alongside the system configuration. This tells a reviewer which cases and rules produced the results.
A language or task tag lets you group cases that may respond differently to a change. Decide which groups need protection before looking at the candidate score.
Anatomy of a Task Suite
The example uses invented support questions and an in-memory retrieval fixture. A toy answer may be a copied sentence or a scripted alteration. Neither retrieval nor generation calls an external service.
The case data model
The grader searches for required and forbidden substrings after lowercasing. It grants partial credit for some required matches and vetoes answers containing a forbidden substring. The labels are substrings that stand in for facts. This intentionally simple grader cannot assess meaning.
PythonIn [3]Expand
import math
from dataclasses import asdict, dataclass, field
@dataclass
class Case:
case_id: str
question: str
must_include: list[str] = field(default_factory=list)
must_exclude: list[str] = field(default_factory=list)
slice: str = "general"
provenance: str = "handwritten"
def score(self, answer: str) -> float:
"""Fraction of required matches, with a forbidden-substring veto."""
low = answer.lower()
if any(bad.lower() in low for bad in self.must_exclude):
return 0.0
if not self.must_include:
return 1.0
hits = sum(good.lower() in low for good in self.must_include)
return hits / len(self.must_include)ConsoleOut [4]Expand
1.0 0.0
The first answer scores 1 because both required substrings appear and the forbidden one is absent. The second scores 0 because the forbidden substring appears. The veto expresses this fixture's decision to give the forbidden phrase precedence.
With two required substrings and one match, the score is 0.5. The report keeps the mean graded score and the binary full-credit count as separate measures. The analytical Bernoulli formula below concerns a mean of binary outcomes. The later descriptive bootstrap resamples differences in the graded scores.
The grading method is the function mapping a system output to a score. It can be exact-match, substring/fact-presence (as here), a rubric applied by an LLM judge (see LLM-as-Judge), or a programmatic check. Every grading method is an operationalization of "correct" with known failure modes; choosing one is choosing which errors you can see.
Assembling a small suite
The six invented cases have two items each in billing, technical help, and multilingual support. This teaching lab uses a single, disjoint slice label per case. A production case can carry several tags, such as both billing and Spanish.
PythonIn [5]Expand
SUITE = [
Case(
"c001",
"How long is the refund window?",
["30 days", "original"],
["60 days"],
"billing",
),
Case(
"c002",
"Can I get a refund after 45 days?",
["no.", "30 days"],
["60 days"],
"billing",
),
Case(
"c003",
"Reset password steps?",
["settings", "email", "link"],
[],
"technical",
),
Case(
"c004",
"App crashes on upload. What do I do?",
["logs", "version"],
["guaranteed"],
"technical",
),
Case(
"c005",
"¿Cuál es el plazo de reembolso?",
["30 días"],
["60 días"],
"multilingual",
),
Case(
"c006",
"Wie setze ich mein Passwort zurück?",
["Einstellungen", "E-Mail"],
[],
"multilingual",
),
]ConsoleOut [6]Expand
Total cases: 6
Per-slice counts: {'billing': 2, 'technical': 2, 'multilingual': 2}One changed outcome moves the pass rate in a two-case slice by 50 percentage points. Inspect the count next to each score before reading a small slice as a reliable estimate of a population.
Versioning the suite
Hash the serialized case records so the report can detect changed case inputs or labels. Store the scorer's release and configuration separately, since case bytes cannot identify changes to the scorer's implementation. Digests help detect changed bytes. NIST Secure Hash Standard
PythonIn [7]Expand
import hashlib
import json
def suite_hash(cases: list[Case]) -> str:
payload = [asdict(case) for case in cases]
blob = json.dumps(payload, sort_keys=True).encode("utf-8")
return hashlib.sha256(blob).hexdigest()ConsoleOut [8]Expand
Suite version: faf2c1e1350c0da74114a78bdd91e70b3f478416164a13ed8dd168142c2fa188
This digest binds all case fields and their order under the chosen encoding. Case order is part of this version. Matching digests support comparing the case inputs. The run must also hold the grading policy fixed.
Splits, Holdouts, and the Contamination Boundary
A case used to choose the prompt has become development evidence. Subsequent performance on that case measures behavior on a known example. Adaptive reuse can overfit a holdout even when tuners see only aggregate feedback. Dwork et al. (2015)
Keep cases for development and reserve separate cases to confirm changes. A known failure can also become a regression test once resolved. Regression cases deliberately remain known and protect behavior you have already fixed. In a real split, keep duplicates, paraphrases, and examples from the same underlying customer issue in one partition when they would otherwise leak across it.
PythonIn [9]Expand
import random
def split_suite(cases: list[Case], holdout_frac=0.34, seed=7):
if len(cases) < 2 or not 0 < holdout_frac < 1:
raise ValueError(
"Need at least two cases and a fraction strictly between 0 and 1."
)
rng = random.Random(seed)
shuffled = cases[:]
rng.shuffle(shuffled)
n_hold = min(len(shuffled) - 1, max(1, round(len(shuffled) * holdout_frac)))
return {"holdout": shuffled[:n_hold], "dev": shuffled[n_hold:]}PythonIn [10]Expand
splits = split_suite(SUITE)
for name, cases in splits.items():
print(name, "->", [c.case_id for c in cases])ConsoleOut [10]Expand
holdout -> ['c005', 'c001'] dev -> ['c006', 'c004', 'c002', 'c003']
The seeded example gives four dev cases and two holdout cases. Both partitions are visible here so you can inspect the mechanics. This notebook uses dev for tuning examples and makes no generalization claim from the toy holdout.
Inspect the split before treating it as a representative sample. The chart counts how many cases each slice contributes to each partition. The toy holdout contains no technical cases. Protecting technical behavior on this split therefore requires other evidence.
PythonIn [11]Expand
partition_groups = ["billing", "technical", "multilingual"]
partition_counts = {
partition: [
sum(case.slice == group for case in cases) for group in partition_groups
]
for partition, cases in splits.items()
}
partition_rows = list(range(len(partition_groups)))VisualizationOut [12]Expand

Restrict access to holdout cases and detailed outputs during tuning. If you inspect a failure and tune against it, move it into dev or the known regression set. Replace it with fresh confirmation data when you need an independent estimate.
Recording Traces
A trace helps diagnose a scored failure by recording what happened before the answer. A failed run can become a repeatable test once you specify which behavior ought to change. Evaluate agent workflows
This fixture records retrieval and generation as ordered events. Fields store enough detail to inspect the simulated decisions. Log only the necessary, permitted fields in production. Tracing and Observability for AI Systems
PythonIn [13]Expand
@dataclass
class Step:
name: str
payload: dict
@dataclass
class Trace:
case_id: str
steps: list[Step]
answer: str = ""
score: float = 0.0
def add(self, name: str, **payload) -> None:
self.steps.append(Step(name, payload))
def find(self, name: str) -> list[Step]:
return [s for s in self.steps if s.name == name]The simulated retriever selects the first matching keyword. The scripted generator copies the document unless its configuration injects an omission or a wrong duration. There is no language model in this fixture.
PythonIn [14]Expand
KNOWLEDGE = {
"refund": "Refunds are available within 30 days with the original receipt.",
"password": "Go to Settings, then Email, and click the reset link.",
"upload": "Check the app logs and your version number before reporting.",
"reembolso": "Los reembolsos están disponibles dentro de 30 días.",
"passwort": "Gehen Sie zu Einstellungen und dann E-Mail.",
}
def fake_system(question: str, trace: Trace, config: dict) -> str:
# 1. Retrieval: naive keyword match
doc = ""
for key, text in KNOWLEDGE.items():
if key in question.lower():
if not (key == "upload" and config.get("retrieval_miss")):
doc = text
break
trace.add("retrieve", doc=doc, found=bool(doc))
# 2. Generation: stand-in that may drop or add facts per config
if not doc:
ans = "I don't have information on that."
else:
ans = doc
if question == "Can I get a refund after 45 days?":
ans = "No. " + ans
if config.get("drop_receipt_hint") and "receipt" in doc:
ans = ans.replace(" with the original receipt", "")
if (
config.get("wrong_window")
and question == "Can I get a refund after 45 days?"
):
ans = ans.replace("30 days", "60 days")
if (
config.get("retrieval_miss")
and question == "App crashes on upload. What do I do?"
):
assert not doc
trace.add("generate", question_chars=len(question), answer=ans)
return ans
def run_case(case: Case, config: dict) -> Trace:
tr = Trace(case.case_id, [])
tr.answer = fake_system(case.question, tr, config)
tr.score = case.score(tr.answer)
return trConsoleOut [15]Expand
answer: Refunds are available within 30 days with the original receipt.
score: 1.0
retrieve -> {'doc': 'Refunds are available within 30 days with the original receipt.', 'found': True}
generate -> {'question_chars': 30, 'answer': 'Refunds are available within 30 days with the original receipt.'}The refund fixture records retrieval of a matching document, a copied answer, and a full score. The next run holds retrieval fixed and changes one generation flag.
A deliberate failure, traced
Let's break the system on purpose and read the trace. We flip drop_receipt_hint, which simulates the generator dropping a required fact.
ConsoleOut [16]Expand
answer: Refunds are available within 30 days. score: 0.5 retrieval found doc: True
Retrieval found the document and the answer lost a required substring. The score falls from 1 to 0.5. This controlled flag isolates the cause in the fixture. In a real system, a trace can suggest a cause that you then test by changing one input or replaying one component.
Scoring, Aggregation, and Slice Ceilings
The case score is between 0 and 1 and can be fractional. The mean case score gives every observed case equal weight. A pass rate uses a different variable: map full credit to one and every other score to zero. Report which measure you computed.
Aggregate scores and their variance
For independent, identically distributed binary outcomes with success probability , the mean pass indicator has variance . Its standard error is the square root of that variance. A fixed set of six hand-authored cases has no random sampling model for production traffic. Report counts and descriptive means on these fixtures. If you need population uncertainty, define the target population, how you sampled it, and what dependence the estimate must account for.
PythonIn [17]Expand
def aggregate(traces: list[Trace]) -> dict:
scores = [trace.score for trace in traces]
if not scores:
raise ValueError("Cannot summarize an empty group.")
return {
"n": len(scores),
"mean": sum(scores) / len(scores),
"passes": sum(score == 1.0 for score in scores),
}
def by_slice(traces: list[Trace], cases: list[Case]) -> dict:
by_id = {case.case_id: case for case in cases}
buckets: dict[str, list[Trace]] = {}
for trace in traces:
buckets.setdefault(by_id[trace.case_id].slice, []).append(trace)
return {name: aggregate(group) for name, group in buckets.items()}PythonIn [18]Expand
dev_cases = splits["dev"]
dev_traces = [run_case(case, {}) for case in dev_cases]
print("Development cases:", aggregate(dev_traces))
for group, stats in by_slice(dev_traces, dev_cases).items():
print(group, stats)ConsoleOut [18]Expand
Development cases: {'n': 4, 'mean': 1.0, 'passes': 4}
multilingual {'n': 1, 'mean': 1.0, 'passes': 1}
technical {'n': 2, 'mean': 1.0, 'passes': 2}
billing {'n': 1, 'mean': 1.0, 'passes': 1}The slice ceiling
With disjoint slices the overall mean is a weighted average. Let be the case count in slice , its observed mean score, and the total case count. The aggregate weights each slice by its share .
The weights are nonnegative and sum to one. This places the aggregate between the smallest and largest slice means. If a slice of weight stays at while all scores lie in , the aggregate ceiling is , since even perfect performance elsewhere contributes at most . The ceiling depends on the mix.
Keep the underlying slice rates fixed in this synthetic example. With equal representation, the expected mean is . When billing accounts for 30 of 40 cases, the expected mean is . This increase comes entirely from reweighting unchanged slice rates.
PythonIn [19]Expand
rates = {"Billing": 1.0, "Technical": 0.5, "Multilingual": 0.0}
mixes = {
"Balanced mix": {"Billing": 10, "Technical": 10, "Multilingual": 10},
"Billing-heavy mix": {"Billing": 30, "Technical": 5, "Multilingual": 5},
}
expected = {
label: sum(rates[s] * count for s, count in counts.items())
/ sum(counts.values())
for label, counts in mixes.items()
}
plot_labels = [*rates, "Balanced mix", "Billing-heavy mix"]
plot_rates = [*rates.values(), *expected.values()]VisualizationOut [20]Expand

Compare releases on the same cases when possible. If the sample mix must change, show the slice values and estimate a weighted aggregate against a declared reference mix. Fixing weights alone cannot correct for a shift in difficulty within a slice.
Error Taxonomy
Use a small set of labels to describe evidence recorded in this harness. A missing document is a retrieval miss. A forbidden output substring is a veto. A partial result with a retrieved document indicates missing required text in this fixture. A separate unknown label covers absent retrieval instrumentation. A label identifies a next step for investigation.
PythonIn [21]Expand
def classify(trace: Trace, case: Case) -> str:
if trace.score == 1.0:
return "pass"
retrieval = trace.find("retrieve")
if not retrieval:
return "unclassified"
if not retrieval[0].payload["found"]:
return "retrieval_miss"
if any(bad.lower() in trace.answer.lower() for bad in case.must_exclude):
return "forbidden_text"
return "missing_required_text"PythonIn [22]Expand
from collections import Counter
by_id = {case.case_id: case for case in SUITE}
labels = [classify(trace, by_id[trace.case_id]) for trace in dev_traces]
print("Dev taxonomy:", dict(Counter(labels)))ConsoleOut [22]Expand
Dev taxonomy: {'pass': 4}The baseline fixture passes its dev cases. Now change generation settings and configure one missing retrieval. These synthetic failures exercise the separate labels.
PythonIn [23]Expand
broken_config = {
"drop_receipt_hint": True,
"wrong_window": True,
"retrieval_miss": True,
}
broken = [run_case(case, broken_config) for case in SUITE]
for trace in broken:
label = classify(trace, by_id[trace.case_id])
if label != "pass":
print(trace.case_id, label, repr(trace.answer))ConsoleOut [23]Expand
c001 missing_required_text 'Refunds are available within 30 days.' c002 forbidden_text 'No. Refunds are available within 60 days.' c004 retrieval_miss "I don't have information on that."
Compare label counts on the same six cases. The first taxonomy above covers development cases only. Both runs here include the two holdout fixtures for illustration. The shared denominator isolates the configuration change in this fixture.
PythonIn [24]Expand
full_baseline = [run_case(case, {}) for case in SUITE]
for name, traces in (("baseline", full_baseline), ("broken", broken)):
full_counts = Counter(
classify(trace, by_id[trace.case_id]) for trace in traces
)
print(name, dict(full_counts))ConsoleOut [24]Expand
baseline {'pass': 6}
broken {'missing_required_text': 1, 'forbidden_text': 1, 'pass': 3, 'retrieval_miss': 1}The three seeded failures exercise three distinct rules. A missing retrieval points to the retriever. Forbidden or missing answer text triggers a check of both the retrieved material and the generation trace. A field called found only establishes that a document was found. It does not establish its relevance or correctness.
Choose labels that point to distinct investigations. Keep enough evidence to revisit a diagnosis and allow multiple contributing failures where your system needs them.
Regression Gates
This fixture's gate checks an overall tolerance, a tolerance for every observed slice, and any previously full-credit case that loses credit. The tolerance checks treat differences within of the configured threshold as equal to it, to accommodate floating-point arithmetic on the mean scores. The tolerances are release-policy inputs. A release can be valuable for latency or cost while quality stays within declared bounds.
The gate first pairs traces by case id. It rejects duplicate, missing, extra, or empty case sets. This prevents a reordered run or omitted hard case from changing which outcomes are compared.
PythonIn [25]Expand
@dataclass
class GateResult:
passed: bool
reasons: list[str]
def paired_cases(baseline, candidate, cases):
expected = {case.case_id for case in cases}
left = {trace.case_id: trace for trace in baseline}
right = {trace.case_id: trace for trace in candidate}
if not expected or (
len(expected) != len(cases)
or len(left) != len(baseline)
or len(right) != len(candidate)
or set(left) != expected
or set(right) != expected
):
raise ValueError("Both runs need exactly one outcome for every case.")
return [(left[case.case_id], right[case.case_id]) for case in cases]
def exceeds_tolerance(drop, tolerance):
return drop > tolerance and not math.isclose(
drop, tolerance, rel_tol=0.0, abs_tol=1e-12
)
def regression_gate(baseline, candidate, cases, agg_tol=0.02, slice_tol=0.10):
try:
pairs = paired_cases(baseline, candidate, cases)
except ValueError as err:
return GateResult(False, [str(err)])
reasons = []
overall_drop = aggregate(baseline)["mean"] - aggregate(candidate)["mean"]
if exceeds_tolerance(overall_drop, agg_tol):
reasons.append(f"Aggregate fell {overall_drop:.3f}")
base_slices = by_slice(baseline, cases)
trial_slices = by_slice(candidate, cases)
for name, stats in base_slices.items():
drop = stats["mean"] - trial_slices[name]["mean"]
if exceeds_tolerance(drop, slice_tol):
reasons.append(f"Slice {name!r} fell {drop:.3f}")
for old, new in pairs:
if old.score == 1.0 and new.score < 1.0:
reasons.append(f"Regression on case {new.case_id}")
return GateResult(not reasons, reasons)PythonIn [26]Expand
candidate_dev = [run_case(case, broken_config) for case in dev_cases]
result = regression_gate(dev_traces, candidate_dev, dev_cases)
print("Gate passed:", result.passed)
for r in result.reasons:
print(" -", r)ConsoleOut [26]Expand
Gate passed: False - Aggregate fell 0.500 - Slice 'technical' fell 0.500 - Slice 'billing' fell 1.000 - Regression on case c004 - Regression on case c002
The status and reasons give a reviewer the aggregate, slice, and individual failures that triggered this policy. The gate compares the development instances of the fixtures. It does not substitute for independent confirmation.
Give the gate a policy owner who can choose and revisit the tolerances as the suite grows. A zero tolerance can block changes on measurement noise, increasing the pressure to disable the gate. A large tolerance can admit degradations the team cares about. Set tolerances for the amount of change the product can accept, and measure uncertainty separately.
Try two changes to the same candidate log. Reordering its records leaves the gate unchanged because the join selects matches by id. Removing a record returns an alignment error before the gate computes a mean.
PythonIn [27]Expand
reordered = regression_gate(
dev_traces, list(reversed(candidate_dev)), dev_cases
)
incomplete = regression_gate(dev_traces, candidate_dev[:-1], dev_cases)
assert reordered == result
assert not exceeds_tolerance(0.92 - 0.90, 0.02)
assert not exceeds_tolerance(0.40 - 0.30, 0.10)
assert exceeds_tolerance(0.92 - 0.89, 0.02)
print("Reordered run:", reordered.passed)
print("Incomplete run:", incomplete.reasons)ConsoleOut [27]Expand
Reordered run: False Incomplete run: ['Both runs need exactly one outcome for every case.']
These checks protect the denominator. If an evaluator silently skips an expensive tool case, a naive overall mean may improve because that case is absent. Treat skip reasons and unavailable outcomes as part of the measurement design. Decide in advance whether each kind of missing result is a scored failure, a separate availability metric, or a reason to reject the comparison. This fixture rejects the comparison.
Gates and paired comparisons
For paired comparisons compute candidate minus baseline for each shared case. Pairing fixes the cases used by both configurations. To isolate a component's effect, hold the scorer and other configuration fixed as well. If the case pairs are sampled independently from a target population, a paired bootstrap resamples whole pairs with replacement. Here the bootstrap describes variation under resampling the small observed fixture. Do not treat its quantiles as reliable population uncertainty.
PythonIn [28]Expand
def paired_bootstrap(baseline, candidate, cases, n_boot=2000, seed=0):
pairs = paired_cases(baseline, candidate, cases)
differences = [new.score - old.score for old, new in pairs]
rng = random.Random(seed)
means = sorted(
sum(rng.choices(differences, k=len(differences))) / len(differences)
for _ in range(n_boot)
)
return means[int(0.025 * n_boot)], means[int(0.975 * n_boot)]ConsoleOut [29]Expand
Toy paired resampling quantiles: [-1.000, 0.000]
For this fixture there are two changes of and two zeros. Each draw in a bootstrap resample has probability one half of selecting one of the two losses. For four independent draws with replacement, the expected distribution of means can be computed exactly. At every possible mean below, the height is the probability of that resampled mean. The zero at the right occurs if all four draws select unchanged cases.
PythonIn [30]Expand
loss_counts = list(range(5))
bootstrap_means = [-losses / 4 for losses in loss_counts]
bootstrap_masses = [math.comb(4, losses) / 16 for losses in loss_counts]
assert math.isclose(sum(bootstrap_masses), 1.0)VisualizationOut [31]Expand

The resampling estimate is separate from the deterministic gate. Even if a pair of quantiles brackets zero, the fixture's protected-case policy still blocks an observed loss of full credit. An inconclusive population comparison and an observed break in a specific fixture can coexist.
A Worked Loop: Diagnosing a "Net Improvement"
Use a second synthetic comparison to see how an aggregate threshold can miss a protected slice regression.
These traces have explicit fixture scores. The candidate improves the technical and multilingual means while reducing the billing mean.
PythonIn [32]Expand
# Baseline: passes two billing cases and one technical case
def make_trace(case_id, score):
t = Trace(case_id, [])
t.score = score
t.steps.append(Step("retrieve", {"found": True}))
return t
slices_for = {
"c001": "billing",
"c002": "billing",
"c003": "technical",
"c004": "technical",
"c005": "multilingual",
"c006": "multilingual",
}
baseline = [
make_trace("c001", 1.0),
make_trace("c002", 1.0),
make_trace("c003", 1.0),
make_trace("c004", 0.0),
make_trace("c005", 0.0),
make_trace("c006", 0.0),
]
candidate = [
make_trace("c001", 0.0),
make_trace("c002", 0.0),
make_trace("c003", 1.0),
make_trace("c004", 1.0),
make_trace("c005", 1.0),
make_trace("c006", 0.0),
]
meta = [Case(cid, "", slice=s) for cid, s in slices_for.items()]PythonIn [33]Expand
b = aggregate(baseline)
c = aggregate(candidate)
print(f"Aggregate baseline={b['mean']:.3f} candidate={c['mean']:.3f}")
print("By slice (baseline -> candidate):")
bs, cs = by_slice(baseline, meta), by_slice(candidate, meta)
for s in bs:
print(
f" {s:14s} {bs[s]['mean']:.2f} -> {cs.get(s, {'mean': 0})['mean']:.2f}"
)ConsoleOut [33]Expand
Aggregate baseline=0.500 candidate=0.500 By slice (baseline -> candidate): billing 1.00 -> 0.00 technical 0.50 -> 1.00 multilingual 0.00 -> 0.50
Both aggregates equal 0.50. Billing falls from 1 to 0 while technical and multilingual each gain 0.50. An aggregate-only threshold sees no change.
ConsoleOut [34]Expand
Gate passed: False - Slice 'billing' fell 1.000 - Regression on case c001 - Regression on case c002
The point pairs below show which direction each slice moved. The thin connectors pair the two measurements for a slice without combining the cases across slices. The aggregate appears as a fourth row so you can see where the change vanishes.
PythonIn [35]Expand
worked_groups = ["Overall", "Billing", "Technical", "Multilingual"]
baseline_rates = [
b["mean"],
*(bs[group.lower()]["mean"] for group in worked_groups[1:]),
]
candidate_rates = [
c["mean"],
*(cs[group.lower()]["mean"] for group in worked_groups[1:]),
]
worked_rows = list(range(len(worked_groups)))VisualizationOut [36]Expand

The slice gate flags the billing drop and the case gate names c001 and c002. The threshold expresses a policy decision about these cases.
The failed gate identifies billing and names c001 and c002. Start with the recorded answer and trace for each case. Those records tell you which component to inspect next. The gate localizes the observed regressions; the diagnosis comes from checking the evidence.
The protection policy matters as much as the plot. Suppose a team prioritizes an increase in multilingual coverage without reducing billing accuracy. A requirement for zero loss on protected billing fixtures is easy to state once the cases are tagged. A different team might allow a specified loss in an inexpensive low-risk route if latency also drops. Both policies need clear scope and a known baseline. Telling readers which policy was chosen lets them judge the decision from the same table.
A case-wise check can grow too brittle if prompts are stochastic and the only record for a baseline case is one successful sample. For hard requirements, test the observable policy or invariant directly when possible. For a stochastic quality measure use a repeated sampling plan and a predefined aggregate. Keep those results distinct from pinned deterministic fixtures.
Avoiding False Improvements
A scored improvement can come from changes to the measurement setup. Compare identical case sets or explicitly reweight by a stated target distribution. Keep holdout feedback away from adaptive tuning. Pin the grading version and re-score both releases if that version changes. For stochastic systems, predeclare the number of generations per case and summarize their mean success. An at-least-one-success metric answers a different question from mean success per generation.
Judge calibration matters too. Zheng et al. describe position, verbosity, and self-enhancement bias in their work on model judges. Compare model grades to human judgments on relevant outputs and review disagreements. Zheng et al. (2023)
The toy grader can accept a negated assertion containing the required words. Run it on two answers about the same policy.
ConsoleOut [37]Expand
Honest answer scores: 1.0 Negated answer scores: 1.0
Both score 1 because both contain the same required characters. Only one affirms the policy. The fixture measures substring presence. Use task-specific grading tests to catch that gap.
Several issues can occur in the same run. A developer can report tuned cases as if they were independent confirmation, select a noisy winner from many variants, or change the suite's case mix. The negation example has a different cause. Its substring rule fails to measure answer meaning even when the data are kept separate. Pinning evaluation data helps isolate the first set of problems. Testing and calibrating the grader helps reveal the last.
Implementation: Assembling the Harness
The harness stores the suite digest, grader version, configuration, traces, slice scores, and taxonomy counts. The report exposes which evidence produced the gate's decision.
PythonIn [38]Expand
@dataclass
class RunReport:
suite_version: str
grader_version: str
config: dict
traces: list[Trace]
aggregate: dict
slices: dict
taxonomy: dict
def evaluate(cases: list[Case], config: dict) -> RunReport:
traces = [run_case(c, config) for c in cases]
case_map = {c.case_id: c for c in cases}
tax = Counter(classify(t, case_map[t.case_id]) for t in traces)
return RunReport(
suite_version=suite_hash(cases),
grader_version="substring-v1",
config=config.copy(),
traces=traces,
aggregate=aggregate(traces),
slices=by_slice(traces, cases),
taxonomy=dict(tax),
)PythonIn [39]Expand
baseline_report = evaluate(dev_cases, config={})
print("Suite:", baseline_report.suite_version)
print(
"Aggregate:",
{
k: round(v, 2) if isinstance(v, float) else v
for k, v in baseline_report.aggregate.items()
},
)
print("Taxonomy:", baseline_report.taxonomy)ConsoleOut [39]Expand
Suite: b9dd6a7f0439c284f4cdf4ccc8ab9add604ccf4cb22be9c4c683e3355c7cc8d1
Aggregate: {'n': 4, 'mean': 1.0, 'passes': 4}
Taxonomy: {'pass': 4}Now the gate accepts a pair of reports rather than raw traces, so the harness is the single source of truth. We compare a candidate against the stored baseline and print a human-readable verdict fit for a pull request.
PythonIn [40]Expand
def gate_reports(
baseline: RunReport, candidate: RunReport, cases: list[Case], **kw
) -> GateResult:
if (
baseline.suite_version != candidate.suite_version
or baseline.suite_version != suite_hash(cases)
):
return GateResult(False, ["Suite version changed"])
if baseline.grader_version != candidate.grader_version:
return GateResult(False, ["Grader version changed"])
return regression_gate(baseline.traces, candidate.traces, cases, **kw)PythonIn [41]Expand
candidate_report = evaluate(dev_cases, config={"wrong_window": True})
verdict = gate_reports(baseline_report, candidate_report, dev_cases)
print(
"Suite versions match:",
baseline_report.suite_version == candidate_report.suite_version,
)
print("Gate passed:", verdict.passed)
for r in verdict.reasons:
print(" -", r)ConsoleOut [41]Expand
Suite versions match: True Gate passed: False - Aggregate fell 0.250 - Slice 'billing' fell 1.000 - Regression on case c002
The gate first checks the suite version of both reports and the submitted case list. It also checks that the reports used the same grader version. This prevents those differences from being reported as the candidate's effect.
Reading the summary the way a reviewer would
Show the version, aggregate mean, slice means and denominators, taxonomy counts, and the gate result together.
PythonIn [42]Expand
def review_summary(base: RunReport, cand: RunReport, gate: GateResult) -> str:
lines = [
f"suite={base.suite_version}",
f"grader={base.grader_version}",
f"aggregate {base.aggregate['mean']:.2f} -> {cand.aggregate['mean']:.2f}",
]
for name, before in base.slices.items():
after = cand.slices.get(name)
candidate_label = (
"missing"
if after is None
else f"{after['mean']:.2f} (n={after['n']})"
)
lines.append(
f" {name:14s} {before['mean']:.2f} (n={before['n']}) -> {candidate_label}"
)
lines.append(f"taxonomy {base.taxonomy} -> {cand.taxonomy}")
lines.append(f"gate={'PASS' if gate.passed else 'FAIL'}")
lines.extend(f" - {reason}" for reason in gate.reasons)
return "\n".join(lines)PythonIn [43]Expand
print(review_summary(baseline_report, candidate_report, verdict))ConsoleOut [43]Expand
suite=b9dd6a7f0439c284f4cdf4ccc8ab9add604ccf4cb22be9c4c683e3355c7cc8d1
grader=substring-v1
aggregate 1.00 -> 0.75
multilingual 1.00 (n=1) -> 1.00 (n=1)
technical 1.00 (n=2) -> 1.00 (n=2)
billing 1.00 (n=1) -> 0.00 (n=1)
taxonomy {'pass': 4} -> {'pass': 3, 'forbidden_text': 1}
gate=FAIL
- Aggregate fell 0.250
- Slice 'billing' fell 1.000
- Regression on case c002A reviewer can match each displayed slice mean to its case count and read the labels before opening individual traces. The summary displays the same verdict and reasons returned by the gate for the chosen policy.
Limitations and Impact
The toy suite is useful for testing the evaluation machinery. To infer production effects, you need cases that represent the intended use, a grader that tracks the intended behavior, and a sample size appropriate to the decision. A reproducible wrong metric still measures the wrong behavior. Compare automated grades with qualified human judgments, and consider which groups or tasks are missing.
Version the evaluation setup along with the deployed system. The companion chapters cover runtime traces and coordinated releases. Versioning Models, Prompts, Data, and Tools
Summary
- Record versioned cases, scoring rules, and system configuration.
- Keep development, withheld confirmation, and known regression evidence distinct.
- Read traces to locate likely failures, then test the proposed cause with a controlled change.
- Compare the same cases and report slice-level counts alongside overall scores.
- Keep a predeclared regression gate separate from population inference.
Quiz
Ready to test your understanding? Take this quick quiz to reinforce what you've learned about evaluation-driven development.
Evaluation-Driven Development
Join the discussionAsk a question or share what you learned.
Keep exploring
Reference
Citation details
Cite or share this article.


Comments
Add to the conversation
A question, a correction, or an example from your own work.
No comments yet. Be the first to share your thoughts!