CI/CD for ML: A Quality Gate That Blocks a Weaker Model, Even When Every Test Passes
A candidate model passes all 4 tests and beats the champion overall by one point, and the gate still blocks it, because new customers drop from 44.51% to 40.66%. The rules, the exit code, a pinned validation file and the CI job chain.
What you will learn
- Tell code tests apart from a model quality gate
- Write gate rules before the candidate arrives: a minimum overall gain and a maximum drop per group
- Return a non-zero exit code so a failing gate stops the CI job
- Protect the gate's data: pin the validation file with a hash and keep the final test set closed
Before you start
- CI with GitHub Actions
- Slice Evaluation and Fairness Checks
- Train-Test Split and Data Leakage
CI with GitHub Actions made every push run the tests. That checks the code. But a model can have perfect code and still be worse than the one you're running today. So in this article we put a quality gate on the model itself.
The idea is a contract: a few rules, written down before the candidate shows up. You'll see a candidate that passes every test, beats the champion overall, and still gets blocked.
Two words: champion and candidate
Training gives us a new model. We call it the candidate, and it wants to replace the champion, the model in use today. Tests check its code. The gate judges the model. Only once the gate says yes does it get packaged. (If you've used a model registry, the champion is the version the alias points at; see MLflow registry aliases.)
Check the jar, taste the sauce
Think of a restaurant that bottles its own sauce. Someone checks the jar: lid on, label straight, weight right. That's your tests, and they say nothing about what's inside. So someone also opens a jar and tastes it next to the batch they're selling today. That's the gate.
And one spoon isn't enough, because a batch can taste fine on top and be burnt at the bottom. So you taste in more than one place. In ML, those places are slices: groups of rows, like customer types.
All green, still worse
The project has a champion (logistic regression on five columns) and a candidate called lean, a smaller logistic regression that uses only two columns. The data is synthetic, customers we generated ourselves, with two groups: returning and new.
CANDIDATES = {
"champion": (LogisticRegression, FEATURES),
"boosted": (lambda: GradientBoostingClassifier(
random_state=0), FEATURES),
"lean": (LogisticRegression, ["x0", "x1"]),
}
Pytest says everything is fine:
.... [100%]
4 passed in 3.54s
Overall, the champion scores 75.73% accuracy and lean scores 76.73%. One point up. Now split it by group:
Returning customers go up to 81.71%. New customers go down, from 44.51% to 40.66%. In the validation set there are 1,318 returning customers and 182 new ones, about seven to one, so the big group hid the drop in the average. Every test was green, and the model is still worse for a whole group. (Scoring group by group is the idea behind slice evaluation; here it becomes a rule that can block a release.)
gate.py: the limits and the score
Here's the contract. The two limits are set before any candidate arrives:
MIN_GAIN = 0.005 # overall accuracy must rise by this
SLICE_DROP = 0.02 # no group may fall by more than this
def score(name):
model, cols = train(name)
df = load_validation()
hit = model.predict(df[cols]) == df["y"]
out = {"overall": round(float(hit.mean()), 4)}
for g, rows in df.groupby("group"):
out[g] = round(float(hit[rows.index].mean()), 4)
return out
MIN_GAIN: overall accuracy has to rise by at least half a point. SLICE_DROP: no group may fall by more than two points.
score trains the model and predicts on the validation set. hit is True or False for each row. Overall is the mean of the hits, and a short loop gives each group its own mean.
check() and the return code
def check(cand, champ):
fails = []
gain = round(cand["overall"] - champ["overall"], 4)
if gain < MIN_GAIN:
fails.append(f"overall gain {gain} < {MIN_GAIN}")
for g in ("returning", "new"):
drop = round(champ[g] - cand[g], 4)
if drop > SLICE_DROP:
fails.append(f"slice {g} fell by {drop}")
return fails
def main(name):
if digest(DATA / "validation.csv") != VALIDATION_SHA:
print("FAIL: validation set changed")
return 1
champ, cand = score("champion"), score(name)
print("champion", champ)
print("candidate", cand)
fails = check(cand, champ)
for f in fails:
print("FAIL:", f)
print("GATE", "FAILED" if fails else "PASSED")
return 1 if fails else 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1]))
check compares the two sets of scores and collects failures in a list. For lean, the gain is 0.01, which clears 0.005. Returning rose. New fell by 0.0385, more than 0.02, so a failure goes on the list.
python -m ci_gate.gate lean
champion {'overall': 0.7573, 'new': 0.4451, 'returning': 0.8005}
candidate {'overall': 0.7673, 'new': 0.4066, 'returning': 0.8171}
FAIL: slice new fell by 0.0385
GATE FAILED
main returns 1, and sys.exit(1) gives a non-zero exit code. In CI, a non-zero exit code fails the job. That's the whole trick: the gate speaks the same language as pytest.
Now the other candidate, boosted, through the same rules:
python -m ci_gate.gate boosted
champion {'overall': 0.7573, 'new': 0.4451, 'returning': 0.8005}
candidate {'overall': 0.822, 'new': 0.8516, 'returning': 0.8179}
GATE PASSED
Overall 82.2%, new customers 85.16%, the list stays empty, exit code 0. The data is synthetic, so that jump isn't a benchmark. Note that a gate on overall accuracy alone would have passed both candidates.
Protect the data the gate trusts
A gate is only as honest as its data. Drop a few hard rows from the validation file, and every candidate looks better, though no model improved. So gate.py pins that file with a fingerprint, a SHA-256 hash:
# pinned hash of data/validation.csv
VALIDATION_SHA = (
"6dfdd5a94b8a75415ff4d6f3043d96a9"
"d2a1bc28127fe0b955f666a34719d4a6")
Edit one cell in validation.csv, run boosted again, and the gate refuses before scoring anything:
FAIL: validation set changed
The final test set gets a different guard. If you keep tweaking against a score, you slowly fit that score, so the final test stays closed until the end:
def load_final_test():
"""Final test set. Release day only, never in CI."""
if os.environ.get("RELEASE_DAY") != "1":
raise PermissionError("final test is protected")
return make(1500, seed=3)
PermissionError: final test is protected
Anyone can set RELEASE_DAY, so it's a guard rail and not a lock. It stops accidents, not people.
Connect the gate to the build
Here's .github/workflows/ci.yml, with three jobs:
name: CI
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.13"
- run: pip install -e .[dev]
- run: pytest -q
gate:
needs: test
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.13"
- run: pip install -e .
- run: python -m ci_gate.gate boosted
package:
needs: gate
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.13"
- run: pip wheel . --no-deps -w dist
Gate needs test, and package needs gate. If the gate returns 1, package never starts. If it returns 0, package builds the wheel, ci_gate-0.1.0-py3-none-any.whl. GitHub Actions runs this on every push and pull request, and a failing gate shows up as a red cross, so nothing gets merged past it.
python:3.13-slim container: the tests (4 passed), the gate on boosted (GATE PASSED) and the wheel build.Common mistakes
- Treating green tests as a green light. Tests check the jar. Only the gate tastes the sauce.
- Gating on the average only. Both candidates here pass an overall-only rule. A drop for a small group hides inside the mean.
- Setting the limits after seeing the result. Then the rule bends to fit the candidate you wanted.
- An unguarded validation file. If it can change quietly, the gate can be passed quietly.
Recap
| Piece | In this project |
|---|---|
| Rules first | MIN_GAIN = 0.005, SLICE_DROP = 0.02 |
| Overall and every group | Lean: +0.01 overall, new customers −0.0385, GATE FAILED |
| Exit code | 1 fails the CI job, 0 lets package run |
| Pinned data | VALIDATION_SHA; any edit gives "validation set changed" |
| Closed final test | PermissionError unless RELEASE_DAY=1 |
Try it yourself: in gate.py, change SLICE_DROP to 0.05, run the gate on lean again, and read what it prints.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →CI with GitHub Actions: Run the Tests and Build the Docker Image on Every Push
Next →Which Cloud for What: AWS, Azure, Google Cloud, GPU Clouds, Edge and Platforms
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Python Virtual Environments: One Project, One Toolbox
Why every Python project gets its own virtual environment: two projects that need different versions of requests, python -m venv .venv, activation, pip install and the PyCharm setting that activates it for you.
Git and GitHub Fundamentals: Commits, Branches, Push and Pull
The Git you use every day, on a tiny hello-ml project: commits as save points, the staging area, a branch merged with a fast-forward, then push, clone, pull and pull requests with a teammate.
Testing a FastAPI App with pytest: Three Small Tests
A tiny FastAPI app with a Hello World route and a name route that refuses numbers, three pytest tests that check it, and what happens when the validation is deleted by mistake.
Config and Logging Instead of Hard-Coded Values in ML Training
Take the hard-coded values out of a car price training script: one config.toml read with tomllib, logging with levels and a run id on every line, and secrets read from the environment. Same RMSE, 2195, before and after.