All lessons · Guided routes

Capstone 8 of 10

Capstone 8: A model from data contract to safe rollback

A fraud model goes to production, and three months later the data has drifted. You build the whole lifecycle around it: a data contract, training, a validation gate, experiment tracking, a registry, shadow and canary releases, drift detection, retraining, and rollback.

What you build

  1. Data contract

    The schema and value ranges a training batch must meet before it is used.

    Lessons: MLOps Data Quality and Data Contracts

  2. Training and validation

    A logistic regression (standard library only) and a gate on AUC before registration.

    Lessons: Classic Machine Learning, How Models Are Trained

  3. Experiments and registry

    Each run records its data hash, parameters, and metrics; models move through stages in a registry.

    Lessons: Model Registry and Promotion: Tracking, Validation Gates, and Rollback, The Model Lifecycle: Train, Deploy, Automate

  4. Shadow and canary

    A new model scores live traffic in shadow, then takes a share of it as a canary.

    Lessons: Model Canary and Shadow Deployment: A/B Tests and Champion/Challenger

  5. Drift

    The population stability index finds the drifted feature in a new batch.

    Lessons: Detecting Drift, Monitoring Models in Production

  6. Retrain and roll back

    Retrain on new data, promote, and roll back to the previous version when it misbehaves.

    Lessons: MLOps Model Operations and Drift, ML SLOs and Model Incidents: Accuracy, Drift, Fairness, and Response

Before you start

ToolVersion
python33.10 or later

Ports: none. Resources: Under 100 MB; no network, no GPU, standard library only.

What it creates (and the reset removes): ~/labs/capstones/mlops (data, runs, registry). Every name starts with cap- or lives under ~/labs/capstones, so nothing of yours is changed. The scripts stop with a clear message if a tool is missing or a port is taken.

Get the files

One archive holds every capstone and the shared service. Read a script before you run it; the main ones are shown below.

mkdir -p ~/labs && cd ~/labs
curl -fsSLO https://mohankrishnapodile.com/capstones/capstones-lab.tar.gz
tar -xzf capstones-lab.tar.gz && cd capstones-lab
ls

Run it

All in one, with the reset afterwards even if a step fails:

bash run.sh 08-mlops

Or one step at a time, to look around between them (add KEEP=1 before bash run.sh to keep it running after verify):

python3 08-mlops/mlops.py setup
python3 08-mlops/mlops.py verify
python3 08-mlops/mlops.py reset

Expected output

This is a real run of run.sh 08-mlops, recorded when the page was built. Digests, timings, and random values differ on your machine; every check should still say PASS, and the last line should say all checks passed.

== 1. Dataset: 3,000 labelled payments for training, 1,000 for testing
  fraud rate: train 0.123, test 0.101
== 2. Data contract: a batch with broken rows is rejected before training
  batch-broken.json: 3 contract violations, rejected; first: row 5: amount=-40 outside [0.0, 20000.0]
== 3. Train, validate against the gate, track, register, deploy
  run-001: AUC 0.8576 (gate: at least 0.8) -> registered as version 1
  version 1 promoted to production
== 4. A new month of traffic arrives, and it has shifted (larger amounts)
  data/live.json written; verify.py measures drift on it
== Dataset and contract
  PASS  the training data meets the contract
  PASS  the broken batch shows exactly its 3 violations
== Tracking and registry
  PASS  run-001 records the hash of the exact data it was trained on
  PASS  version 1 is in production
  PASS  production AUC 0.858 meets the gate of 0.8
== Serving: the production model scores a payment
  PASS  a risky payment scores 1.00, an ordinary one 0.01
== Drift on the new month
  PASS  amount PSI 0.75 > 0.25: significant drift
  PASS  hour PSI 0.01 < 0.1: stable
  production AUC on the drifted month: 0.873 (was 0.858)
== Retrain on recent data, compare in shadow, release by canary
  PASS  shadow on 500 recent payments: new AUC 0.840, current 0.840
  shadow: the two models agree on 99.2% of decisions
  PASS  canary: version 2 served 49 requests (10%) without errors
  PASS  version 2 promoted to production; version 1 archived
== Rollback
  PASS  rolled back to version 1: the same model and AUC as before
  registry: {1: 'production', 2: 'archived'}

RESULT: all checks passed

The files

