GyaanStack. Blog

Articles / mlopsmachine-learningpython

Auto-retrain an ML model when it drifts: a champion/challenger loop in Python

A retrain loop that watches labelled batches, catches drift with PSI and KS, retrains on a recent window and promotes only if the challenger wins.

By Raghunath · · 21 min read

A model that scored well at launch loses accuracy as the world moves away from its training data. The usual fix is a loop: watch the model on fresh labelled data, decide when it has degraded, train a replacement, and swap it in only if it is better. Most tutorials show that loop as one if accuracy < 0.8: retrain() and stop.

That version has four problems in production. Labels arrive late, so you find out about a drop weeks after it starts. A single bad week can trigger a retrain that was not needed. A broken upstream job can hand you garbage labels, and the retrain will learn from them. And the "is the new model better" check often compares the challenger's score on its own validation split with the champion's score on different data, which proves nothing.

This post builds a loop that handles all four, runs it on a 20-week synthetic stream with two kinds of drift and one poisoned batch, and shows the full log of what it decided and why. Charts and alerting for the same signals are covered in the model monitoring dashboard post. Here the focus is the decision logic that runs after an alert.

The loop#

            every week
                |
   new batch X arrives (no labels yet)
                |
     champion scores X  -----------------> predictions served
                |
     drift check: PSI / KS vs reference --> DRIFT-ALERT (early warning only)
                |
   labels for week t-2 arrive
                |
     quality gate on (X, y) --- fail ---> reject batch, never train on it
                | pass
     live AUC of what was served
                |
     2 breaches in a row?  (AUC drop or PSI on labelled data)
                | yes
     train challenger on last 4 clean weeks
                |
     champion vs challenger on the SAME newest clean week
     (paired bootstrap)
                |
     gain >= 0.01 and wins >= 95%? --- no --> keep champion
                | yes
     register v(n+1), move production pointer
                |
     next labelled week: new vs old --- old better by 0.02 --> rollback

Two rules shape the design. Drift on unlabelled inputs raises an alert but does not retrain anything by itself, because input drift does not always hurt the model. Retraining and deployment are separate decisions: a finished training run is a candidate, nothing more.

A stream with drift baked in#

The stream produces one batch of 600 rows per week with five features. The label comes from a logistic rule over those features. Two things change over time:

  • From week 6, feature x1 shifts right by 0.8. The label rule stays the same. This is covariate shift: the inputs look different, but a correctly specified model keeps working.
  • From week 10, the label rule itself changes over three weeks. x2 stops mattering, x3 flips sign, and x4, which was noise, becomes predictive. Input distributions stay the same. This is concept drift, and input drift detectors cannot see it.

In week 15 a simulated pipeline bug writes every label as 0.

"""Synthetic production stream: one batch per week, with drift baked in."""
import numpy as np

N_FEATURES = 5
FEATURES = [f"x{i}" for i in range(N_FEATURES)]


def make_batch(week, n=600, seed=0):
    rng = np.random.default_rng(seed * 1000 + week)
    X = rng.normal(0.0, 1.0, size=(n, N_FEATURES))

    # Covariate shift from week 6: x1 moves right. The label rule is unchanged,
    # so a correct model should cope. Drift detectors will still fire.
    if week >= 6:
        X[:, 1] += 0.8

    # Concept drift from week 10: x2 stops helping and x3 flips sign, ramping
    # over three weeks. Input distributions do not change at all.
    w = np.array([1.2, 0.8, 1.0, 0.9, 0.0])
    ramp = min(max(week - 9, 0) / 3.0, 1.0)
    w[2] = 1.0 * (1 - ramp)
    w[3] = 0.9 * (1 - 2 * ramp)
    w[4] = 1.1 * ramp  # a feature that used to be noise starts to matter

    logit = X @ w - 0.8
    p = 1 / (1 + np.exp(-logit))
    y = (rng.random(n) < p).astype(int)

    # Week 15: an upstream join bug writes every label as 0.
    if week == 15:
        y[:] = 0
    return X, y

In a real system make_batch is a query against your feature store or warehouse, and the labels come from a separate join that lands later (chargebacks, churn flags, delivery outcomes). Keep those two arrivals separate in code, as the pipeline below does, or you will end up evaluating on labels you would not have had at decision time.

Drift statistics and the quality gate#

Two drift measures run on every feature against a reference sample, which starts as the training data.

