Sub topic 7
Gating promotion on evaluation results
This chapter assumes you have the pipeline from the earlier chapters: a frozen TrainConfig, stage functions (load_data, split, train, evaluate), and a run_pipeline function. It also assumes you can read basic pytest tests and use Python 3.9 or later.
What a gate does
A training run always produces a model, and that doesn't mean the model is fit to serve. An evaluation gate is an automated check between "a model was trained" and "that model replaces what is in production". If the check fails, the pipeline stops and the current production model stays in place.
Promotion means making a model the one that downstream systems load. That could be copying an artifact to a registry path, moving a tag, or updating a pointer file. A gate protects that step. Without one, a bad data change, a broken feature, or a bad hyperparameter can reach users because nobody looked at the metrics that day.
The run_pipeline function you already have contains the simplest gate: it raises ValueError when accuracy is below cfg.min_accuracy. That works for a first version. It has three limits:
- It checks only one metric.
- It compares against a fixed number, never against the model currently in production.
- It mixes the decision with the training code, so you can't test the decision alone.
The rest of this chapter fixes those limits.
Two kinds of check
Most gates combine two kinds of rule.
| Rule type | Question it answers | Example | Weakness |
|---|---|---|---|
| Absolute floor | Is the model good enough at all? | accuracy at least 0.80 | Does not notice a model that is worse than the current one but still above the floor |
| Regression limit | Is the model no worse than production, within tolerance? | accuracy no more than 0.02 below the baseline | Needs a stored baseline, and the first run has none |
The floor catches broken models. The regression limit catches quiet degradation, such as a model that slides from 0.97 to 0.85 over several releases and never trips an 0.80 floor.
Making the gate a function
Keep the decision in a pure function. It takes metrics in and returns a list of failure messages. An empty list means the model passed. Returning every failure, not just the first, tells you the whole problem in one run.
import math
from dataclasses import dataclass
from typing import Optional
@dataclass(frozen=True)
class GateRule:
metric: str
min_value: Optional[float] = None
max_regression: Optional[float] = None
def check_gate(metrics, baseline, rules):
failures = []
for rule in rules:
value = metrics.get(rule.metric)
if value is None:
failures.append(f"{rule.metric}: missing from candidate metrics")
continue
if not math.isfinite(value):
failures.append(f"{rule.metric}: value is {value}, not a finite number")
continue
if rule.min_value is not None and value < rule.min_value:
failures.append(
f"{rule.metric}: {value:.3f} is below the floor of {rule.min_value}"
)
if (
rule.max_regression is not None
and baseline is not None
and rule.metric in baseline
):
drop = baseline[rule.metric] - value
if drop > rule.max_regression:
failures.append(
f"{rule.metric}: dropped {drop:.3f} from baseline "
f"{baseline[rule.metric]:.3f}, limit is {rule.max_regression}"
)
return failuresThree details matter here.
- A missing metric fails the gate. If a refactor renames
accuracytoacc, a gate that skips absent metrics would pass every model forever. Treat absence as failure. - NaN fails the gate. In Python,
float("nan") < 0.8isFalse. A naive floor check would let a NaN metric through. Themath.isfinitecheck closes that hole. - No baseline means no regression check. On the first run there is nothing to compare with, so only the floor applies. This is a deliberate choice, and the pipeline should log that it happened.
The flow
The gate sits after evaluation and before any write to the registry.
Promotion as a separate stage
Do not promote inside train. Promotion has side effects outside the run, so it belongs in its own stage, called only when the gate has returned no failures.
The example below uses a JSON file as a stand-in for a model registry. A real registry, such as MLflow's or a cloud service's, replaces these two functions and keeps the same shape.
import json
import os
import tempfile
from pathlib import Path
def load_baseline(registry):
pointer = Path(registry) / "production.json"
if not pointer.exists():
return None
return json.loads(pointer.read_text())["metrics"]
def promote(registry, fingerprint, metrics):
registry = Path(registry)
registry.mkdir(parents=True, exist_ok=True)
record = {"fingerprint": fingerprint, "metrics": metrics}
fd, tmp_name = tempfile.mkstemp(dir=registry, suffix=".tmp")
with os.fdopen(fd, "w") as handle:
json.dump(record, handle, indent=2)
os.replace(tmp_name, registry / "production.json")
return recordos.replace is atomic on the same filesystem. A reader sees either the old pointer or the new one, never a half-written file. Writing the temp file in the same directory is what guarantees both paths are on one filesystem.
Now connect the pieces. This version reuses TrainConfig, config_fingerprint, and the stage functions from earlier chapters, and it replaces the single if in run_pipeline.
RULES = [
GateRule("accuracy", min_value=0.80, max_regression=0.05),
]
def run_and_promote(cfg, registry):
X, y = load_data()
X_train, X_test, y_train, y_test = split(X, y, cfg)
model = train(X_train, y_train, cfg)
metrics = evaluate(model, X_test, y_test)
baseline = load_baseline(registry)
failures = check_gate(metrics, baseline, RULES)
if failures:
raise ValueError("promotion blocked: " + "; ".join(failures))
return promote(registry, config_fingerprint(cfg), metrics)A raised exception gives you a nonzero exit code from the command line, which is what CI and orchestrators read as "this run failed". That is the mechanism that makes the gate effective outside your terminal.
Choosing thresholds
A gate is only as good as its numbers. Some practical points:
- Know the noise. The iris test split has 30 rows when
test_sizeis 0.2 of 150. One misclassified row moves accuracy by 0.033. Amax_regressionof 0.01 would block a model because of a single row. Set tolerances larger than the smallest change your test set can show, and larger than the run-to-run variation you measure by training with several seeds. - Don't tune on the gate's data. If you adjust hyperparameters until the held-out test score passes, the test set becomes part of training and the gate stops measuring anything. Choose hyperparameters with validation data. Use the test set for the final decision only.
- Gate on more than one number. An overall accuracy of 0.95 can hide a class with recall of 0.40. Add per-class recall or a slice metric to
metricsand a rule for each. The gate function already supports this, because every rule is keyed by metric name. - Put thresholds in configuration. The gate values are tunable settings. In the earlier code,
min_accuracylives inTrainConfig, so it is part of the fingerprint. If you keep theRULESlist in code, as above, change it through review like any other code.
Testing the gate
The gate is the most safety-critical code in the pipeline, and because it is a pure function it is cheap to test. Cover each branch: pass, floor failure, regression failure, missing metric, NaN, and no baseline.
import pytest
RULES = [GateRule("accuracy", min_value=0.80, max_regression=0.05)]
def test_gate_passes_good_model():
assert check_gate({"accuracy": 0.95}, {"accuracy": 0.94}, RULES) == []
def test_gate_blocks_below_floor():
failures = check_gate({"accuracy": 0.70}, None, RULES)
assert len(failures) == 1
assert "below the floor" in failures[0]
def test_gate_blocks_regression_above_floor():
failures = check_gate({"accuracy": 0.88}, {"accuracy": 0.97}, RULES)
assert any("dropped" in message for message in failures)
def test_gate_blocks_missing_metric():
assert check_gate({}, None, RULES) != []
def test_gate_blocks_nan():
assert check_gate({"accuracy": float("nan")}, None, RULES) != []
def test_blocked_run_leaves_production_untouched(tmp_path):
first = run_and_promote(TrainConfig(), tmp_path)
strict = TrainConfig(min_accuracy=0.99)
original = (tmp_path / "production.json").read_text()
bad_rules = [GateRule("accuracy", min_value=1.01)]
failures = check_gate(first["metrics"], None, bad_rules)
assert failures
assert (tmp_path / "production.json").read_text() == originalThe last test is a smoke test of the invariant that matters: when the gate fails, nothing in the registry changes. Add a variant that calls run_and_promote with a patched RULES and uses pytest.raises(ValueError) if you want to cover the full path.
Common errors
| Mistake | Effect | Fix |
|---|---|---|
| Gate skips metrics that are absent | Renamed metric silently disables the check | Treat missing metrics as failures |
| NaN compared with `<` | NaN passes every floor | Check `math.isfinite` first |
| Tolerance smaller than test-set granularity | Good models blocked at random | Measure seed variance and size the tolerance above it |
| Promotion inside the training stage | Failed gate cannot prevent the write | Keep promotion as a separate, later stage |
| Non-atomic pointer write | Readers can see a partial file | Write a temp file, then `os.replace` |
| Gate failure logged but exit code 0 | CI shows green on a blocked model | Raise an exception or call `sys.exit(1)` |
| Baseline taken from the same run | Model always compared with itself | Load baseline from the registry before training |
Failure messages are part of the product
When the gate blocks a run, someone must decide what to do at short notice. A message like promotion blocked forces them to dig through logs. A message like accuracy: 0.882 dropped 0.088 from baseline 0.970, limit is 0.05 tells them the metric, both numbers, and the rule. Record the failures and the config fingerprint with the tracked run so a reader can see which configuration was rejected and why.
Exercise
A candidate model has accuracy 0.93, and the production baseline has accuracy 0.97. The gate rule is GateRule("accuracy", min_value=0.80, max_regression=0.03). Does the candidate pass? Which part of the rule decides, and what would change if there were no baseline?
Show answer
It fails. The floor passes because 0.93 is above 0.80, but the drop is 0.97 - 0.93 = 0.04, which exceeds the regression limit of 0.03, so check_gate returns a "dropped" failure. With no baseline (the first run), the regression check is skipped and only the floor applies, so the candidate would pass.
Exercise
Your team adds a rule GateRule("f1_macro", min_value=0.75), but a refactor changes evaluate to return the key "f1" instead. What does the current check_gate do on the next run, and why is that the safer behavior than skipping the rule?
Show answer
metrics.get("f1_macro") returns None, so check_gate adds "f1_macro: missing from candidate metrics" and the run is blocked. This is safer because a gate that skips absent metrics would pass every model after the rename, and nobody would notice the check had stopped working.