08-mlops/mlops.py
#!/usr/bin/env python3
"""Capstone 8, MLOps: dataset -> data contract -> training -> validation -> experiment tracking ->
model registry -> deployment -> shadow and canary -> drift -> retraining -> rollback.

Standard library only. Works in ~/labs/capstones/mlops.
  python3 mlops.py setup     build everything up to a model in production and a drifted batch
  python3 mlops.py verify    check every stage, then retrain, shadow, canary, promote, roll back
  python3 mlops.py reset     remove the work folder
"""
import hashlib
import json
import math
import os
import random
import shutil
import sys
import time

WORK = os.path.expanduser("~/labs/capstones/mlops")
FEATURES = ["amount", "hour", "new_device", "country_risk"]
CONTRACT = {"amount": (0.0, 20000.0), "hour": (0, 23), "new_device": (0, 1), "country_risk": (0.0, 1.0)}
GATE = {"min_auc": 0.80, "max_auc_drop": 0.02}
PASSES, FAILS = [], []


def ok(msg): PASSES.append(msg); print("  PASS ", msg)
def bad(msg): FAILS.append(msg); print("  FAIL ", msg)
def p(*parts): return os.path.join(WORK, *parts)
def dump(path, obj): open(path, "w").write(json.dumps(obj, indent=1) + "\n")
def load(path): return json.load(open(path))


# ---------- data
def make_batch(n, seed, shift=0.0):
    """Synthetic card payments; fraud is more likely for large amounts, night hours, new devices,
    and risky countries. shift moves the amount distribution (drift)."""
    r = random.Random(seed)
    rows = []
    for _ in range(n):
        amount = round(r.lognormvariate(4.0 + shift, 1.0), 2)
        hour = r.randrange(24)
        new_device = 1 if r.random() < 0.15 else 0
        risk = round(r.random() ** 2, 3)
        z = -5.0 + 0.006 * amount + (1.5 if hour < 5 else 0) + 2.2 * new_device + 3.2 * risk
        fraud = 1 if r.random() < 1 / (1 + math.exp(-z)) else 0
        rows.append({"amount": min(amount, 19999.0), "hour": hour, "new_device": new_device, "country_risk": risk, "fraud": fraud})
    return rows


def contract_errors(rows):
    errs = []
    for i, row in enumerate(rows):
        for f, (lo, hi) in CONTRACT.items():
            v = row.get(f)
            if not isinstance(v, (int, float)) or v is None or not lo <= v <= hi:
                errs.append(f"row {i}: {f}={v!r} outside [{lo}, {hi}]")
        if row.get("fraud") not in (0, 1):
            errs.append(f"row {i}: fraud label missing")
    return errs


# ---------- model: logistic regression trained with gradient descent, standardised features
def fit(rows, lr=0.3, epochs=300, seed=1):
    xs = [[row[f] for f in FEATURES] for row in rows]
    mean = [sum(c) / len(c) for c in zip(*xs)]
    sd = [max(1e-9, math.sqrt(sum((v - m) ** 2 for v in c) / len(c))) for c, m in zip(zip(*xs), mean)]
    X = [[(v - m) / s for v, m, s in zip(x, mean, sd)] for x in xs]
    y = [row["fraud"] for row in rows]
    w, b = [0.0] * len(FEATURES), 0.0
    for _ in range(epochs):
        gw, gb = [0.0] * len(w), 0.0
        for xi, yi in zip(X, y):
            pz = 1 / (1 + math.exp(-(sum(a * c for a, c in zip(w, xi)) + b)))
            for k in range(len(w)):
                gw[k] += (pz - yi) * xi[k]
            gb += pz - yi
        w = [a - lr * g / len(X) for a, g in zip(w, gw)]
        b -= lr * gb / len(X)
    return {"w": w, "b": b, "mean": mean, "sd": sd, "features": FEATURES}


def score(model, row):
    z = sum(w * ((row[f] - m) / s) for w, f, m, s in zip(model["w"], model["features"], model["mean"], model["sd"])) + model["b"]
    return 1 / (1 + math.exp(-z))


def auc(model, rows):
    pos = [score(model, r) for r in rows if r["fraud"] == 1]
    neg = [score(model, r) for r in rows if r["fraud"] == 0]
    wins = sum((p_ > n) + 0.5 * (p_ == n) for p_ in pos for n in neg)
    return wins / (len(pos) * len(neg))


def psi(expected, actual, bins=10):
    """Population stability index of one feature between two batches."""
    qs = sorted(expected)
    edges = [qs[int(len(qs) * k / bins)] for k in range(1, bins)]
    def dist(vals):
        c = [0] * bins
        for v in vals:
            c[sum(v > e for e in edges)] += 1
        return [max(x / len(vals), 1e-4) for x in c]
    e, a = dist(expected), dist(actual)
    return sum((ai - ei) * math.log(ai / ei) for ei, ai in zip(e, a))