The Population Stability Index (PSI) bins the reference into deciles, measures what share of the new batch lands in each bin, and sums (new - ref) * ln(new / ref) over bins. The common rule of thumb reads below 0.10 as little shift and above 0.25 as significant. Those cut-offs are folklore from credit risk; Yurdakul's thesis on PSI points out that they are used without any stated Type I or Type II error rate and studies how PSI behaves with sample size. Treat 0.25 as a starting point and tune it on your own history.

The two-sample Kolmogorov-Smirnov test, scipy.stats.ks_2samp, gives the largest gap between the two empirical CDFs plus a p-value. With thousands of rows the p-value goes to zero for shifts nobody cares about, so the loop logs the statistic and does not alert on the p-value.

The quality gate runs on each labelled batch before it is used for anything. It returns a list of problems, and any problem means the batch is dropped from both monitoring and training.

"""Drift statistics and the data quality gate."""
import numpy as np
from scipy.stats import ks_2samp


def psi(reference, current, bins=10, eps=1e-4):
    """Population Stability Index of one feature, bins cut on reference quantiles."""
    edges = np.quantile(reference, np.linspace(0, 1, bins + 1))
    edges[0], edges[-1] = -np.inf, np.inf
    ref_frac = np.histogram(reference, edges)[0] / len(reference)
    cur_frac = np.histogram(current, edges)[0] / len(current)
    ref_frac = np.clip(ref_frac, eps, None)
    cur_frac = np.clip(cur_frac, eps, None)
    return float(np.sum((cur_frac - ref_frac) * np.log(cur_frac / ref_frac)))


def drift_report(X_ref, X_cur):
    """Worst feature by PSI, plus its two-sample KS statistic and p-value."""
    scores = [psi(X_ref[:, j], X_cur[:, j]) for j in range(X_ref.shape[1])]
    j = int(np.argmax(scores))
    ks = ks_2samp(X_ref[:, j], X_cur[:, j])
    return {"feature": j, "psi": scores[j], "ks": float(ks.statistic), "ks_p": float(ks.pvalue)}


def quality_gate(X, y, ref_pos_rate, min_rows=300, rate_band=(0.5, 1.6)):
    """Return a list of problems. Empty list means the batch may be used."""
    problems = []
    if len(y) < min_rows:
        problems.append(f"only {len(y)} rows")
    if np.isnan(X).any():
        problems.append("NaN in features")
    if len(np.unique(y)) < 2:
        problems.append("labels are a single class")
    rate = y.mean()
    lo, hi = rate_band[0] * ref_pos_rate, rate_band[1] * ref_pos_rate
    if not lo <= rate <= hi:
        problems.append(f"positive rate {rate:.3f} outside [{lo:.3f}, {hi:.3f}]")
    return problems

The positive-rate band is wide on purpose. Real concept drift can move the base rate, and a band that is too tight will reject the very weeks you need to learn from. Row counts, nulls and a single-class check catch most broken joins. Add schema and range checks for your own features.

A registry you can roll back#

Rollback is only cheap if old versions are never overwritten. The registry below writes each model to its own immutable file and keeps a small JSON pointer that says which version serves traffic, plus the history of promotions. Rolling back moves the pointer one step back. MLflow's model registry works the same way at larger scale: you assign an alias such as champion to a version and update serving by reassigning the alias.

"""A tiny file-based model registry: immutable versions plus a movable pointer."""
import json
from pathlib import Path

import joblib


class Registry:
    def __init__(self, root):
        self.root = Path(root)
        self.root.mkdir(parents=True, exist_ok=True)
        self.pointer = self.root / "production.json"

    def register(self, model, meta):
        version = len(list(self.root.glob("v*.joblib"))) + 1
        joblib.dump(model, self.root / f"v{version}.joblib")
        (self.root / f"v{version}.json").write_text(json.dumps(meta, indent=2))
        return version

    def promote(self, version):
        history = self._read().get("history", [])
        history.append(version)
        self.pointer.write_text(json.dumps({"version": version, "history": history}))

    def rollback(self):
        state = self._read()
        if len(state["history"]) < 2:
            raise RuntimeError("nothing to roll back to")
        history = state["history"][:-1]
        self.pointer.write_text(json.dumps({"version": history[-1], "history": history}))
        return history[-1]

    def production(self):
        version = self._read()["version"]
        return version, joblib.load(self.root / f"v{version}.joblib")

    def load(self, version):
        return joblib.load(self.root / f"v{version}.joblib")

    def _read(self):
        return json.loads(self.pointer.read_text()) if self.pointer.exists() else {}

