Sub topic 18
Testing and observing the pipeline itself
The earlier chapters built the parts of an automated retraining pipeline: triggers, a trigger policy, data validation, an evaluation gate, a registry, and a rollout. This chapter covers how to know those parts work and keep working. It assumes you can write pytest tests, read structured logs, and know what a cron-style scheduler and a metrics dashboard do.
Why the pipeline needs its own monitoring
You already monitor the model. The pipeline that produces the model is software too, and it fails in ways model monitoring does not catch.
Most pipeline failures are silent:
- The trigger never fires because a drift job stopped writing its statistics. The model ages, and nothing alerts.
- The trigger fires every day because a threshold was set too low, so cost climbs.
- The evaluation gate has a bug and approves every challenger.
- A data source changes its schema. Validation is skipped or misconfigured, and the pipeline trains on garbage.
- Each run succeeds technically, but the gate rejects every challenger, so the production model never updates.
A pipeline that is down looks the same from outside as a pipeline with nothing to do. Testing prevents bugs in the decision logic. Observability tells you when the pipeline stops behaving the way you designed it.
Testing the decision logic
The trigger policy and the evaluation gate are pure functions, which makes them the cheapest and most valuable things to test. A bug in either one changes what reaches production.
Test the boundaries and the precedence rules. For example, a cooldown must win over a drift signal, and a maximum model age must fire even when there is no drift. The file below includes the two functions from earlier chapters so it runs on its own. In a real repository you would import them.
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
import pytest
@dataclass(frozen=True)
class TriggerConfig:
psi_threshold: float = 0.2
min_new_rows: int = 50_000
max_model_age: timedelta = timedelta(days=30)
cooldown: timedelta = timedelta(days=2)
def should_retrain(now, last_trained, max_feature_psi, new_rows, cfg):
age = now - last_trained
if age < cfg.cooldown:
return False, "cooldown"
if age >= cfg.max_model_age:
return True, "max_model_age"
if max_feature_psi >= cfg.psi_threshold and new_rows >= cfg.min_new_rows:
return True, "drift_with_enough_data"
return False, "no_trigger"
def should_promote(challenger_auc, champion_auc, challenger_data_ok,
min_gain=0.002, max_regression=0.0):
if not challenger_data_ok:
return False, "data_validation_failed"
delta = challenger_auc - champion_auc
if delta < -max_regression:
return False, "regression"
if delta < min_gain:
return False, "gain_below_threshold"
return True, "promote"
NOW = datetime(2026, 11, 30, tzinfo=timezone.utc)
CFG = TriggerConfig()
def test_cooldown_beats_drift():
last = NOW - timedelta(days=1)
assert should_retrain(NOW, last, 0.9, 500_000, CFG) == (False, "cooldown")
def test_max_age_fires_without_drift():
last = NOW - timedelta(days=31)
assert should_retrain(NOW, last, 0.0, 0, CFG) == (True, "max_model_age")
def test_drift_needs_enough_rows():
last = NOW - timedelta(days=10)
assert should_retrain(NOW, last, 0.5, 1_000, CFG) == (False, "no_trigger")
@pytest.mark.parametrize(
"challenger, champion, data_ok, expected",
[
(0.99, 0.90, False, "data_validation_failed"),
(0.50, 0.90, True, "regression"),
(0.9051, 0.905, True, "gain_below_threshold"),
(0.912, 0.905, True, "promote"),
],
)
def test_gate_reasons(challenger, champion, data_ok, expected):
assert should_promote(challenger, champion, data_ok)[1] == expectedThe first gate case matters most. A challenger with a suspiciously high AUC must still be blocked when its data checks failed. Keep that case in the suite permanently. It guards against someone reordering the checks later.
Testing the pipeline as a whole
Unit tests do not show that the stages connect. Add these checks at the pipeline level:
- Smoke run on a tiny dataset. Run every stage end to end on a few hundred rows in CI. This catches broken imports, schema mismatches between stages, and missing permissions.
- Bad-data injection. Feed in a dataset with a null column, a shifted unit, or duplicated rows. Assert that the run stops at data validation and that no model reaches the registry.
- Known-bad challenger. Force a model that predicts a constant. Assert that the gate rejects it.
- Idempotency. Run the same trigger event twice. Assert that you get one model version, or two clearly linked versions, and not a half-written state. Schedulers retry, so this will happen in production.
- Rollback drill. Promote a model in a staging environment, then roll back. Confirm that serving returns to the previous version.
Observing the pipeline
Emit one structured record per run, plus timing for each stage. The record explains each decision: which trigger fired, what the gate compared, and how long each stage took.
import json
import logging
import time
import uuid
from contextlib import contextmanager
from dataclasses import asdict, dataclass, field
from typing import Optional
logging.basicConfig(level=logging.INFO, format="%(message)s")
log = logging.getLogger("retrain")
@dataclass
class RunRecord:
run_id: str
trigger_reason: str
stage_seconds: dict = field(default_factory=dict)
train_rows: int = 0
challenger_auc: Optional[float] = None
champion_auc: Optional[float] = None
gate_reason: str = ""
status: str = "running"
@contextmanager
def stage(record, name):
start = time.perf_counter()
try:
yield
finally:
record.stage_seconds[name] = round(time.perf_counter() - start, 3)
record = RunRecord(run_id=str(uuid.uuid4()), trigger_reason="max_model_age")
with stage(record, "validate"):
record.train_rows = 120_000
with stage(record, "train"):
time.sleep(0.01)
record.challenger_auc, record.champion_auc = 0.912, 0.905
record.gate_reason, record.status = "promote", "succeeded"
log.info(json.dumps(asdict(record)))Because the finally block records the duration even when a stage raises, failed stages still show up in the timing data.
What to alert on
Alert on the pipeline's behavior over time, not only on single-run errors.
| Failure | Signal | Alert condition |
|---|---|---|
| Trigger never fires | Age of the production model | Age exceeds the maximum model age plus a grace period |
| Pipeline stopped running | Time since last run record | No run record within the expected interval |
| Retraining loop | Runs per week | More runs than the cooldown allows |
| Gate always rejects | Consecutive rejections | Three or more in a row |
| Gate always accepts | Promotion rate | Every challenger promoted over many runs |
| Cost drift | Stage duration and compute spend | Training time or spend above a multiple of the trailing median |
| Data trouble | Validation failures and row counts | A sudden drop in row counts, or repeated validation failures |
The "no run record" alert is a dead man's switch. It fires on the absence of data, which an error-count alert cannot detect.
Common mistakes
- Testing only the model code and not the trigger and gate logic.
- Logging a run only when it succeeds, so failed and skipped runs leave no trace.
- Recording that a trigger fired without recording why. The reason string is what lets you tune thresholds later.
- Setting alerts on error counts alone, which misses a pipeline that never runs.
- Never rehearsing rollback, so the first attempt happens during an incident.
Exercise
A team's pipeline has been green for two months, with no failed runs and no error alerts. The production model is now 75 days old, and the configured maximum model age is 30 days. Name the most likely cause and the monitoring that would have caught it earlier.
Show answer
The pipeline most likely stopped being triggered. For example, the scheduler or the drift job stopped running, so no run produced an error. The team had no alert on the absence of runs. A dead man's switch (alert when no run record appears within the expected interval) and an alert on production model age (age beyond the 30-day maximum plus a grace period) would have fired within days.