Sub topic 8
Quality Gates: Thresholds and Baseline Comparison
A quality gate is an automated check that turns a model's metrics into a pass or fail result. This chapter assumes you can write pytest tests, can train and evaluate a scikit-learn model, and know how a CI job fails a pull request when a command exits with a non-zero status. Earlier chapters covered code tests, data validation, and behavioral tests. Those checks tell you the model is well-formed. A gate tells you whether it is good enough to ship.
What a quality gate decides
A trained model can pass every behavioral test and still be worse than the model it replaces. Probabilities can sum to 1 and predictions can ignore row order while accuracy falls by five points. Nothing in your unit tests notices that, because they check properties and not performance.
A quality gate closes this gap. It takes a metrics dictionary from the candidate model, compares it with fixed rules and with a baseline, and returns a verdict. In CI the verdict decides whether the pull request can merge.
A good gate has three properties:
- Deterministic. The same inputs give the same verdict. This depends on the seeding and pinning from the reproducibility chapter.
- Explainable. A failure says which metric, which rule, and by how much.
- Cheap to run. The gate works on metrics that already exist, so the check itself takes milliseconds.
Two kinds of rules
Most gates combine two rules that catch different failures.
| Rule | Question it answers | Catches | Misses |
|---|---|---|---|
| Absolute threshold | Is the model above the minimum we accept? | A model that is simply bad | Slow decline that stays above the floor |
| Baseline comparison | Is the model worse than what we have now? | A regression from the current model | A baseline that was already poor |
The absolute threshold is a business decision, such as "we will not ship below 0.85 accuracy." The baseline comparison is a relative guard, such as "no more than 0.02 worse than production."
You need both. With only a floor, a model can lose several points on each merge and never trip the rule until it reaches the floor. With only a baseline comparison, a sequence of small allowed drops can wear the model down. Each step passes, but the total loss is large. The floor stops that slide.
A gate as a testable function
Write the gate as a pure function that returns a list of failure messages. An empty list means pass. This is easy to unit test, and the messages can go straight into CI logs.
def check_quality_gate(candidate: dict, baseline: dict,
min_accuracy: float = 0.85,
max_drop: float = 0.02) -> list[str]:
failures = []
acc = candidate["accuracy"]
if acc < min_accuracy:
failures.append(f"accuracy {acc:.3f} is below the minimum {min_accuracy:.3f}")
if baseline["accuracy"] - acc > max_drop:
failures.append(
f"accuracy dropped by more than {max_drop:.3f} "
f"(baseline {baseline['accuracy']:.3f}, candidate {acc:.3f})"
)
return failures
def test_gate_passes_for_small_change():
assert check_quality_gate({"accuracy": 0.90}, {"accuracy": 0.91}) == []
def test_gate_fails_for_regression():
assert len(check_quality_gate({"accuracy": 0.80}, {"accuracy": 0.91})) == 2The function collects every failure instead of returning at the first one. A developer who sees both messages can fix the problem in one pass. The second test shows this: a candidate at 0.80 breaks the floor and the baseline rule at once, so the gate reports two failures.
Testing the gate itself matters. If the comparison has the wrong sign, the gate passes every model, and nobody notices until a bad model ships.
Choosing thresholds
Setting the floor
Pick the floor from the cost of being wrong, not from the current score. If the current model scores 0.91, a floor of 0.90 will fail on ordinary variation. A floor of 0.85 leaves room for noise while still blocking clearly broken models. Record the reason for the number next to it in the code or the docs, so that a later change is a deliberate decision.
Setting the allowed drop
The allowed drop must be larger than the noise in your metric. Measured accuracy on a finite test set has a standard error of about sqrt(p(1 - p) / n). At accuracy 0.90 on 1,000 test rows, that is about 0.0095. A max_drop of 0.005 would then fail on random variation alone, and the team would learn to rerun or ignore the check.
To estimate noise for your own project, retrain the same code with several seeds on the same data and look at the spread of the metric. Set max_drop to a bit more than that spread, and tighten it only when you have a larger or more stable evaluation set.
Floating-point edges
Subtraction can land on the wrong side of a boundary. The expression 0.91 - 0.89 evaluates to about 0.020000000000000018, which is greater than 0.02. A drop you meant to allow therefore fails. Two fixes work. Round the difference before comparing, for example round(baseline - acc, 6) > max_drop. Or choose thresholds that do not sit exactly on values your metrics are likely to produce.
Where the baseline comes from
The baseline is the metrics of the model you are comparing against. The source decides how trustworthy the comparison is.
- A committed metrics file. For example
metrics/baseline.json, updated by a deliberate pull request. This is simple and reviewable. The risk is that it goes stale when the data or the evaluation set changes. - The production model's recorded metrics. These come from a model registry or an artifact store. The comparison is against what users actually get, but CI now needs access to that store.
- The previous run on the main branch. This tracks the latest merged state. The danger is drift by small steps, because each merge becomes the next baseline.
Whichever source you use, compute baseline and candidate metrics on the same evaluation data, with the same code. A baseline measured on last month's test set and a candidate measured on this month's test set is not a comparison. If you change the evaluation set, regenerate the baseline in the same pull request.
Update the baseline only on purpose. If CI overwrites the baseline after every passing run, the gate stops guarding anything, and the small allowed drops add up. Make a baseline change a visible diff that a reviewer approves.
Running the gate in CI
The gate becomes useful when a failure blocks the merge. Wrap it in a short script that loads two metrics files, prints the failures, and sets the exit code.
import json
import sys
from pathlib import Path
from gates import check_quality_gate
def main(candidate_file: str, baseline_file: str) -> int:
candidate = json.loads(Path(candidate_file).read_text())
baseline = json.loads(Path(baseline_file).read_text())
failures = check_quality_gate(candidate, baseline)
for message in failures:
print(f"GATE FAILED: {message}")
if not failures:
print("Quality gate passed")
return 1 if failures else 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1], sys.argv[2]))This script assumes check_quality_gate lives in a module named gates.py on the import path. In the workflow, run it as a step after the model is trained and evaluated:
python check_gate.py metrics/candidate.json metrics/baseline.jsonA non-zero exit code fails the step, which fails the job, which marks the pull request as failing. Mark the job as a required status check in your repository settings. Without that, a failing gate is only a warning that people can merge past.
Gating more than one metric
Accuracy alone hides problems. A model for a rare event can score 0.98 accuracy while finding none of the events. Gate the metrics that match the task:
- For imbalanced classification, use recall, precision, or area under the precision-recall curve, not only accuracy.
- For regression, use an error measure such as mean absolute error. The direction flips: higher is worse, so the check becomes
candidate - baseline > max_increase. - For latency or model size, use an upper bound, because a slightly better model that is ten times slower may be unusable.
Keep the direction of each metric explicit. A common bug is applying a "higher is better" rule to an error metric, which makes the gate reward regressions.
Aggregate metrics can also hide failures in a subgroup. If you have an important slice of the data, such as a region or a customer segment, compute the metric on that slice and give it its own floor. This costs little, because the evaluation already has the rows.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Gate fails randomly on unchanged code | `max_drop` smaller than metric noise, or unseeded training | Measure the spread across seeds, widen the tolerance, fix seeds |
| Gate always passes | Wrong comparison direction, or the baseline file is the candidate's own metrics | Add a test with a deliberately bad candidate, as in `test_gate_fails_for_regression` |
| Gate fails after a data update | Baseline computed on the old evaluation set | Regenerate the baseline on the new set in the same pull request |
| Slow quality decline over many merges | Baseline refreshed on every merge, no floor | Add an absolute floor and update the baseline only by reviewed changes |
| Failure message says only "gate failed" | Function returns a boolean | Return messages that name the metric, the values, and the rule |
| Failing gate does not block merging | Job not set as a required check | Mark the job as required in branch protection |
Summary of decisions
- Use both an absolute floor and a baseline comparison.
- Set the allowed drop above the measured seed-to-seed noise.
- Return readable failure messages, and unit test the gate function.
- Keep the baseline in a reviewed, versioned location, and compute it on the same evaluation data as the candidate.
- Gate the metrics that fit the task, with the correct direction, and add slice checks for important subgroups.
- Make the job a required check so a failure blocks the merge.
Exercise
A gate uses minaccuracy=0.85 and maxdrop=0.02. The baseline accuracy is 0.92 and the candidate accuracy is 0.89. How many failures does checkqualitygate return, and which rule causes them?
Show answer
One failure. The candidate is above the floor (0.89 is at least 0.85), so the absolute rule passes. The drop is 0.92 - 0.89 = 0.03, which is greater than 0.02, so the baseline rule fails. The candidate is still acceptable in absolute terms but is a regression from the baseline.
Exercise
A teammate proposes having CI overwrite metrics/baseline.json with the candidate's metrics after every pull request that passes the gate. Give one problem with this and one safer alternative.
Show answer
Each merge may lose up to max_drop and then become the new baseline, so quality can decline in small allowed steps with no check against the original level. Safer alternatives: keep an absolute floor, and update the baseline only through a reviewed pull request that changes the file, or compare against the metrics of the model in production.
Exercise
Your evaluation set has 400 rows and accuracy is about 0.90. A colleague sets max_drop to 0.005. Estimate the standard error of the accuracy and explain what will happen in CI.
Show answer
The standard error is about sqrt(0.9 * 0.1 / 400) = sqrt(0.000225) = 0.015. A max_drop of 0.005 is far below this noise, so the gate will fail on random variation even when the model has not changed. The fix is to widen the tolerance to cover the measured spread, or to use a larger evaluation set.