Sub topic 1
Why CI for ML Is Different: Code, Data, and Models Can All Break
Prerequisites
This chapter assumes you can do the following:
- Write Python functions and run tests with pytest.
- Use Git branches and pull requests.
- Train and evaluate a model with scikit-learn or a similar library.
- Read a short YAML file for a CI service such as GitHub Actions.
You do not need to know any CI tooling in depth. Later chapters build each check in detail. This chapter gives the working model that those chapters share.
What continuous integration does
Continuous integration (CI) is the practice of merging changes often and running automated checks on every change. In a typical software project, a developer opens a pull request and the CI service runs the tests. If any test fails, the merge is blocked.
This works because conventional software is deterministic and fully described by its source code. The same commit, built in the same environment, gives the same behavior. A failing test points at a line of code that changed.
An ML project breaks that assumption. The behavior of the system depends on three things, and any of them can change without the others changing.
Three things that can break
An ML system is made of code, data, and a trained model. Each can fail on its own.
| Artifact | What it is | Example failure | Visible in a code diff? |
|---|---|---|---|
| Code | Feature, preprocessing, training, and serving code | A scaling function divides by zero when a median is 0 | Yes |
| Data | Training and evaluation datasets | A column changes type, or `age` contains `-1` | No |
| Model | The trained artifact produced from code and data | Accuracy drops from 0.91 to 0.80 after a refactor | No |
The last two rows are the reason ML needs its own CI practice. A pull request can leave the code almost untouched and still ruin the model, because a new data export has a different schema or the training configuration quietly changed.
Code failures
Code failures are the familiar kind. A preprocessing function raises an exception, returns the wrong shape, or mishandles an edge case. Ordinary unit tests catch these.
Data failures
Data failures are silent. A pipeline that reads a CSV file will usually run to the end even when the file is wrong. Typical problems include:
- A column is missing, renamed, or has a different dtype.
- Values fall outside a valid range, such as a negative age.
- The fraction of missing values rises sharply.
- Labels contain values the model was never designed for.
- The distribution of a feature shifts away from what the model was trained on.
No exception is raised in most of these cases. The model trains and produces numbers. Those numbers are simply worse, or wrong.
Model failures
A model can be wrong even when the code and data are both valid. Training is a stochastic process with many settings. Changing a library version, a random seed, a hyperparameter, or the order of rows can change the result. Failures here include:
- Predicted probabilities that do not sum to 1.
- Predictions that change when you only reorder the input rows.
- A metric that falls below an acceptable floor.
- A metric that is acceptable in absolute terms but clearly worse than the model currently in use.
How the failure modes differ from software bugs
Three properties make ML failures harder to catch than ordinary bugs.
- Failures are often silent. A bug in software usually produces an error or an obviously wrong output. A weak model produces plausible outputs. You only notice when you measure quality.
- Correctness is statistical. There is rarely one right answer for a given input. A model is judged by aggregate metrics over many examples, so tests compare numbers against thresholds instead of checking exact values.
- Results are not exactly repeatable by default. Random initialization, data shuffling, and floating-point differences across library versions mean two runs can differ. A test that is flaky for this reason trains the team to ignore failures.
These properties change what a test looks like. Instead of "this function returns 4", an ML test often says "this metric is at least 0.85" or "this set of rows has no values outside the range 0 to 120".
A layered view of ML CI
The practical response is to test each artifact separately and in order of cost. Cheap, fast checks run first and catch most problems. Expensive checks run later, or less often.
Each layer answers a different question.
- Code tests: Does this function do what we intend, including on bad input?
- Data tests: Is the data we are about to train on shaped and ranged the way the pipeline expects?
- Model tests: Does a small trained model behave sanely, with valid outputs and stable predictions?
- Quality gate: Is the candidate model good enough in absolute terms, and not meaningfully worse than the baseline?
The next chapter develops this strategy. Here, the point is that one test suite cannot cover all three artifacts with the same technique.
Seeing each layer in code
Each of the following examples is small on purpose. They show what "testing" means for each artifact.
A data check
A validation function returns a list of problems instead of raising on the first one. A test then asserts that a small committed sample file has none.
import pandas as pd
EXPECTED_DTYPES = {"age": "int64", "income": "float64", "label": "int64"}
def validate_training_data(df: pd.DataFrame, max_missing: float = 0.05) -> list[str]:
errors = []
for col, dtype in EXPECTED_DTYPES.items():
if col not in df.columns:
errors.append(f"missing column: {col}")
elif str(df[col].dtype) != dtype:
errors.append(f"{col}: expected {dtype}, got {df[col].dtype}")
if "age" in df.columns and not df["age"].between(0, 120).all():
errors.append("age outside [0, 120]")
if "label" in df.columns and not df["label"].isin([0, 1]).all():
errors.append("label contains values other than 0 and 1")
if len(df) > 0 and df.isna().mean().max() > max_missing:
errors.append(f"missing-value fraction above {max_missing}")
return errors
def test_sample_data_is_valid():
df = pd.read_csv("tests/data/sample.csv")
assert validate_training_data(df) == []Returning a list means one CI run reports every problem at once. A reviewer does not have to fix one error, push, and wait to find the next.
Note that this test checks a small sample committed to the repository. It proves the validation logic works. It does not prove that your full production dataset is clean. A later chapter covers running the same function against real data.
A model check
A behavioral test trains a tiny, seeded model and checks properties that must always hold, no matter how good the model is.
import numpy as np
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
def train_small_model():
X, y = make_classification(n_samples=200, n_features=5, random_state=0)
model = LogisticRegression(max_iter=200)
model.fit(X, y)
return model, X
def test_probabilities_are_valid():
model, X = train_small_model()
proba = model.predict_proba(X)
assert proba.shape == (len(X), 2)
assert np.allclose(proba.sum(axis=1), 1.0)
def test_predictions_do_not_depend_on_row_order():
model, X = train_small_model()
perm = np.random.default_rng(0).permutation(len(X))
assert np.array_equal(model.predict(X)[perm], model.predict(X[perm]))The random_state=0 arguments and the seeded generator make the test repeatable. Without them, the second test could pass on one run and fail on the next for reasons unrelated to your change.
A quality gate
A quality gate turns a metric into a pass or fail decision. This one uses two rules: an absolute floor, and a limit on how far the candidate may fall below the baseline.
def check_quality_gate(candidate: dict, baseline: dict,
min_accuracy: float = 0.85,
max_drop: float = 0.02) -> list[str]:
failures = []
acc = candidate["accuracy"]
if acc < min_accuracy:
failures.append(f"accuracy {acc:.3f} is below the minimum {min_accuracy:.3f}")
if baseline["accuracy"] - acc > max_drop:
failures.append(
f"accuracy dropped by more than {max_drop:.3f} "
f"(baseline {baseline['accuracy']:.3f}, candidate {acc:.3f})"
)
return failures
def test_gate_passes_for_small_change():
assert check_quality_gate({"accuracy": 0.90}, {"accuracy": 0.91}) == []
def test_gate_fails_for_regression():
assert len(check_quality_gate({"accuracy": 0.80}, {"accuracy": 0.91})) == 2Both rules are needed. The floor alone would allow a model to slip from 0.99 to 0.86 and still pass. The drop limit alone would allow a series of tiny drops to accumulate until the model is poor.
Wiring the layers into a workflow
The checks only help if they run automatically. A GitHub Actions workflow runs them on every pull request and on every push to main. The fast code and data tests run before the model tests, so a cheap failure stops the run early.
name: ml-ci
on:
pull_request:
push:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.11"
cache: pip
- run: pip install -r requirements.txt
- name: Code and data tests
run: pytest tests/unit tests/data -q
- name: Model tests
run: pytest tests/model -qTwo details matter. The cache: pip option reuses downloaded packages between runs, which keeps the run fast. The requirements.txt file should pin versions, so that the environment does not change between runs without a commit. Both topics get their own chapters.
Common errors when starting out
- Testing only code. Teams add unit tests for functions and assume the model is covered. A schema change in the data then passes CI and breaks training in production.
- Training the full model in CI. A multi-hour training job on every pull request makes developers avoid CI. Use small samples for pull requests and run heavy jobs on a schedule or on demand.
- Unseeded tests. Random behavior produces flaky failures. Seed every source of randomness and compare floating-point numbers with a tolerance such as
pytest.approx. - A threshold with no baseline. A fixed accuracy floor ignores whether the new model is worse than the current one. Compare against a stored baseline as well.
- Treating a green build as proof of quality. CI on a small sample shows that the pipeline is sound and the model behaves sanely. It does not show that the model is good on real data. Evaluation on a proper held-out set still has to happen.
What this tutorial covers next
The remaining chapters build the pieces in this order: the layered strategy, reproducibility, unit tests for feature code, data validation, drift checks, behavioral tests, quality gates, pipeline smoke tests, the full workflow, cost control, artifact versioning, and the handoff to delivery and retraining.
Exercise
A teammate changes only a data-export query. No Python file is modified, and all unit tests pass. Two days later the model's accuracy in production has dropped. Which layer of the ML CI strategy would have caught this before merge, and what would it have checked?
Show answer
The data validation layer. It would have checked the exported data against the expected schema (column names and dtypes), value ranges (for example age between 0 and 120), label values, and the fraction of missing values. Code unit tests could not catch it because no code changed. A metric quality gate on a model trained with the new data could also have caught the drop, but data validation is cheaper and points directly at the cause.
Exercise
A quality gate requires accuracy of at least 0.85. The current baseline model scores 0.93. A candidate scores 0.86. Does the floor alone pass it? Should the pipeline accept it, and what rule would change the decision?
Show answer
The floor alone passes it, since 0.86 is at least 0.85. But the candidate is 0.07 below the baseline, which is likely a serious regression. Adding a maximum-drop rule against the baseline, such as max_drop = 0.02, fails the candidate, because 0.93 - 0.86 = 0.07 exceeds 0.02.
Exercise
Why does the row-order invariance test use a fixed seed for both the dataset and the permutation, and what problem appears if it does not?
Show answer
Fixed seeds make the test repeatable, so the same inputs are used on every run. Without them, the dataset or the permutation could differ between runs, so a failure might come from the random draw and not from a real change. The test would become flaky, and the team would learn to ignore it.