Sub topic 13
From CI to Continuous Delivery and Retraining
This chapter covers what happens after the pull-request checks pass. It assumes you have the earlier chapters' pieces: pytest tests for code, data, and model behavior, a metric quality gate, and a GitHub Actions workflow. It also assumes you know how to tag a Git commit and read a cron expression.
Where CI ends and delivery begins
Continuous integration answers one question: is this change safe to merge? Continuous delivery (CD) answers a different one: is this specific trained model safe to serve, and can we get it there repeatably?
In ML the two differ in what they act on. CI works on a commit of code, with small sample data and a small seeded model. CD works on a candidate model trained on the full dataset. That candidate is an artifact: a file plus the facts needed to trust it. A passing CI run says nothing about whether the full-scale model is good, because CI never trained it.
The handoff is the point where CI evidence turns into a delivery decision. It has three parts:
- A candidate artifact, built once from a merged commit.
- A record of how it was built (code version, data version, metrics).
- A promotion rule that decides whether it moves to the next stage.
The handoff record
A candidate model without provenance cannot be debugged, rolled back, or audited. The simplest provenance is a manifest: a small JSON file stored next to the model. It holds the Git commit, a hash of the training data, a hash of the model file, and the evaluation metrics.
The hashes matter because file names lie. model.pkl can be overwritten, but a SHA-256 digest changes if a single byte changes.
import hashlib
import json
from pathlib import Path
def sha256_of(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as f:
for chunk in iter(lambda: f.read(1 << 20), b""):
digest.update(chunk)
return digest.hexdigest()
def build_manifest(model_path: Path, data_path: Path,
metrics: dict, git_sha: str) -> dict:
return {
"git_sha": git_sha,
"model_sha256": sha256_of(model_path),
"data_sha256": sha256_of(data_path),
"metrics": metrics,
}
def should_promote(candidate: dict, production: dict,
min_gain: float = 0.0) -> list[str]:
"""Return reasons to block promotion; an empty list means promote."""
blockers = []
gain = candidate["accuracy"] - production["accuracy"]
if gain < min_gain:
blockers.append(
f"accuracy gain {gain:+.3f} is below the required {min_gain:+.3f}"
)
return blockers
def test_manifest_changes_when_data_changes(tmp_path):
model = tmp_path / "model.bin"
data = tmp_path / "train.csv"
model.write_bytes(b"weights")
data.write_text("age,label\n30,1\n")
first = build_manifest(model, data, {"accuracy": 0.9}, "abc123")
data.write_text("age,label\n31,1\n")
second = build_manifest(model, data, {"accuracy": 0.9}, "abc123")
assert first["data_sha256"] != second["data_sha256"]
assert first["model_sha256"] == second["model_sha256"]
def test_promotion_blocked_when_candidate_is_worse():
assert should_promote({"accuracy": 0.88}, {"accuracy": 0.90}) != []
assert should_promote({"accuracy": 0.91}, {"accuracy": 0.90}) == []Notice that should_promote compares against the model currently in production, not only against a fixed floor. The CI gate you built earlier compared against a baseline too. The difference is that this comparison runs on full-scale training results, so it carries more weight.
Stages of delivery
A promoted model rarely goes straight to all users. Each stage below adds evidence that the previous stage could not produce.
| Stage | What runs | Evidence it adds |
|---|---|---|
| Candidate | Full training on the merged commit | Full-scale metrics and the manifest |
| Registered | Artifact stored with its manifest | A versioned, retrievable model |
| Staging | Model served in a test environment | Loading works, latency is acceptable, the API contract holds |
| Shadow or canary | Real traffic, mirrored or a small share | Behavior on live inputs without full exposure |
| Production | Full traffic | Ongoing monitoring becomes the only evidence |
Staging checks are mostly software checks: does the container start, does the model file load, does a request return the expected response shape? Shadow and canary checks are the first to see the live input distribution. A model that passed every offline test can still fail here, because the offline test set is a sample of the past.
Keep the previous production version registered and ready. Rollback is then a pointer change to a known artifact. It does not require a rebuild.
Retraining as a loop
A deployed model degrades even when no code changes, because the world that produced its training data keeps moving. Retraining closes that loop. It reuses the same pipeline, with a different trigger.
Three trigger types are common:
- Schedule: retrain every N days. It is simple and predictable, but it wastes compute when nothing changed and reacts slowly when something did.
- Data-driven: retrain when a drift check against the reference dataset crosses a threshold, or when enough new labeled data has arrived.
- Performance-driven: retrain when live metrics fall. This is the most direct signal, but labels often arrive late, so it lags.
Most teams combine a schedule as a safety net with a drift trigger as the fast path. The decision logic should be a plain function you can test, not a condition buried in a workflow file.
def decide_retrain(drift_score: float, days_since_training: int,
drift_threshold: float = 0.2,
max_age_days: int = 30) -> list[str]:
"""Return the reasons to retrain; an empty list means do nothing."""
reasons = []
if drift_score > drift_threshold:
reasons.append(
f"drift score {drift_score:.2f} exceeds {drift_threshold:.2f}"
)
if days_since_training > max_age_days:
reasons.append(
f"model is {days_since_training} days old (limit {max_age_days})"
)
return reasons
def test_no_retrain_when_fresh_and_stable():
assert decide_retrain(0.05, 10) == []
def test_retrain_on_drift_or_age():
assert len(decide_retrain(0.35, 10)) == 1
assert len(decide_retrain(0.05, 45)) == 1
assert len(decide_retrain(0.35, 45)) == 2A retrained model is a new candidate. It must pass the same quality gate and promotion rule as any other, and it must never replace production automatically without that check. Automatic retraining without an automatic gate only automates the production of bad models.
A retraining workflow
The CI workflow runs on pull requests and pushes. The retraining workflow runs on a schedule or on demand. It lives in a separate file so that its cost and permissions stay separate from your fast checks.
This sketch assumes your repository has train.py, gate.py, and a metrics.json produced by training. Adapt the names to your project.
name: retrain
on:
schedule:
- cron: "0 3 * * 1"
workflow_dispatch:
jobs:
retrain:
runs-on: ubuntu-latest
timeout-minutes: 120
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.11"
cache: pip
- run: pip install -r requirements.txt
- name: Train candidate
run: python train.py --output artifacts/
- name: Apply quality gate
run: python gate.py artifacts/metrics.json
- name: Store candidate and manifest
uses: actions/upload-artifact@v4
with:
name: candidate-${{ github.sha }}
path: artifacts/The cron line runs it at 03:00 UTC every Monday. workflow_dispatch adds a manual button, which you will use when a drift alert fires. Steps run in order and the job stops at the first failing step. If gate.py exits with a non-zero status, nothing is uploaded, so a failed candidate never reaches the registry.
Common errors
These mistakes appear in most first implementations of ML delivery.
- Promoting on the offline metric alone. The test set may overlap with training data through time or duplicates, so the number is too optimistic. Require shadow or canary evidence before full traffic.
- Comparing against a stale baseline. If the baseline metric is from an old dataset, a candidate can "beat" it simply because the evaluation data changed. Re-evaluate the production model on the same test set as the candidate.
- Retraining on data that includes the model's own influence. If a model's predictions decide which cases get labeled, the new data is biased toward what the model already believes. Keep a random holdout of cases that bypass the model.
- No rollback artifact. Deleting old versions to save storage removes your fastest recovery path. Keep at least the last known good version.
- Drift thresholds picked once and never revisited. A threshold that fires weekly gets ignored, and one that never fires protects nothing. Review how often it triggers.
- Nondeterministic retraining. If two runs on the same commit and data give different models, you cannot tell whether a metric change comes from the data or from chance. The seeding and pinning rules from the reproducibility chapter apply here too.
The whole loop
The diagram shows how the pieces connect. CI is the first box. Everything after the merge belongs to delivery and retraining.
Decision criteria
Use these questions to decide how much delivery machinery you need.
- How costly is a bad prediction? If it is low, a manual promotion step after the gate may be enough. If it is high, add shadow or canary stages and a human approval.
- How fast does your data change? Slow-changing domains can retrain monthly on a schedule. Fast-changing ones need drift triggers.
- How long do labels take to arrive? If labels lag by weeks, performance-driven triggers cannot help, and you must rely on input drift as a proxy.
- How expensive is training? Costly training pushes you toward fewer, better-justified retraining runs and a cheap drift check in front of them.
Start with the smallest loop that gives you a manifest, a gate, and a rollback path. Add stages when an incident shows which evidence you were missing.
Exercise
A weekly scheduled workflow retrains your model, and the new candidate scores 0.91 accuracy against a fixed floor of 0.85, so it passes the CI quality gate. The production model scores 0.92 on a test set from last quarter. A teammate wants to promote the candidate automatically because it is above the floor. Give two reasons this is risky, and say what check you would add.
Show answer
First, the floor only guards against a bad absolute level. It does not catch a regression relative to production, and the candidate is 0.01 below the current model. Second, the two scores may not be comparable: the production number comes from last quarter's test set, so the candidate could be scored on different data. Add a promotion rule that evaluates both models on the same, current test set and requires the candidate to match or beat production, optionally followed by a canary stage on live traffic before full promotion.
Exercise
Why does the manifest store a SHA-256 hash of the training data and model file instead of just their file paths?
Show answer
Paths can stay the same while the contents change, for example when a file is overwritten. A hash changes whenever the content changes, so it lets you prove which exact data produced which exact model and detect that an artifact was altered or replaced.