Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 5 of 6 · Lab · 25 min · revision 2

Lab: Testing ML Code in CI and Choosing Retraining Triggers

Write the tests a training repository should run on every pull request (feature unit tests, a training smoke test on a 300-row sample, and an inference contract test against a committed schema), watch the contract test catch a dropped response field, implement and test a retraining policy that combines a schedule, new labelled data, drift and performance alerts with the label delay, and run the GitHub Actions job locally.

Contentsand lesson path

What you will learn

  • Run ML-specific tests in CI (feature unit tests, a training smoke test on a data sample, an inference contract test) and define retraining triggers: schedule, new data or a drift alert.

01. Goal and setup

The earlier lessons of this skill protect the pipeline from bad data and bad models. This lab protects it from bad code. A pull request that breaks a feature function, stops the model from learning or changes the response that other services read should fail in continuous integration (CI), the automatic test run on every pull request, long before a nightly training run or a customer finds the problem. CI tests for ML code have to be fast, so they test logic on small inputs and leave full training to the pipeline.

You build a small churn package with three kinds of test, then the logic that decides when to retrain, with its own tests. Finally you add a GitHub Actions workflow and run the same command locally. In terms of the MLOps maturity levels described by Google Cloud, level 0 is manual training from notebooks, level 1 adds an automated training pipeline, and level 2 adds CI and automated delivery of the pipeline code itself. This lab is a piece of level 2.

You need: Python 3.12. The pinned versions are in requirements.txt.

Project layout at the end of the lab
ml-ci-lab/
├── requirements.txt
├── pytest.ini
├── contract.json                 written in step 3, committed
├── what_if.py                    step 4: the policy on seven situations
├── churn/
│   ├── __init__.py
│   ├── data.py                   generated churn data with a seed
│   ├── features.py               step 1
│   ├── train.py                  step 2
│   ├── serve.py                  step 3: request and response schemas
│   └── triggers.py               step 4: retraining policy
├── tests/                        one test file per step
└── .github/workflows/ml-ci.yml   step 5
Terminal
mkdir ml-ci-lab && cd ml-ci-lab
mkdir -p churn tests .github/workflows && touch churn/__init__.py
python3.12 -m venv .venv && source .venv/bin/activate
Text · requirements.txt
numpy==2.5.5
pandas==3.1.1
scikit-learn==1.9.1
pydantic==2.14.3
pytest==9.2.0
Terminal
python -m pip install -r requirements.txt

pytest.ini lets the tests import the churn package from the project root. Every test command below writes the full pytest report to pytest.log and prints the exit code and the one-line result of each test, because the report also contains timings that change on every run.

Text · pytest.ini
[pytest]
pythonpath = .
testpaths = tests

02. Step 1: Feature unit tests

data.py generates labelled customers. features.py derives two features from raw columns: support calls per year and a flag for customers in their first three months. The same function runs inside the trained model, so training and serving compute features with one piece of code. A unit test checks one function on tiny, hand-made inputs whose correct output you know. Feature code is where edge cases hide: a customer who joined this month has a tenure of 0, and a missing support count must become 0 rather than spread NaN through the row. The last test also checks that the function does not change its input, a common source of hard-to-find bugs when a data frame is reused.

Python · churn/data.py
import numpy as np
import pandas as pd


def generate(n: int, seed: int = 0) -> pd.DataFrame:
    rng = np.random.default_rng(seed)
    tenure = rng.integers(0, 73, n)                     # 0 = joined this month
    calls = rng.poisson(1.2, n).astype(float)
    calls[rng.random(n) < 0.02] = np.nan                # the support system misses some
    fee = rng.normal(60, 18, n).clip(10).round(2)
    logit = -1.0 + 0.6 * np.nan_to_num(calls) - 0.04 * tenure + 0.02 * (fee - 60)
    return pd.DataFrame({
        "tenure_months": tenure, "monthly_fee": fee, "support_calls": calls,
        "plan": rng.choice(["basic", "standard", "premium"], n),
        "churned": (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)})