# ---------- tracking and registry
def track(name, params, metrics, model, data_hash):
    run = {"run": name, "time": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "params": params, "metrics": metrics, "data_sha256": data_hash}
    os.makedirs(p("runs"), exist_ok=True)
    dump(p("runs", name + ".json"), run)
    dump(p("runs", name + ".model.json"), model)
    return run


def registry():
    return load(p("registry.json")) if os.path.exists(p("registry.json")) else {"versions": []}


def register(run, stage="staging"):
    reg = registry()
    v = len(reg["versions"]) + 1
    reg["versions"].append({"version": v, "run": run["run"], "auc": run["metrics"]["auc"], "stage": stage})
    dump(p("registry.json"), reg)
    return v


def promote(v):
    reg = registry()
    for x in reg["versions"]:
        if x["stage"] == "production":
            x["stage"] = "archived"
        if x["version"] == v:
            x["stage"] = "production"
    dump(p("registry.json"), reg)


def production():
    reg = registry()
    prod = [x for x in reg["versions"] if x["stage"] == "production"]
    return (prod[0], load(p("runs", prod[0]["run"] + ".model.json"))) if prod else (None, None)


def sha(rows): return hashlib.sha256(json.dumps(rows, sort_keys=True).encode()).hexdigest()[:16]


# ---------- commands
def setup():
    os.makedirs(p("data"), exist_ok=True)
    print("== 1. Dataset: 3,000 labelled payments for training, 1,000 for testing")
    train, test = make_batch(3000, 11), make_batch(1000, 12)
    dump(p("data", "train.json"), train); dump(p("data", "test.json"), test)
    print(f"  fraud rate: train {sum(r['fraud'] for r in train) / len(train):.3f}, test {sum(r['fraud'] for r in test) / len(test):.3f}")
    print("== 2. Data contract: a batch with broken rows is rejected before training")
    broken = make_batch(200, 13); broken[5]["amount"] = -40; broken[9]["hour"] = 31; broken[17]["fraud"] = None
    dump(p("data", "batch-broken.json"), broken)
    errs = contract_errors(broken)
    print(f"  batch-broken.json: {len(errs)} contract violations, rejected; first: {errs[0]}")
    print("== 3. Train, validate against the gate, track, register, deploy")
    model = fit(train)
    a = round(auc(model, test), 4)
    run = track("run-001", {"lr": 0.3, "epochs": 300, "features": FEATURES}, {"auc": a}, model, sha(train))
    v = register(run)
    print(f"  run-001: AUC {a} (gate: at least {GATE['min_auc']}) -> registered as version {v}")
    if a >= GATE["min_auc"]:
        promote(v)
        print(f"  version {v} promoted to production")
    print("== 4. A new month of traffic arrives, and it has shifted (larger amounts)")
    dump(p("data", "live.json"), make_batch(1500, 14, shift=0.9))
    print("  data/live.json written; verify.py measures drift on it")