joblib files are pickles, and loading one can run arbitrary code. The scikit-learn persistence guide says to load only files you trust and suggests skops.io when you cannot. Inside your own registry bucket that is fine; never load a model file someone sent you.

The retrain loop#

The model is a scaled logistic regression, and the metric is ROC AUC from roc_auc_score. AUC ignores the decision threshold, which suits a stream where the base rate moves. Pick the metric your business reads: recall at a fixed precision for fraud, or log loss if downstream code uses the probabilities.

The settings at the top are the policy. Everything else is bookkeeping.

"""Champion/challenger retrain loop over a drifting weekly stream."""
import shutil

import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

from monitor import drift_report, quality_gate
from registry import Registry
from stream import make_batch

LABEL_DELAY = 2       # labels for week t land in week t + 2
WINDOW = 4            # clean labelled weeks used for training
AUC_DROP = 0.05       # performance alert: AUC below baseline minus this
PSI_ALERT = 0.25      # drift alert on the worst feature
CONSECUTIVE = 2       # breaches in a row before acting
PROMOTE_MARGIN = 0.01 # mean AUC gain the challenger needs on the holdout
ROLLBACK_MARGIN = 0.02
COOLDOWN = 2          # weeks between retrain attempts
FIRST_LIVE, LAST_WEEK = 4, 20


def train(X, y):
    return make_pipeline(StandardScaler(), LogisticRegression()).fit(X, y)


def auc(model, X, y):
    return roc_auc_score(y, model.predict_proba(X)[:, 1])


def paired_bootstrap(champ, challenger, X, y, n=500, seed=0):
    """Mean AUC gain of challenger over champion and share of resamples it wins."""
    rng = np.random.default_rng(seed)
    a, b = champ.predict_proba(X)[:, 1], challenger.predict_proba(X)[:, 1]
    gains = []
    for _ in range(n):
        i = rng.integers(0, len(y), len(y))
        gains.append(roc_auc_score(y[i], b[i]) - roc_auc_score(y[i], a[i]))
    gains = np.array(gains)
    return gains.mean(), (gains > 0).mean()


def stack(weeks, data):
    return (np.vstack([data[w][0] for w in weeks]),
            np.concatenate([data[w][1] for w in weeks]))