Python · churn/features.py
import numpy as np
import pandas as pd

FEATURES = ["tenure_months", "monthly_fee", "support_calls", "calls_per_year",
            "is_new", "plan"]


def add_features(df: pd.DataFrame) -> pd.DataFrame:
    """Derived features, computed the same way for training and for serving."""
    out = df.copy()
    out["support_calls"] = out["support_calls"].fillna(0)   # missing: none logged
    years = np.maximum(out["tenure_months"], 1) / 12           # no division by zero
    out["calls_per_year"] = (out["support_calls"] / years).round(3)
    out["is_new"] = (out["tenure_months"] < 3).astype(int)
    return out[FEATURES]
Python · tests/test_features.py
import numpy as np
import pandas as pd

from churn.features import FEATURES, add_features


def one(**overrides):
    row = {"tenure_months": 24, "monthly_fee": 50.0, "support_calls": 4.0,
           "plan": "basic"}
    return pd.DataFrame([{**row, **overrides}])


def test_calls_per_year_uses_tenure_in_years():
    assert add_features(one())["calls_per_year"].item() == 2.0     # 4 calls in 2 years


def test_brand_new_customer_does_not_divide_by_zero():
    out = add_features(one(tenure_months=0, support_calls=1.0))
    assert np.isfinite(out["calls_per_year"].item())
    assert out["is_new"].item() == 1


def test_missing_support_calls_count_as_zero():
    out = add_features(one(support_calls=np.nan))
    assert out["support_calls"].item() == 0
    assert out["calls_per_year"].item() == 0


def test_output_columns_and_input_untouched():
    raw = one(support_calls=np.nan)
    out = add_features(raw)
    assert list(out.columns) == FEATURES
    assert raw["support_calls"].isna().item()                  # no side effects
Terminal
python -m pytest -q -rA tests/test_features.py > pytest.log
echo "pytest exit code: $?"
grep -E "^(PASSED|FAILED|ERROR) " pytest.log
Expected output
pytest exit code: 0
PASSED tests/test_features.py::test_calls_per_year_uses_tenure_in_years
PASSED tests/test_features.py::test_brand_new_customer_does_not_divide_by_zero
PASSED tests/test_features.py::test_missing_support_calls_count_as_zero
PASSED tests/test_features.py::test_output_columns_and_input_untouched

03. Step 2: A training smoke test on a sample

train.py builds one scikit-learn pipeline from raw columns to probabilities: the feature function, scaling and encoding, and a logistic regression. A smoke test runs the real training code end to end on a small sample, here 300 rows, to show that it still works at all. It is not a quality test: the promotion gate of the previous lesson judges quality on real data. The smoke test asserts four things: training finishes within a time limit, every prediction is a probability, the model beats the base-rate baseline (always predicting the share of churners) on log loss, and the saved file loads back with identical predictions. The baseline check is what catches code that runs but learns nothing, such as labels that were shuffled or features that are all zero.

Python · churn/train.py
import sys

import joblib
from sklearn.compose import make_column_transformer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import FunctionTransformer, OneHotEncoder, StandardScaler

from churn.data import generate
from churn.features import add_features

NUMERIC = ["tenure_months", "monthly_fee", "support_calls", "calls_per_year", "is_new"]


def build():
    """One object from raw columns to probabilities: features, encoding, model."""
    encode = make_column_transformer((StandardScaler(), NUMERIC),
                                     (OneHotEncoder(handle_unknown="ignore"), ["plan"]))
    return make_pipeline(FunctionTransformer(add_features), encode,
                         LogisticRegression(max_iter=1000))


def train(df):
    return build().fit(df.drop(columns="churned"), df["churned"])


if __name__ == "__main__":
    out = sys.argv[1] if len(sys.argv) > 1 else "model.joblib"
    model = train(generate(5000, seed=1))
    joblib.dump(model, out)
    print("saved", out)
Python · tests/test_train_smoke.py
import time

import joblib
import numpy as np
from sklearn.metrics import log_loss

