Sub topic 10
Stages of an automated retraining pipeline
A trigger decides when to retrain. The pipeline decides what happens next. This chapter walks through the stages a triggered run passes through, the artifact each stage leaves behind, and the places where a run should stop. It assumes you know the train, validate, test, deploy workflow, can read basic Python, and have used CI/CD or a job scheduler. Later chapters cover validation, versioning, the evaluation gate, registry, rollout, and orchestration in detail. Here you get the overall shape and the contracts between stages.
Why a pipeline is more than a training script
A manual retraining run usually lives in one notebook or script. An engineer reads the output and judges whether it looks right. An automated run has no such person in the loop, so every judgment the engineer made implicitly has to become an explicit stage with a pass or fail result.
Three properties separate a pipeline from a script:
- Each stage has a defined input and output. The output is a stored artifact, not a variable in memory.
- Each stage can stop the run. A stopped run is a normal outcome, not an error. Most triggered runs should be allowed to end without deploying anything.
- Each run is traceable. You can answer "which data, code, and configuration produced this model?" long after the run finished.
The stages at a glance
| Stage | Main input | Artifact produced | Typical stop reason |
|---|---|---|---|
| Trigger | Monitoring signals, schedule | Run record with trigger reason | Cooldown active |
| Ingest | Raw data sources, time window | Immutable dataset snapshot with an ID | Source unavailable |
| Validate | Snapshot, expected schema and statistics | Validation report | Schema break, too many nulls, too few rows |
| Train | Snapshot, code version, hyperparameters | Challenger model and training metrics | Training crash, non-converging loss |
| Evaluate | Challenger, champion, held-out data | Comparison report | Regression or gain below threshold |
| Register | Passing challenger | Versioned registry entry with lineage | Missing metadata |
| Roll out | Registered version | Traffic split or shadow logs | Canary metrics worse than champion |
| Monitor | Live predictions and outcomes | Metrics feeding the next trigger | Rollback signal |
Stage by stage
Trigger and run record
When a trigger fires, the first thing the pipeline does is write a run record. It holds the run ID, the trigger reason (for example drift_with_enough_data), and the signal values at that moment. This record is what lets you later ask whether drift-triggered runs produce better models than schedule-triggered ones.
Ingest and snapshot
Ingest selects the training window and freezes it. "The last 90 days from the warehouse" is not a dataset, because the table changes as late data arrives. A snapshot with an ID, or a query pinned to a table version, is. Without it you cannot reproduce the run, and you cannot compare the challenger and champion on the same data.
Decide the window deliberately. A short window adapts quickly but is noisy. A long window is stable but dilutes recent behavior. Also exclude rows whose labels have not matured yet, or you will train on incomplete outcomes.
Validate
Validation checks the snapshot before you spend compute on it. Typical checks are schema, null rates, value ranges, row counts, and label distribution. It protects against two failures. The first is a broken upstream job that silently changes a column. The second is data poisoning, where bad or adversarial rows enter the training set and the next model learns from them. A validation failure should stop the run and alert a human, not retry.
Train
Training should be a pure function of three things: the snapshot, the code version, and the configuration. Fix random seeds where feasible and log them. Save the training metrics and the model file together. Treat the result as a challenger, not a replacement. It has not earned production yet.
Evaluate
The evaluation gate compares the challenger with the current champion on the same held-out data, ideally including a recent time slice and important segments. A challenger that wins on average can still lose badly for one customer group, so segment checks belong here. The gate also needs a minimum improvement. Without one, noise in the metric will trigger a deployment on almost every run.
Register
Registration stores the model with its lineage: snapshot ID, code commit, configuration, metrics, and the validation and evaluation reports. Registered versions are immutable. Promotion changes a label such as staging or production on a version. It never overwrites the version.
Roll out and monitor
A passing model is still a hypothesis about live traffic. Shadow mode runs the challenger on real requests without serving its answers. A canary serves it to a small share of traffic. Both give evidence that offline evaluation cannot, for example latency or unexpected inputs. Keep the previous champion deployable so rollback is a configuration change, not a rebuild.
A minimal skeleton
This runnable sketch shows the control flow: shared context, one artifact per stage, and a stop signal. The stage bodies are stubs standing in for real work.
from dataclasses import dataclass, field
@dataclass
class RunContext:
trigger_reason: str
artifacts: dict = field(default_factory=dict)
class StageStopped(Exception):
"""Raised by a stage to end the run without an error."""
def ingest(ctx):
ctx.artifacts["snapshot_id"] = "snap-2026-11-30"
ctx.artifacts["rows"] = 120_000
def validate(ctx):
if ctx.artifacts["rows"] < 50_000:
raise StageStopped("validate: too few rows")
ctx.artifacts["validation_report"] = "ok"
def train(ctx):
ctx.artifacts["model_uri"] = "models/challenger-001"
ctx.artifacts["challenger_auc"] = 0.912
def evaluate(ctx, champion_auc=0.905, min_gain=0.002):
gain = ctx.artifacts["challenger_auc"] - champion_auc
if gain < min_gain:
raise StageStopped("evaluate: gain below threshold")
ctx.artifacts["evaluation"] = "pass"
def register(ctx):
ctx.artifacts["registry_version"] = "v42"
STAGES = [ingest, validate, train, evaluate, register]
def run_pipeline(trigger_reason):
ctx = RunContext(trigger_reason)
for stage in STAGES:
try:
stage(ctx)
except StageStopped as stop:
return "stopped", str(stop), ctx.artifacts
return "completed", "registered", ctx.artifacts
status, detail, artifacts = run_pipeline("drift_with_enough_data")
print(status, detail)
print(artifacts)Production orchestrators add retries, parallelism, and persistent storage, but the contract stays the same: a stage reads earlier artifacts, writes its own, and may stop the run.
Edge cases and common errors
- Retrying a deterministic failure. Retry transient errors such as network timeouts. Do not retry a validation failure, because the data will fail again.
- Evaluating on training-adjacent data. If the evaluation set overlaps with the training window, the gate approves overfit models. Split by time, with the evaluation data newer than the training data.
- Comparing against a stale champion score. Re-score the champion on the current evaluation set. Its score from deployment time was measured on different data.
- Non-idempotent stages. A rerun after a crash must not create a duplicate registry entry. Key artifacts by run ID.
- Treating "stopped" as failure. If every stopped run pages someone, the team will learn to ignore alerts. Alert on validation failures. Log gate rejections for review.
Exercise
A pipeline run trains a challenger with AUC 0.9031. The champion's AUC, recorded at its deployment three months ago, was 0.905. A teammate says the run should stop at the evaluation gate. What is wrong with this reasoning, and what should the gate do instead?
Show answer
The comparison uses a stale number. The champion's recorded AUC came from older evaluation data, so it is not comparable with the challenger's score on the current held-out set. The gate should score both the champion and the challenger on the same current evaluation data, then apply the regression and minimum-gain rules to the difference. The challenger may well win on the new data, or lose by more than 0.0019.