def run():
    shutil.rmtree("registry", ignore_errors=True)
    reg = Registry("registry")

    # Bootstrap: train v1 on weeks 0-2, hold out week 3.
    hist = {w: make_batch(w) for w in range(FIRST_LIVE)}
    X_tr, y_tr = stack([0, 1, 2], hist)
    v1 = train(X_tr, y_tr)
    baseline = auc(v1, *hist[3])
    reg.promote(reg.register(v1, {"trained_on": [0, 1, 2], "holdout_auc": baseline}))
    X_ref, ref_pos = stack([0, 1, 2, 3], hist)[0], stack([0, 1, 2, 3], hist)[1].mean()
    print(f"bootstrap v1 holdout AUC={baseline:.3f}  ref positive rate={ref_pos:.3f}")

    clean = dict(hist)          # labelled batches that passed the gate
    arrived = {}                # week -> (X, true y kept aside until labels land)
    served = {}                 # week -> (version, scores)
    drift = {}                  # week -> drift report at arrival time
    perf_breach, drift_breach = [], []
    last_attempt, watch = -99, None

    for week in range(FIRST_LIVE, LAST_WEEK):
        X, y = make_batch(week)
        arrived[week] = (X, y)
        version, model = reg.production()
        served[week] = (version, model.predict_proba(X)[:, 1])
        drift[week] = d = drift_report(X_ref, X)
        line = f"wk{week:02d} serve v{version} | psi[x{d['feature']}]={d['psi']:.2f} ks={d['ks']:.2f}"
        if d["psi"] >= PSI_ALERT:
            line += " DRIFT-ALERT"

        lw = week - LABEL_DELAY
        if lw < FIRST_LIVE:
            print(line + " | labels: none yet")
            continue
        Xl, yl = arrived[lw]
        problems = quality_gate(Xl, yl, ref_pos)
        if problems:
            print(line + f" | labels wk{lw:02d} REJECTED: {'; '.join(problems)}")
            continue
        clean[lw] = (Xl, yl)
        sv, scores = served[lw]
        live_auc = roc_auc_score(yl, scores)
        line += f" | labels wk{lw:02d} AUC(v{sv})={live_auc:.3f}"

        # Post-promotion watch: compare new champion with the one it replaced.
        if watch and sv == watch["new"]:
            old_auc = auc(reg.load(watch["old"]), Xl, yl)
            if old_auc - live_auc > ROLLBACK_MARGIN:
                back = reg.rollback()
                line += f" ROLLBACK to v{back} (old {old_auc:.3f})"
            else:
                line += f" watch ok vs v{watch['old']} {old_auc:.3f}"
            watch = None

        perf_breach.append(live_auc < baseline - AUC_DROP)
        # Recompute drift against the current reference, which may have moved.
        drift_breach.append(drift_report(X_ref, Xl)["psi"] >= PSI_ALERT)
        perf_hit = len(perf_breach) >= CONSECUTIVE and all(perf_breach[-CONSECUTIVE:])
        drift_hit = len(drift_breach) >= CONSECUTIVE and all(drift_breach[-CONSECUTIVE:])
        print(line)
        if not (perf_hit or drift_hit) or week - last_attempt < COOLDOWN:
            continue

        # Retrain: recent clean window, newest clean week as holdout.
        last_attempt = week
        weeks = sorted(clean)[-(WINDOW + 1):]
        train_weeks, hold = weeks[:-1], weeks[-1]
        challenger = train(*stack(train_weeks, clean))
        champ_v, champ = reg.production()
        c_auc, ch_auc = auc(champ, *clean[hold]), auc(challenger, *clean[hold])
        reason = "perf" if perf_hit else "drift"
        msg = (f"      RETRAIN ({reason}) on wk{train_weeks[0]:02d}-{train_weeks[-1]:02d}, "
               f"holdout wk{hold:02d}: champion v{champ_v}={c_auc:.3f} challenger={ch_auc:.3f}")
        gain, win_rate = paired_bootstrap(champ, challenger, *clean[hold])
        msg += f" gain={gain:+.3f} wins={win_rate:.0%}"
        if gain >= PROMOTE_MARGIN and win_rate >= 0.95:
            new_v = reg.register(challenger, {"trained_on": train_weeks, "holdout_auc": ch_auc})
            reg.promote(new_v)
            watch = {"new": new_v, "old": champ_v}
            baseline = ch_auc
            print(msg + f" -> PROMOTE v{new_v}")
        else:
            print(msg + " -> KEEP champion")
        # Either way the recent window is the new normal for drift checks.
        X_ref = stack(train_weeks[-1:] + [hold], clean)[0]
        perf_breach, drift_breach = [], []


if __name__ == "__main__":
    run()

A few choices in there are deliberate.

The live AUC is computed from the scores that were served at the time, tagged with the version that served them. Re-scoring old batches with today's model would hide what users saw.

The holdout is the newest clean week, and both models are scored on it. A random split of the retrain window would leak future rows into training and test on data older than what the model will face next. The promotion check is a paired bootstrap: resample the holdout 500 times, compute both AUCs on each resample, and require a mean gain of at least 0.01 and a win in at least 95% of resamples. On 600 rows a single AUC moves by a couple of hundredths from noise alone, so a bare new > old comparison would promote coin flips.

After any retrain attempt, the drift reference moves to the two most recent clean weeks. If the champion survived a drift-triggered retrain, it has been checked on labelled data from the new distribution, and the alert has done its job. Without the reset, PSI stays high forever and the loop retrains every two weeks for nothing.

What the loop did over 20 weeks#

This is the unedited output, run with Python 3.15, scikit-learn 1.9.1, SciPy 1.18.1 and NumPy 2.5.5:

bootstrap v1 holdout AUC=0.867  ref positive rate=0.382
wk04 serve v1 | psi[x0]=0.03 ks=0.04 | labels: none yet
wk05 serve v1 | psi[x1]=0.02 ks=0.05 | labels: none yet
wk06 serve v1 | psi[x1]=0.66 ks=0.34 DRIFT-ALERT | labels wk04 AUC(v1)=0.832
wk07 serve v1 | psi[x1]=0.69 ks=0.34 DRIFT-ALERT | labels wk05 AUC(v1)=0.848
wk08 serve v1 | psi[x1]=0.59 ks=0.33 DRIFT-ALERT | labels wk06 AUC(v1)=0.864
wk09 serve v1 | psi[x1]=0.66 ks=0.33 DRIFT-ALERT | labels wk07 AUC(v1)=0.860
      RETRAIN (drift) on wk03-06, holdout wk07: champion v1=0.860 challenger=0.862 gain=+0.003 wins=95% -> KEEP champion