from churn.data import generate
from churn.train import train


def test_training_runs_learns_and_round_trips(tmp_path):
    sample = generate(300, seed=7)                      # small and fast on purpose
    start = time.perf_counter()
    model = train(sample)
    assert time.perf_counter() - start < 30             # catches a runaway loop

    X, y = sample.drop(columns="churned"), sample["churned"]
    p = model.predict_proba(X)[:, 1]
    assert p.shape == (300,) and np.all((p >= 0) & (p <= 1))
    prior = np.full(len(y), y.mean())                   # always predict the base rate
    assert log_loss(y, p) < log_loss(y, prior)          # the model learned something

    joblib.dump(model, tmp_path / "model.joblib")
    again = joblib.load(tmp_path / "model.joblib")
    assert np.array_equal(again.predict_proba(X), model.predict_proba(X))
Terminal
python -m pytest -q -rA tests/test_train_smoke.py > pytest.log
echo "pytest exit code: $?"
grep -E "^(PASSED|FAILED|ERROR) " pytest.log
Expected output
pytest exit code: 0
PASSED tests/test_train_smoke.py::test_training_runs_learns_and_round_trips

04. Step 3: An inference contract test

Other services call the model with a request and read its response. The shape of both is a contract: field names, types and allowed values that consumers rely on. serve.py describes them as Pydantic models, which validate data and can export a JSON Schema. --write-contract saves both schemas to contract.json; in a real repository you commit that file and change it only together with the consumers. The contract test compares the current schemas with the committed file, scores a real request end to end, and checks that impossible input is rejected. Comparing with a file matters: if a refactor changes the response model, its own output still validates against itself, so only a copy of what consumers agreed to can show the difference.

Python · churn/serve.py
import json
import sys
from typing import Literal

import pandas as pd
from pydantic import BaseModel, Field

MODEL_VERSION = "churn-v7"


class ScoreRequest(BaseModel):
    customer_id: str
    tenure_months: int = Field(ge=0, le=600)
    monthly_fee: float = Field(ge=0, le=500)
    support_calls: float | None = Field(default=None, ge=0)
    plan: Literal["basic", "standard", "premium"]


class ScoreResponse(BaseModel):
    customer_id: str
    churn_probability: float = Field(ge=0, le=1)
    model_version: str


def score(model, request: ScoreRequest) -> ScoreResponse:
    row = pd.DataFrame([request.model_dump(exclude={"customer_id"})])
    p = float(model.predict_proba(row)[0, 1])
    return ScoreResponse(customer_id=request.customer_id,
                         churn_probability=round(p, 4), model_version=MODEL_VERSION)


if __name__ == "__main__" and "--write-contract" in sys.argv:
    contract = {"request": ScoreRequest.model_json_schema(),
                "response": ScoreResponse.model_json_schema()}
    with open("contract.json", "w") as f:
        json.dump(contract, f, indent=1, sort_keys=True)
    print("wrote contract.json with", len(contract["response"]["properties"]),
          "response fields")
Python · tests/test_contract.py
import json

import pytest
from pydantic import ValidationError

from churn.data import generate
from churn.serve import ScoreRequest, ScoreResponse, score
from churn.train import train

CONTRACT = json.load(open("contract.json"))      # reviewed and committed with consumers


@pytest.mark.parametrize("name", ["request", "response"])
def test_schema_matches_contract(name):
    model = {"request": ScoreRequest, "response": ScoreResponse}[name]
    current, agreed = model.model_json_schema(), CONTRACT[name]
    missing = sorted(set(agreed["properties"]) - set(current["properties"]))
    added = sorted(set(current["properties"]) - set(agreed["properties"]))
    assert not missing, f"{name} lost fields that consumers rely on: {missing}"
    assert current == agreed, f"{name} schema changed; new fields: {added}"


