Sub topic 10
Putting It Together in a CI Workflow
Prerequisites for this chapter
This chapter assumes you can write pytest tests, open a pull request, and read a GitHub Actions YAML file. It also assumes you have met the three kinds of check from earlier chapters:
- Code tests for feature and preprocessing functions.
- Data validation for schema, ranges, and missing values.
- Model behavioral tests and a metric quality gate.
Here you wire those checks into one automated workflow that runs on every pull request.
What the workflow has to do
A CI workflow for an ML project is a contract with the reviewer. When the pull request shows green, the reviewer can assume four things:
- The code still does what its tests say.
- The data fixtures still satisfy the data contract.
- A small, seeded model still behaves sensibly.
- The candidate metrics have not regressed against the baseline.
A workflow that cannot back up those claims gives false confidence. A workflow that takes 40 minutes gets ignored or bypassed. Design for both: the checks must be meaningful, and the pull-request path must be fast.
Order checks by cost
Run cheap checks first so a typo fails in seconds instead of after a training run. Each stage of the pipeline below costs more than the one before it, and each runs only if the previous stage passed.
Two properties of this ordering matter:
- Failures are cheap to diagnose. A failure in the code tests points at code. A failure in the data tests points at a fixture or the data contract. You never have to guess which layer broke.
- Fast feedback comes first. Most pull requests change code, and most code mistakes show up in the first stage.
The baseline workflow
Start with the simplest version that implements this ordering. It runs on every pull request and on every push to main.
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 -qEach part of this file has a reason:
on: pull_requestandpushtomain. The pull-request run protects the branch before merge. The push run confirms that the merged result is also green, which matters because two individually green pull requests can still conflict in combination.python-version: "3.11". Pin an exact minor version. Floating-point behavior, library defaults, and random number streams can change between versions, and the tolerances in your tests assume one environment.cache: pip.setup-pythonrestores the pip download cache, keyed on your requirements files. Installs of scikit-learn and pandas become much faster on repeat runs.requirements.txt. The file must pin versions (scikit-learn==1.5.2, notscikit-learn). Otherwise a new library release can turn your CI red on a day when nobody touched the repository.- Two test steps in one job. Steps run in order and stop at the first failure by default. The code and data tests therefore act as a gate in front of the model tests.
The directory layout maps to the test layers, which makes the workflow readable:
| Directory | Contains | Typical runtime |
|---|---|---|
| `tests/unit` | Feature and preprocessing function tests | Seconds |
| `tests/data` | Validation of small committed sample files | Seconds |
| `tests/model` | Behavioral tests on a small seeded model | Seconds to a minute |
Running the quality gate as a CI step
The quality gate from the previous chapter is a function that returns a list of failure messages. CI needs a process that exits with a non-zero status when that list is not empty. A short script bridges the two. It assumes your gate function lives in ml_project/gates.py and that earlier steps wrote two JSON files with an accuracy key.
import argparse
import json
import sys
from pathlib import Path
from ml_project.gates import check_quality_gate
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--candidate", required=True)
parser.add_argument("--baseline", required=True)
args = parser.parse_args()
candidate = json.loads(Path(args.candidate).read_text())
baseline = json.loads(Path(args.baseline).read_text())
failures = check_quality_gate(candidate, baseline)
for message in failures:
print(f"GATE FAILURE: {message}")
if failures:
return 1
print("Quality gate passed")
return 0
if __name__ == "__main__":
sys.exit(main())Save it as scripts/check_gate.py. The printed messages appear in the CI log, so a reviewer sees "accuracy dropped by more than 0.020" instead of a bare "exit code 1".
A split workflow with a model job
Once you add a smoke training run and a gate, one job gets crowded. Splitting into two jobs gives a faster first signal and lets the heavier job reuse the lighter job's result through needs.
name: ml-ci
on:
pull_request:
push:
branches: [main]
concurrency:
group: ml-ci-${{ github.ref }}
cancel-in-progress: true
jobs:
fast:
runs-on: ubuntu-latest
timeout-minutes: 10
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
model:
needs: fast
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.11"
cache: pip
- run: pip install -r requirements.txt
- name: Model tests
run: pytest tests/model -q
- name: Smoke train on the sample data
run: python scripts/train.py --data tests/data/sample.csv --out metrics/candidate.json
- name: Quality gate
env:
PYTHONPATH: .
run: python scripts/check_gate.py --candidate metrics/candidate.json --baseline metrics/baseline.json
- name: Keep metrics for review
if: always()
uses: actions/upload-artifact@v4
with:
name: metrics
path: metrics/This version adds four things:
needs: fast. Themodeljob does not start untilfastsucceeds, so a broken data fixture never spends model minutes.concurrencywithcancel-in-progress. When someone pushes a second commit to the same branch, the run for the older commit is cancelled. You stop paying for results nobody will read.timeout-minutes. A hung training loop or a download that never finishes would otherwise run until the platform's default limit, which is several hours on GitHub-hosted runners. A tight timeout also acts as a performance alarm.if: always()on the artifact upload. The metrics file is most useful when the gate fails, because the reviewer can open it and see by how much. Withoutalways(), the upload step is skipped after a failure.
The script scripts/train.py is the project's own smoke training entry point. It must be seeded and must finish in well under a minute on the sample file. The baseline file metrics/baseline.json is a committed file here. Later chapters cover better ways to version it.
Making the green check mean something
A workflow file does not protect anything until the repository requires it.
- Enable branch protection on
mainand mark thefastandmodeljobs as required status checks. Otherwise a failing run is advisory. - Make sure the required job names stay stable. Renaming a job in YAML can leave the old name as a required check that never reports, which blocks every merge.
- Keep the baseline update in the same pull request as the change that justifies it. Then a reviewer sees a lower threshold or a new baseline as an explicit diff, instead of the gate being quietly relaxed.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Green locally, red in CI | Unpinned dependency, a different Python version, or a test that reads a file outside the repository | Pin versions in `requirements.txt`, match the Python version, and use only committed fixtures |
| Gate fails randomly on identical code | A missing seed in the training script, or an exact float comparison | Seed every source of randomness and compare with a tolerance |
| `ModuleNotFoundError` in the gate script | The repository root is not on the import path | Set `PYTHONPATH: .` for the step, or install the project with `pip install -e .` |
| Metrics artifact missing after a failure | The upload step was skipped | Add `if: always()` |
| Two runs for the same branch both finish | No `concurrency` group | Add a group and `cancel-in-progress: true` |
| Required check never reports and the merge is blocked | A job was renamed after it was marked required | Update the required checks in the branch protection settings |
What this workflow deliberately leaves out
The pull-request path runs only the layers that finish in minutes. Full retraining, large-data drift checks, and benchmark comparisons are too slow and too costly to run on every commit. They belong on a schedule or on demand, which the next chapter covers. A fast, trusted pull-request check and a slower, scheduled deep check complement each other.
Exercise
A teammate pushes three commits to a pull request within two minutes. Your workflow takes eight minutes per run. Which setting avoids paying for the first two runs, and why does the quality-gate step still need if: always() on the artifact upload that follows it?
Show answer
Add a concurrency group keyed on github.ref with cancel-in-progress: true, so the runs for the first two commits are cancelled when a newer commit arrives. The upload step needs if: always() because a failed gate step would otherwise skip every later step, and the metrics file is most useful to the reviewer exactly when the gate fails.
Exercise
The model job in the split workflow has needs: fast. A contributor changes only a data fixture and breaks the schema. Which job fails, and what does the repository avoid spending?
Show answer
The fast job fails at the data validation tests. The model job never starts, so the repository avoids the install, model test, smoke training, and gate time of the second job.