wk10 serve v1 | psi[x2]=0.05 ks=0.05 | labels wk08 AUC(v1)=0.869
wk11 serve v1 | psi[x3]=0.04 ks=0.07 | labels wk09 AUC(v1)=0.857
wk12 serve v1 | psi[x3]=0.04 ks=0.04 | labels wk10 AUC(v1)=0.790
wk13 serve v1 | psi[x2]=0.03 ks=0.03 | labels wk11 AUC(v1)=0.721
      RETRAIN (perf) on wk07-10, holdout wk11: champion v1=0.721 challenger=0.753 gain=+0.032 wins=100% -> PROMOTE v2
wk14 serve v2 | psi[x2]=0.03 ks=0.06 | labels wk12 AUC(v1)=0.585
wk15 serve v2 | psi[x2]=0.05 ks=0.05 | labels wk13 AUC(v1)=0.561
      RETRAIN (perf) on wk09-12, holdout wk13: champion v2=0.608 challenger=0.765 gain=+0.158 wins=100% -> PROMOTE v3
wk16 serve v3 | psi[x3]=0.03 ks=0.04 | labels wk14 AUC(v2)=0.633
wk17 serve v3 | psi[x4]=0.02 ks=0.04 | labels wk15 REJECTED: labels are a single class; positive rate 0.000 outside [0.191, 0.611]
wk18 serve v3 | psi[x0]=0.05 ks=0.04 | labels wk16 AUC(v3)=0.785 watch ok vs v2 0.628
wk19 serve v3 | psi[x0]=0.02 ks=0.04 | labels wk17 AUC(v3)=0.786

Weeks 6 to 9 are the covariate shift. PSI on x1 jumps to 0.66 and KS to 0.34 the moment the shift starts, so the alert fires at once. AUC on the labelled weeks stays between 0.86 and 0.87, the same as before. Once two labelled weeks are drifted, the loop retrains, and the challenger is better by 0.003 AUC. It wins 95% of resamples, so a "strictly better" rule would have promoted it, but the gain is below the 0.01 margin and the champion stays. That is the right call: the label rule did not change, so the old model was still correct, and a needless swap would add deployment risk for no gain.

Weeks 10 to 16 are the concept drift. PSI never goes above 0.05 because the inputs did not change. Only the performance signal catches this. AUC for week 10 is 0.790, and the loop does not learn that until week 12 because of the two-week label delay. Week 11 at 0.721 is the second breach, and the retrain fires in week 13. The new model v2 beats v1 on the week 11 holdout (0.753 against 0.721) and is promoted, but it was trained on weeks 7 to 10, which are mostly pre-drift data. By week 13 the rule has fully flipped and v2 scores only 0.608. The next retrain, on weeks 9 to 12, produces v3 at 0.765, and v3 holds 0.785 on week 16.

The rule started changing in week 10 and a good model was serving in week 16. Two of those weeks are pure label delay, one is the "two breaches in a row" rule, and the rest is the window still holding old data. You can shorten each part, with a smaller window, a single-breach trigger for large drops, or proxy labels that arrive sooner, and each one makes false alarms more likely.

Week 15 carries the bad labels. The gate rejects the all-zero batch when its labels land in week 17. It never enters the monitoring numbers or any training window.

The rollback watch ran once, in week 18, and v3 beat v2 by a wide margin (0.785 against 0.628), so nothing rolled back. The v2 watch never ran because v3 replaced v2 before any week served by v2 got its labels. If your retrains can come faster than your label delay, that gap is real and worth an alert of its own.

Testing the guard rails#

The run above shows the happy path for rollback. The tests force the other cases:

"""Checks for the three guard rails: quality gate, poisoned retrain, rollback."""

import numpy as np

from monitor import psi, quality_gate
from pipeline import auc, stack, train
from registry import Registry
from stream import make_batch


def test_psi_is_near_zero_for_same_distribution():
    rng = np.random.default_rng(1)
    assert psi(rng.normal(size=5000), rng.normal(size=5000)) < 0.02