def test_a_real_prediction_fits_the_contract():
    model = train(generate(300, seed=7))
    request = ScoreRequest(customer_id="c-1", tenure_months=2, monthly_fee=80.0,
                           support_calls=None, plan="premium")
    body = score(model, request).model_dump(mode="json")
    ScoreResponse.model_validate(body)                    # round-trips as JSON
    assert set(body) == set(CONTRACT["response"]["properties"])
    assert 0 <= body["churn_probability"] <= 1


def test_impossible_inputs_are_rejected():
    with pytest.raises(ValidationError):
        ScoreRequest(customer_id="c-2", tenure_months=-3, monthly_fee=50.0,
                     plan="basic")
Terminal
python -m churn.serve --write-contract
python -m pytest -q -rA tests/test_contract.py > pytest.log
echo "pytest exit code: $?"
grep -E "^(PASSED|FAILED|ERROR) " pytest.log
Expected output
wrote contract.json with 3 response fields
pytest exit code: 0
PASSED tests/test_contract.py::test_schema_matches_contract[request]
PASSED tests/test_contract.py::test_schema_matches_contract[response]
PASSED tests/test_contract.py::test_a_real_prediction_fits_the_contract
PASSED tests/test_contract.py::test_impossible_inputs_are_rejected

Now play the refactor that breaks a consumer: someone decides model_version is noise and deletes it from the response. The command keeps a copy of the file, deletes the line, runs the contract tests and puts the file back. In a Git repository you would undo the change with git restore churn/serve.py.

Terminal
cp churn/serve.py serve.py.bak
python -c "import pathlib as p; f = p.Path('churn/serve.py'); \
  f.write_text(f.read_text().replace('    model_version: str\n', ''))"
python -m pytest -q -rA tests/test_contract.py > pytest.log
echo "pytest exit code: $?"
grep -E "^(PASSED|FAILED|ERROR) |^E .*lost fields" pytest.log
mv serve.py.bak churn/serve.py
Expected output
pytest exit code: 1
E       AssertionError: response lost fields that consumers rely on: ['model_version']
PASSED tests/test_contract.py::test_schema_matches_contract[request]
PASSED tests/test_contract.py::test_impossible_inputs_are_rejected
FAILED tests/test_contract.py::test_schema_matches_contract[response] - Asser...
FAILED tests/test_contract.py::test_a_real_prediction_fits_the_contract - Ass...

Two tests fail and the first message names the missing field. The code itself raised no error: Pydantic quietly ignores the extra model_version argument in score, so without the contract test this change would have reached production and broken every dashboard that groups predictions by model version.

05. Step 4: A retraining policy you can test

A retraining trigger is a condition that starts the training pipeline. There are four common ones, and each answers a different risk. A schedule retrains at a fixed age; it is simple and works as a backstop when the other signals stay silent. New data retrains when enough new labelled rows have arrived to be worth it. A drift alert fires when input distributions move, for example a PSI above 0.2 from the monitoring job. A performance alert fires when the live metric falls, but it can only be computed on labels that have matured: churn is known 14 days after scoring, so performance always lags.

The label delay changes how drift should act. On the day drift starts, there are no labelled examples of the new behaviour yet, so retraining at once would teach the model mostly old patterns. The policy below therefore waits until 14 days of labels exist after the drift began. A cooldown stops a burst of signals from starting several runs in a row. Writing the policy as a pure function of its inputs makes it easy to unit test and to review.

Python · churn/triggers.py
from dataclasses import dataclass
from datetime import date


@dataclass(frozen=True)
class Policy:
    max_age_days: int = 45            # schedule: a backstop, even if all looks quiet
    min_new_rows: int = 25_000        # new labelled rows since the last training
    psi_alert: float = 0.2            # input drift, from the monitoring job
    max_auc_drop: float = 0.02        # on labels that have matured
    label_delay_days: int = 14        # churn is known 14 days after scoring
    cooldown_days: int = 3            # no retraining storms


@dataclass(frozen=True)
class Signals:
    today: date
    last_trained: date
    new_labelled_rows: int = 0
    psi: float = 0.0
    drift_since: date | None = None   # first day the PSI alert fired
    auc_drop: float | None = None     # None until labels for the new model mature


