Evaluation-Driven Development › Regression Gates

Michael BrenndoerferDecember 2, 20265 min read
Language AI HandbookAll chapters
Part 64 of 67Compound AI System Design
Chapter 487Evaluation-Driven Development › Regression Gates
Reading section 8 of 14 · Regression Gates · 5 minSection 8 of 14 · 5 min

Section 8 of 14 · 5 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

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 10−1210^{-12} 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]
CollapseExpand
@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]
CollapseExpand
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]
CollapseExpand
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]
CollapseExpand
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]
CollapseExpand
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]
CollapseExpand
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]
CollapseExpand
Toy paired resampling quantiles: [-1.000, 0.000]

For this fixture there are two changes of −1-1 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]
CollapseExpand
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]
CollapseExpand
Five possible mean differences run from minus one to zero. The center bar has mass six sixteenths and both ends have one sixteenth.
The exact distribution for resampling the four toy differences assigns 1/16 of its mass to zero.

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.

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!

Newsletter

Stay up to date

Get new articles, book updates, and notes on AI and technology.

Unsubscribe at any time. Privacy policy