Sub topic 16
Running checks automatically
This chapter assumes you have the layout, config loading, seeding, tests, and pinned environment from the earlier chapters. You should also know basic Git and be able to read a YAML file. The goal is to run those checks on every change without relying on anyone to remember them.
Why automate checks
A test suite only helps if it runs. In a machine learning project, people skip checks for predictable reasons: training takes a long time, the environment on one laptop differs from another, and a notebook edit "obviously" cannot break anything. Automated checks remove the decision. Every push runs the same commands in a clean environment, and the result is visible to everyone.
This ties back to reproducibility. A clean runner has only what your repository declares: the pinned dependencies, the package, and the config files. If a check passes there but fails on your laptop, or the reverse, you have found a hidden dependency, such as a package you installed by hand or a file that is not committed.
What belongs in an automated check
Continuous integration (CI) is a service that runs commands for you when code changes, usually on every push and pull request. Keep CI fast and deterministic. Sort checks by cost:
| Check | Typical cost | Runs on |
|---|---|---|
| Formatting and lint | Seconds | Every push |
| Unit tests (config loading, overrides, data functions) | Seconds to a minute | Every push |
| Smoke test of the pipeline on a tiny sample | A minute or two | Every pull request |
| Full training and evaluation | Minutes to hours | On demand or on a schedule |
Full training rarely belongs in the per-push path. It is slow, may need a GPU, and may need data that CI cannot reach. A smoke test gives most of the safety at a small fraction of the cost. It runs each stage end to end on a few rows and checks that the stages connect and produce their outputs.
The flow of a pipeline run
A typical CI job follows the same steps each time. It starts from a fresh machine, builds the environment from the pinned files, and runs the checks in order of cost, so cheap failures stop the job early.
A workflow file
GitHub Actions reads workflow files from .github/workflows/. Other services such as GitLab CI use different file names and syntax, but the structure is the same: a trigger, an environment, and a list of commands.
name: checks
on:
push:
branches: [main]
pull_request:
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.11"
cache: pip
- name: Install dependencies
run: |
pip install -r requirements.txt
pip install -e .
- name: Lint
run: ruff check src tests
- name: Unit tests
run: pytest -qThree details matter here:
pip install -r requirements.txtuses the pinned file from the environment chapter, so CI builds the same dependency set you do. If you install unpinned packages, CI results can change from one day to the next without any change in your code.pip install -e .installs your package fromsrc/. This checks that your imports work through the package and not through an accident of the current directory.cache: pipreuses downloaded wheels between runs, which shortens installs.
Making the tests fit CI
Tests that pass on your machine can fail in CI for reasons that have nothing to do with your code. These are the common causes.
Missing data
Data tracked with a tool like DVC is not in Git, so a fresh checkout has no data/raw. Tests that read it fail with FileNotFoundError. There are two fixes. Write unit tests so they build their own small inputs, as the override test in the earlier chapter does. For smoke tests, commit a tiny sample under tests/fixtures/, a few dozen rows that are enough to exercise the code.
Avoid giving CI broad credentials to pull the whole dataset just to run tests. If a job really needs remote data, give it read-only access to that storage and nothing more.
Hard-coded paths
A test that opens /home/me/project/data/train.csv fails everywhere except your machine. Use paths relative to the test file, or pytest's tmp_path fixture for files the test creates.
import yaml
from my_project.config import load_config
def test_load_config_from_file(tmp_path):
cfg_file = tmp_path / "train.yaml"
cfg_file.write_text(
yaml.safe_dump(
{
"data_path": "data/processed/train.csv",
"seed": 42,
"learning_rate": 0.001,
"batch_size": 32,
}
)
)
cfg = load_config(cfg_file, overrides=["batch_size=64"])
assert cfg.batch_size == 64
assert cfg.seed == 42This test needs no files from the repository. It writes a config to a temporary folder, loads it with an override, and checks that the typed value arrives as an integer.
Flaky randomness
A test that depends on random output can pass on one run and fail on the next. Call set_seed at the start of the test, or better, assert on properties that do not depend on the random draw, such as output shapes or that the loss is a finite number. Do not loosen a tolerance until a flaky test stops failing without understanding why it varied.
A smoke test for the pipeline
A smoke test runs the real stages on fixture data and checks that each one produced its output. Write it as a normal pytest test so it uses the same runner as everything else.
import subprocess
import sys
from pathlib import Path
def test_prepare_stage_runs(tmp_path):
fixture = Path("tests/fixtures/raw_sample.csv")
assert fixture.exists()
result = subprocess.run(
[sys.executable, "-c", "import my_project.data.prepare"],
capture_output=True,
text=True,
)
assert result.returncode == 0, result.stderrThis minimal version only confirms that the stage module imports cleanly in a fresh interpreter. That alone catches missing dependencies, syntax errors, and bad imports. As your stages accept input and output paths, extend it to run the stage on the fixture and assert that the expected file appears in tmp_path.
Checks that fit machine learning specifically
Beyond ordinary software checks, a few cheap ones guard against silent failures:
- Config validation. Load every file in
configs/in a test. A typo in a key then fails the job instead of a training run three hours later. The frozen dataclass raisesTypeErrorfor unknown or missing keys, so loading is the validation. - Pipeline definition. If you use DVC,
dvc dagordvc statuscan confirm that thedvc.yamlfile parses and its dependencies exist. - Output sanity. After a smoke run, assert that metrics are finite numbers and that the saved model file loads.
- Notebook hygiene. Strip notebook outputs before commit, or fail the check if outputs are present, so diffs stay readable and large embedded images do not enter history.
A test that loads every config looks like this:
from pathlib import Path
import pytest
from my_project.config import load_config
CONFIGS = sorted(Path("configs").glob("*.yaml"))
@pytest.mark.parametrize("path", CONFIGS, ids=lambda p: p.name)
def test_every_config_loads(path):
cfg = load_config(path)
assert cfg.batch_size > 0
assert cfg.learning_rate > 0Note that this only works while every file in configs/ has the training keys. If you add configs for other purposes, move them to a separate folder or filter the glob.
Failure modes and limits
- Slow CI gets ignored. When a job takes twenty minutes, people stop waiting for it. Keep the per-push path under a few minutes and move slow work to a schedule.
- Green does not mean correct. Passing tests show that the code runs and the contracts hold. They do not show that a model improved.
- Secrets in logs. CI logs are often visible to many people. Store credentials as encrypted secrets in the CI service, never in the workflow file, and avoid printing them.
- Drift between local and CI. If developers run different commands locally than CI runs, results diverge. Put the commands in one place, such as a
Makefiletarget or a documented script, and have CI call it. - Unpinned tools. Pin your linter version as well as your libraries. A new lint rule can fail your build with no change to your code.
Exercises
Exercise
A test reads data/raw/train.csv, which is tracked by DVC and not by Git. It passes locally and fails in CI with FileNotFoundError. Give two ways to fix it that do not involve giving CI access to the full dataset.
Show answer
Rewrite the test so it creates its own small input inside pytest's tmp_path, or commit a tiny sample file under tests/fixtures/ and point the test at it. Both keep the test independent of data that lives outside Git.
Exercise
Why does the workflow install dependencies from a pinned requirements.txt and run pip install -e .?
Show answer
The pinned file makes CI build the same dependency versions you use locally, so results do not change without a code change. The editable install checks that the code imports through the my_project package, as it would for any user, and not because of the current working directory.
Exercise
Your per-push CI job takes 40 minutes because it trains the full model. What should you change, and what do you give up?
Show answer
Run lint, unit tests, and a smoke test on a tiny fixture sample on every push, and move full training to a scheduled or manually triggered job. You give up immediate feedback on model quality for each push, which remains the job of evaluation and experiment tracking.