def test_gate_rejects_all_zero_labels():
    X, y = make_batch(15)
    assert "labels are a single class" in quality_gate(X, y, ref_pos_rate=0.38)


def test_poisoned_week_hurts_challenger():
    data = {w: make_batch(w) for w in range(12, 18)}
    good = train(*stack([12, 13, 14, 16], data))
    bad = train(*stack([12, 13, 14, 15], data))  # week 15 has every label = 0
    X_hold, y_hold = data[17]
    print(f"\nclean window AUC={auc(good, X_hold, y_hold):.3f} "
          f"poisoned window AUC={auc(bad, X_hold, y_hold):.3f}")
    print(f"mean predicted P(y=1): clean={good.predict_proba(X_hold)[:, 1].mean():.3f} "
          f"poisoned={bad.predict_proba(X_hold)[:, 1].mean():.3f} true rate={y_hold.mean():.3f}")
    assert bad.predict_proba(X_hold)[:, 1].mean() < good.predict_proba(X_hold)[:, 1].mean()


def test_rollback_restores_previous_version(tmp_path):
    reg = Registry(tmp_path / "reg")
    X, y = make_batch(0)
    reg.promote(reg.register(train(X, y), {}))
    reg.promote(reg.register(train(X, y), {}))
    assert reg.production()[0] == 2
    assert reg.rollback() == 1
    assert reg.production()[0] == 1
$ python -m pytest -q -s test_guards.py
..
clean window AUC=0.847 poisoned window AUC=0.847
mean predicted P(y=1): clean=0.446 poisoned=0.339 true rate=0.458
..
4 passed in 6.04s

The poisoned-window result is the reason the gate exists. Training on the all-zero week leaves AUC unchanged at 0.847, because the bad labels mostly shift the intercept and the ranking of rows stays the same. The promotion check would have passed it. But the mean predicted probability drops from 0.446 to 0.339 against a true rate of 0.458, so any downstream rule that thresholds the probability, such as "review if P > 0.4", would quietly change behaviour. A ranking metric cannot see a calibration break. If your consumers use probabilities, add a calibration check to the promotion gate as well (the scikit-learn calibration guide covers reliability curves and Brier score).

Setting the thresholds#

None of the numbers in the config are universal. A way to set them from your own data:

  1. Replay the last year of labelled history through the loop with alerts logged but no actions. Count how often each trigger would have fired and how many of those weeks had a real problem.
  2. Set AUC_DROP from week-to-week noise. Compute the spread of weekly AUC during a stable quarter; a drop of two to three times that spread is a reasonable first trigger.
  3. Set PROMOTE_MARGIN to the smallest gain that justifies a deployment. A model swap costs review time and carries risk, so "better by 0.001" is not worth it.
  4. Keep an absolute floor next to the relative trigger. This loop resets baseline to each new champion's holdout AUC, so a weak champion lowers the bar for the next alert. A fixed floor, such as "page a human if AUC < 0.70 regardless", stops that slide.
  5. Put a human on drift-only triggers at first. Covariate shift often has a business cause (a new market, a pricing change) that someone should know about even when the model copes.

Google's MLOps architecture guide lists the same set of retrain triggers (on a schedule, on new data, on performance degradation and on distribution change) and treats automated retraining as a pipeline you deploy and test like any other code. Its section on continuous training is a good checklist for what this script leaves out: orchestration, feature store reads, and metadata tracking for every run. Rules of Machine Learning has a rule for the related question: know how fast your model goes stale (Rule #8, freshness requirements).

What changes in production#

The script runs in one process and holds data in dicts. A real deployment splits it:

  • The weekly loop becomes a scheduled job in Airflow, Dagster or a cron container, with each step (gate, evaluate, train, compare, promote) as a separate task so a failure stops at a named step.
  • The registry becomes MLflow or your cloud's registry, and "promote" becomes an alias change that serving picks up without a redeploy.
  • The rollback watch runs on a shadow or canary slice before full traffic, so a bad model meets 5% of requests, not all of them.
  • Every decision line in the log above becomes a row in a table: week, versions, metrics, trigger, outcome. When someone asks why the model changed on a Tuesday, that table answers it.

If you are moving from classic models to LLM systems, the same champion/challenger idea applies to prompts and model versions; MLOps vs LLMOps covers what carries over, and CI/CD for LLM applications shows the gate as a pipeline step.

Sources#

Found this useful? You can buy me a coffee or support with any amount. It pays for hosting and keeps new articles coming.