Sub topic 9
Smoke-Testing the Whole Pipeline on a Small Sample
Prerequisites
This chapter assumes you can write pytest tests and use fixtures such as tmp_path. It also assumes you have trained and evaluated a scikit-learn model. The earlier chapters on unit tests and data validation supply the pieces. Here you connect those pieces and run them in sequence.
What a smoke test is for
A pipeline smoke test runs the whole workflow once, from raw data to saved model and metrics, on a very small dataset. The name comes from hardware testing: you switch the device on and check that nothing starts smoking.
A smoke test does not judge model quality. A model trained on 80 rows will score poorly or erratically, and that is fine. The test answers one question: do all the stages still work together?
Unit tests and data validation cannot answer that question. Each of them looks at one part. Many real failures happen between parts:
| Failure | Unit tests | Data validation | Smoke test |
|---|---|---|---|
| A function returns the wrong value | Catches it | No | Sometimes |
| A column has the wrong type in the file | No | Catches it | Sometimes |
| The training step expects a column the preprocessing step renamed | No | No | Catches it |
| The saved model cannot be loaded again | No | No | Catches it |
| A config path or default argument is wrong | No | No | Catches it |
| A library upgrade changes an API the training script calls | Sometimes | No | Catches it |
The most useful rows are the ones where only the smoke test catches the problem. Each is an integration bug. The parts work alone and fail when connected.
Design the pipeline so it can be tested
A smoke test needs a single entry point that you can call from Python with explicit inputs and outputs. Avoid scripts that read hard-coded paths at import time. Three rules make a pipeline testable:
- Take the data path and output directory as arguments. The test can then point them at temporary files.
- Take the seed as an argument. The test can then repeat a run and compare.
- Return the metrics and write the artifacts. The test can then check both the return value and the files on disk.
If your training code is a long notebook or a script with no function to call, extract a run_pipeline function first. A thin command-line wrapper can call it. Production runs and smoke tests then use the same code path, which is the point of the test.
A working example
The module below loads a CSV, checks for required columns, splits the data, trains a scaled logistic regression, evaluates it, and saves the model and metrics. It is small, but it has the same stages as a real pipeline.
# pipeline.py
import json
from pathlib import Path
import joblib
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
FEATURES = ["age", "income"]
TARGET = "label"
def run_pipeline(data_path, output_dir, seed=0):
df = pd.read_csv(data_path)
missing = [c for c in FEATURES + [TARGET] if c not in df.columns]
if missing:
raise ValueError(f"missing columns: {missing}")
train, test = train_test_split(
df, test_size=0.25, random_state=seed, stratify=df[TARGET]
)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=200))
model.fit(train[FEATURES], train[TARGET])
accuracy = accuracy_score(test[TARGET], model.predict(test[FEATURES]))
output_dir = Path(output_dir)
output_dir.mkdir(parents=True, exist_ok=True)
joblib.dump(model, output_dir / "model.joblib")
metrics = {
"accuracy": float(accuracy),
"n_train": int(len(train)),
"n_test": int(len(test)),
}
(output_dir / "metrics.json").write_text(json.dumps(metrics))
return metricsThe smoke test builds its own tiny dataset in a fixture. Generating the data in code means the test needs no data file and cannot go stale, and the seed keeps it stable. The tests then check what the pipeline produced.
# tests/smoke/test_pipeline_smoke.py
import json
import math
import joblib
import numpy as np
import pandas as pd
import pytest
from pipeline import FEATURES, run_pipeline
@pytest.fixture
def small_csv(tmp_path):
rng = np.random.default_rng(0)
n = 80
age = rng.integers(18, 80, size=n)
income = rng.normal(50_000, 15_000, size=n)
label = (income + rng.normal(0, 5_000, size=n) > 50_000).astype(int)
path = tmp_path / "sample.csv"
pd.DataFrame({"age": age, "income": income, "label": label}).to_csv(
path, index=False
)
return path
def test_pipeline_runs_end_to_end(small_csv, tmp_path):
out = tmp_path / "out"
metrics = run_pipeline(small_csv, out, seed=0)
# Artifacts exist
assert (out / "model.joblib").exists()
assert (out / "metrics.json").exists()
# Metrics are present and sane, but not judged for quality
assert math.isfinite(metrics["accuracy"])
assert 0.0 <= metrics["accuracy"] <= 1.0
assert metrics["n_train"] + metrics["n_test"] == 80
# The file on disk matches what the function returned
assert json.loads((out / "metrics.json").read_text()) == metrics
def test_saved_model_can_be_loaded_and_used(small_csv, tmp_path):
out = tmp_path / "out"
run_pipeline(small_csv, out, seed=0)
model = joblib.load(out / "model.joblib")
new_rows = pd.DataFrame({"age": [30, 55], "income": [40_000.0, 90_000.0]})
preds = model.predict(new_rows[FEATURES])
assert preds.shape == (2,)
assert set(preds).issubset({0, 1})
def test_same_seed_gives_same_metrics(small_csv, tmp_path):
first = run_pipeline(small_csv, tmp_path / "run1", seed=3)
second = run_pipeline(small_csv, tmp_path / "run2", seed=3)
assert first == second
def test_missing_column_fails_loudly(tmp_path):
bad = tmp_path / "bad.csv"
pd.DataFrame({"age": [30, 40], "label": [0, 1]}).to_csv(bad, index=False)
with pytest.raises(ValueError, match="income"):
run_pipeline(bad, tmp_path / "out")Run it with pytest tests/smoke -q. On a laptop it should take a few seconds.
What to assert, and what not to
Each assertion in the example guards a different kind of break.
- Artifacts exist. The pipeline can fail silently if a save step is skipped by a changed condition or a wrong path. Checking for the files catches that.
- Metrics are finite and in range. A
NaNaccuracy usually means an empty test split or a divide-by-zero. The range check costs nothing and catches many silent bugs. - The saved model reloads and predicts. This is the most valuable check. Serialization problems, such as an unpicklable object, a missing import, or a library version mismatch, only appear when you load the file. Serving code loads the model this way in production, so the test follows the same path.
- Output shapes and label sets. The check
set(preds).issubset({0, 1})confirms the model output matches what downstream code expects. - Determinism. Two runs with the same seed should match. If they do not, other tests that compare metrics will be flaky. Finding that here is cheaper than finding it in a quality gate.
- A bad input fails with a clear error. A pipeline that raises a specific message on a missing column is easier to debug than one that fails three stages later with a
KeyError.
Do not assert a minimum accuracy in the smoke test. With 80 rows, the score depends on the split and can swing widely. A threshold would either be so low that it protects nothing or so high that it fails at random. Quality thresholds belong in the quality gate, which runs on a proper evaluation set. Keep the two jobs separate. The smoke test says "it runs", and the gate says "it is good enough".
Choosing the sample
The sample has to be small enough to run in seconds and varied enough to exercise every branch. These guidelines help:
- Include every class. If the pipeline stratifies a split, each class needs enough rows for it. With
stratify, scikit-learn raises an error when a class has fewer than 2 members. - Include the awkward cases your real data has. If production data has missing values, put a few in the sample. If the pipeline handles categorical columns, include one. A sample of perfectly clean numbers skips the branches that tend to break.
- Keep it deterministic. Generate it from a seeded random generator, or commit a small file. Do not sample from the live data source, because the test would then depend on network access and on data that changes.
- Match the real schema. The sample should have the same column names and types as production data. A sample with different columns tests a different pipeline.
Generating data in a fixture, as above, is easiest to keep in sync with the code. A committed file, like the tests/data/sample.csv used by the data validation chapter, is better when you want realistic values. You can reuse that file here, so the smoke test and the schema check cover the same sample.
Where the smoke test sits
The smoke test runs after the cheaper checks. If a unit test or schema check fails, there is no reason to spend time on a full run. The diagram shows what the test exercises.
In a CI workflow, the smoke tests form their own step after the unit and data tests and before any slow model checks. The next chapter shows how to arrange those steps in one workflow file.
Common problems
The smoke test is too slow. If it takes more than a minute, people will skip it or the team will stop running it on every pull request. Reduce the rows, set a low max_iter or a small number of estimators, and use one epoch for neural networks. Add a configuration option such as fast=True only if you must, and remember that every difference between the smoke path and the real path is a place where bugs can hide.
The smoke test differs from the real pipeline. If the test calls a separate "test version" of the training code, it proves nothing about the real one. Use the same run_pipeline and change only the inputs and parameters.
The test depends on the environment. Writing to a fixed path such as models/model.joblib makes tests interfere with each other and with local files. Always write to tmp_path.
The test passes with a broken pipeline. A smoke test that only checks "no exception was raised" can pass when the pipeline did nothing. Check the outputs, as the example does.
Flaky results. Unseeded randomness is the usual cause. Pass the seed through every step, including the split and the model. The reproducibility chapter covers pinning dependencies, which prevents the other common cause: a library update changing behavior between runs.
Summary of the approach
- Expose one entry point that takes a data path, an output directory, and a seed.
- Build a small, seeded, realistic sample, including the awkward cases.
- Run the real pipeline on it, writing to a temporary directory.
- Assert that artifacts exist, metrics are valid, the model reloads and predicts, and the same seed gives the same result.
- Check that a bad input fails with a clear message.
- Keep the whole run under about a minute, and leave quality thresholds to the quality gate.
Exercise
Your smoke test passes, but after deployment the serving service crashes with an error when it loads the model file. The smoke test only checks that model.joblib exists and that run_pipeline returned metrics. Which assertion would have caught this, and why does it work?
Show answer
Add a step that loads the saved file with joblib.load and calls predict on a few new rows, then check the output shape and label values. Serialization problems such as missing imports, unpicklable objects, or library version mismatches only show up when the file is read back. Checking that the file exists proves it was written, not that it can be used. Loading it follows the same path that the serving code takes.
Exercise
A teammate adds assert metrics["accuracy"] > 0.9 to the smoke test, and the CI run now fails about one run in five. Explain the likely cause and what to do.
Show answer
The sample has about 80 rows, so accuracy on the 20-row test split varies with the data and the split, and a high threshold fails at random. Remove the threshold from the smoke test and keep only the range check (finite, between 0 and 1). Put the accuracy threshold in the quality gate, which runs on a full evaluation set where the score is stable enough to compare with a baseline.