def decide(s: Signals, p: Policy = Policy()) -> tuple[bool, list[str]]:
    age = (s.today - s.last_trained).days
    if age < p.cooldown_days:
        return False, [f"cooldown: trained {age} days ago"]
    reasons, notes = [], []
    if s.auc_drop is not None and s.auc_drop > p.max_auc_drop:
        reasons.append(f"performance: AUC down {s.auc_drop:.3f} on matured labels")
    if age >= p.max_age_days:
        reasons.append(f"schedule: model is {age} days old")
    if s.new_labelled_rows >= p.min_new_rows:
        reasons.append(f"new data: {s.new_labelled_rows:,} labelled rows")
    if s.psi > p.psi_alert and s.drift_since is not None:
        waited = (s.today - s.drift_since).days
        if waited >= p.label_delay_days:
            reasons.append(f"drift: PSI {s.psi:.2f}, labels of shifted data ready")
        else:
            notes.append(f"drift: PSI {s.psi:.2f}, wait {p.label_delay_days - waited}"
                         " more days for labels")
    return bool(reasons), reasons + notes
Python · tests/test_triggers.py
from datetime import date, timedelta

from churn.triggers import Signals, decide

TRAINED = date(2026, 10, 1)


def on(days, **signals):
    return decide(Signals(today=TRAINED + timedelta(days), last_trained=TRAINED,
                          **signals))


def test_quiet_period_does_not_retrain():
    assert on(10) == (False, [])


def test_schedule_is_a_backstop():
    retrain, reasons = on(45)
    assert retrain and reasons[0].startswith("schedule")


def test_enough_new_labels_trigger_retraining():
    assert on(20, new_labelled_rows=25_000)[0]


def test_drift_waits_until_labels_of_the_shifted_data_exist():
    since = TRAINED + timedelta(10)
    assert not on(15, psi=0.31, drift_since=since)[0]          # 5 days of labels
    assert on(24, psi=0.31, drift_since=since)[0]              # 14 days


def test_performance_drop_on_matured_labels_triggers():
    assert on(20, auc_drop=0.04)[0]
    assert not on(20, auc_drop=0.01)[0]


def test_cooldown_blocks_a_second_run_right_after_training():
    assert on(2, new_labelled_rows=30_000) == (False, ["cooldown: trained 2 days ago"])
Python · what_if.py
from datetime import date, timedelta

from churn.triggers import Signals, decide

trained = date(2026, 10, 1)


def day(n):
    return trained + timedelta(n)


cases = {
    "quiet, day 10": Signals(day(10), trained, new_labelled_rows=8_000, psi=0.04),
    "day 45, nothing else": Signals(day(45), trained, new_labelled_rows=9_000),
    "new labels, day 33": Signals(day(33), trained, new_labelled_rows=26_400),
    "drift began day 30, now 35": Signals(day(35), trained, psi=0.31,
                                          drift_since=day(30)),
    "drift began day 30, now 44": Signals(day(44), trained, psi=0.31,
                                          drift_since=day(30)),
    "AUC down 0.04, day 20": Signals(day(20), trained, auc_drop=0.04),
    "new labels, day 2": Signals(day(2), trained, new_labelled_rows=30_000),
}
for name, signals in cases.items():
    retrain, reasons = decide(signals)
    print(f"{name:<27} {'RETRAIN' if retrain else 'wait':<8} {'; '.join(reasons)}")