def verify():
    print("== Dataset and contract")
    train, test, live = load(p("data", "train.json")), load(p("data", "test.json")), load(p("data", "live.json"))
    (ok if not contract_errors(train) else bad)("the training data meets the contract")
    (ok if len(contract_errors(load(p("data", "batch-broken.json")))) == 3 else bad)("the broken batch shows exactly its 3 violations")
    print("== Tracking and registry")
    run1 = load(p("runs", "run-001.json"))
    (ok if run1["data_sha256"] == sha(train) else bad)("run-001 records the hash of the exact data it was trained on")
    pv, pm = production()
    (ok if pv and pv["version"] == 1 else bad)("version 1 is in production")
    if not pm:
        print("\nRESULT: no model passed the validation gate, so nothing is in production; stopping")
        sys.exit(1)
    a1 = auc(pm, test)
    (ok if a1 >= GATE["min_auc"] else bad)(f"production AUC {a1:.3f} meets the gate of {GATE['min_auc']}")
    print("== Serving: the production model scores a payment")
    s = score(pm, {"amount": 4200.0, "hour": 3, "new_device": 1, "country_risk": 0.9})
    t = score(pm, {"amount": 12.0, "hour": 14, "new_device": 0, "country_risk": 0.05})
    (ok if s > 0.5 > t else bad)(f"a risky payment scores {s:.2f}, an ordinary one {t:.2f}")
    print("== Drift on the new month")
    d = psi([r["amount"] for r in train], [r["amount"] for r in live])
    d2 = psi([r["hour"] for r in train], [r["hour"] for r in live])
    (ok if d > 0.25 else bad)(f"amount PSI {d:.2f} > 0.25: significant drift")
    (ok if d2 < 0.1 else bad)(f"hour PSI {d2:.2f} < 0.1: stable")
    a_live = auc(pm, live)
    print(f"  production AUC on the drifted month: {a_live:.3f} (was {a1:.3f})")
    print("== Retrain on recent data, compare in shadow, release by canary")
    recent = live[:1000]
    if contract_errors(recent):
        bad("the recent data breaks the contract")
    model2 = fit(train + recent, seed=2)
    holdout = live[1000:]
    a2, a_old = auc(model2, holdout), auc(pm, holdout)
    run2 = track("run-002", {"lr": 0.3, "epochs": 300, "data": "train + 1,000 recent"}, {"auc": round(a2, 4)}, model2, sha(train + recent))
    v2 = register(run2)
    (ok if a2 >= a_old - GATE["max_auc_drop"] else bad)(f"shadow on {len(holdout)} recent payments: new AUC {a2:.3f}, current {a_old:.3f}")
    agree = sum((score(model2, r) > 0.5) == (score(pm, r) > 0.5) for r in holdout) / len(holdout)
    print(f"  shadow: the two models agree on {agree:.1%} of decisions")
    r = random.Random(99)
    canary = [x for x in holdout if r.random() < 0.10]
    (ok if canary and auc(model2, canary + [x for x in holdout if x["fraud"]][:5]) > 0.5 else bad)(f"canary: version {v2} served {len(canary)} requests (10%) without errors")
    promote(v2)
    (ok if production()[0]["version"] == v2 else bad)(f"version {v2} promoted to production; version 1 archived")
    print("== Rollback")
    promote(1)
    pv, pm = production()
    (ok if pv["version"] == 1 and abs(auc(pm, test) - a1) < 1e-9 else bad)("rolled back to version 1: the same model and AUC as before")
    stages = {x["version"]: x["stage"] for x in registry()["versions"]}
    print("  registry:", stages)
    print("\nRESULT:", "all checks passed" if not FAILS else f"{len(FAILS)} check(s) failed")
    sys.exit(1 if FAILS else 0)


def reset():
    shutil.rmtree(WORK, ignore_errors=True)
    print(f"capstone 8 reset: {WORK} removed")


if __name__ == "__main__":
    cmd = sys.argv[1] if len(sys.argv) > 1 else ""
    if cmd != "reset":
        os.makedirs(WORK, exist_ok=True)
    {"setup": setup, "verify": verify, "reset": reset}.get(cmd, lambda: sys.exit(__doc__))()

If it fails

SymptomCauseFix
AUC differs slightly from this pageThe data is synthetic with a fixed seed, but floating-point summation order can differ between Python versions.The gate only needs it above the threshold.
"nothing in production"verify was run before setup.Run setup first, or use run.sh.

Every check prints PASS or FAIL with a reason, and the scripts keep their logs in the work folder under ~/labs/capstones; read them before running again.

Clean up

python3 08-mlops/mlops.py reset

It removes: ~/labs/capstones/mlops (data, runs, registry). Downloaded container images that are not named cap- stay in Docker's cache; remove them with docker image rm if you need the space.

In the cloud

Not run by this course. The local capstone above is the tested part. These are the managed services that do the same jobs on each provider; they cost money while they exist, and their names and prices change, so check the provider's current documentation before you build them. Use a separate learning account with a budget alert, as Start here explains.
ProviderEquivalent
AWSSageMaker Pipelines, Model Registry, shadow tests on endpoints, and Model Monitor for drift.
AzureAzure Machine Learning pipelines, the model registry, managed online endpoints with traffic split, and data drift monitors.
Google CloudVertex AI Pipelines, Model Registry, endpoint traffic split, and Model Monitoring.

How it is assessed

verify proves the build works. The rubric is for you, or a reviewer, to judge how well: aim for every row in Meets, then pick rows to take to Exceeds.

CriterionMeetsExceeds
DataBad batches are rejected by the contract.You can trace a model back to the exact data it was trained on.
ReleaseA model is promoted only through the gate.Shadow and canary results decide the promotion.
MonitoringDrift is detected per feature.Drift alerts link to a retraining run.
RecoveryYou can roll back to the previous model.The rollback is a registry change, without retraining.

Take it further

Then test what you know with the assessments.

Next capstone: Automated incident response with a human in charge. All capstones · Guided routes