Terminal
python -m pytest -q -rA tests/test_triggers.py > pytest.log
echo "pytest exit code: $?"
grep -E "^(PASSED|FAILED|ERROR) " pytest.log
python what_if.py
Expected output
pytest exit code: 0
PASSED tests/test_triggers.py::test_quiet_period_does_not_retrain
PASSED tests/test_triggers.py::test_schedule_is_a_backstop
PASSED tests/test_triggers.py::test_enough_new_labels_trigger_retraining
PASSED tests/test_triggers.py::test_drift_waits_until_labels_of_the_shifted_data_exist
PASSED tests/test_triggers.py::test_performance_drop_on_matured_labels_triggers
PASSED tests/test_triggers.py::test_cooldown_blocks_a_second_run_right_after_training
quiet, day 10               wait     
day 45, nothing else        RETRAIN  schedule: model is 45 days old
new labels, day 33          RETRAIN  new data: 26,400 labelled rows
drift began day 30, now 35  wait     drift: PSI 0.31, wait 9 more days for labels
drift began day 30, now 44  RETRAIN  drift: PSI 0.31, labels of shifted data ready
AUC down 0.04, day 20       RETRAIN  performance: AUC down 0.040 on matured labels
new labels, day 2           wait     cooldown: trained 2 days ago

Read the table as a review of the policy. Five days after drift began it waits, and says how long; on day 44 the labels of the shifted customers exist and it retrains. The performance alert on day 20 retrains at once because it is measured on real outcomes. Two days after training, even 30,000 new rows wait for the cooldown. Which signals deserve the most weight depends on the model: when labels arrive quickly and patterns move without warning, performance and drift alerts can carry most of the load with a schedule behind them; when labels take months, drift and a schedule are all you have for a long time. In production a small daily flow computes these signals and starts the training flow when decide returns True.

06. Step 5: The CI workflow, run locally

The workflow runs on every pull request and on pushes to main. It installs the pinned requirements and runs the same pytest command you have been using. The time limit stops a hung test from blocking other pull requests. Because the whole suite runs in seconds on small samples, it can stay on every pull request; slower checks, such as training on the full data, belong to the pipeline or to a nightly job. Save the file, then run exactly what CI runs.

YAML · .github/workflows/ml-ci.yml
name: ml-ci
on:
  pull_request:          # every pull request into the training repository
  push:
    branches: [main]
jobs:
  tests:
    runs-on: ubuntu-latest
    timeout-minutes: 15  # a smoke test that hangs must not block the queue
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-python@v7
        with:
          python-version: "3.12"
          cache: pip
      - run: python -m pip install -r requirements.txt
      - name: Feature unit tests, training smoke test, contract and trigger tests
        run: python -m pytest -q -rA
Terminal
python -m pytest -q -rA > pytest.log
echo "pytest exit code: $?"
echo "tests passed: $(grep -cE "^PASSED " pytest.log)"
Expected output
pytest exit code: 0
tests passed: 15

All 15 tests pass, so the pull request can merge. GitHub marks the check as failed whenever pytest exits with a non-zero code, which is exactly what the contract break in step 3 would have produced. Protect the main branch so that a failed check blocks the merge.

07. Check your understanding

Practice check · 3 questions

Tests and triggers

Use the code and outputs of this lab.

Q1. The smoke test asserts that the model’s log loss is below that of always predicting the base rate. Which failure does this catch that “training finished without an error” would miss?
Q2. In `what_if.py`, drift began on day 30 but the policy only retrains on day 44. Why not retrain on day 30?
Q3. Why does `test_schema_matches_contract` compare with a committed `contract.json` instead of only validating responses with `ScoreResponse`?
Practice only: not graded, not saved, not evidence.

08. Apply it

The practice project asks for CI on every pull request with feature unit tests and a training smoke test. Finish it in your own repository.

  1. Write unit tests for every derived feature, including the edge cases of your data (empty values, zeros, unseen categories).
  2. Add a smoke test that trains on a fixed sample, beats a baseline and round-trips the saved model, and a contract test against a committed schema.
  3. Write down your retraining policy with the label delay of your problem, implement it as a function, test each rule, and open a pull request that breaks one test on purpose to see the check fail.

09. Review prompt

Without looking back, name the three kinds of ML test that belong in CI and what each catches; explain why the smoke test compares with a base-rate baseline and why it runs on a small sample; say why the contract test reads a committed file; list the four retraining triggers and how the label delay affects the drift and performance triggers; and describe what separates MLOps levels 0, 1 and 2.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check