Sub topic 10
Running the pipeline from the CLI, CI, or an orchestrator
This chapter assumes you have the pipeline from the earlier chapters: a frozen TrainConfig, stage functions (load_data, split, train, evaluate), and a run_pipeline function with an accuracy gate. You should also be comfortable with argparse, Git, and reading a YAML file.
So far the pipeline only runs when someone calls run_pipeline from a Python session. That is not yet a workflow. In this chapter you will give the pipeline one command-line entry point, then call that entry point from three places: your terminal, a CI job, and an orchestrator.
One entry point, many callers
A common mistake is to write separate launch logic for each environment: a notebook cell for experiments, a shell script for CI, and a DAG file for production. The three copies drift apart, and a model trained in production is no longer the model you tested.
Instead, treat run_pipeline(cfg) as the single definition of the work. Every caller builds a TrainConfig, calls it, and reacts to the result. The callers differ only in who starts the run and what happens when it fails.
Distinguishing a gate failure from a crash
Callers need to tell two kinds of failure apart:
- A gate failure means the pipeline worked and the model was too weak. Retrying will not help, because the same seed and data give the same result.
- A crash means something broke, such as a network error or a full disk. A retry might help.
The current pipeline raises a plain ValueError for both a weak model and many unrelated bugs. Give the gate its own exception type. Subclassing ValueError keeps your existing tests working.
# pipeline.py (changed parts only; the stage functions are unchanged)
class GateError(ValueError):
"""Raised when evaluation metrics do not meet the promotion threshold."""
def check_gate(metrics, cfg):
if metrics["accuracy"] < cfg.min_accuracy:
raise GateError(
f"accuracy {metrics['accuracy']:.3f} is below the gate of {cfg.min_accuracy}"
)
def run_pipeline(cfg):
X, y = load_data()
X_train, X_test, y_train, y_test = split(X, y, cfg)
model = train(X_train, y_train, cfg)
metrics = evaluate(model, X_test, y_test)
check_gate(metrics, cfg)
return model, metricsExtracting check_gate also lets the orchestrator example below apply the same rule without copying it.
Writing the command-line interface
The CLI has three jobs: turn flags into a TrainConfig, run the pipeline, and translate the outcome into an exit code and files. Exit codes matter because every CI system and scheduler decides success or failure from them.
# train.py
import argparse
import dataclasses
import json
import sys
from pathlib import Path
import joblib
from pipeline import GateError, TrainConfig, config_fingerprint, run_pipeline
EXIT_OK = 0
EXIT_GATE_FAILED = 3
def parse_args(argv=None):
parser = argparse.ArgumentParser(description="Train and gate the iris model.")
parser.add_argument("--seed", type=int, default=TrainConfig.seed)
parser.add_argument("--test-size", type=float, default=TrainConfig.test_size)
parser.add_argument("--n-estimators", type=int, default=TrainConfig.n_estimators)
parser.add_argument("--min-accuracy", type=float, default=TrainConfig.min_accuracy)
parser.add_argument("--out", type=Path, default=Path("artifacts"))
parser.add_argument("--force", action="store_true", help="rerun even if outputs exist")
return parser.parse_args(argv)
def main(argv=None) -> int:
args = parse_args(argv)
cfg = TrainConfig(
seed=args.seed,
test_size=args.test_size,
n_estimators=args.n_estimators,
min_accuracy=args.min_accuracy,
)
fingerprint = config_fingerprint(cfg)
run_dir = args.out / fingerprint
metrics_path = run_dir / "metrics.json"
if metrics_path.exists() and not args.force:
print(f"run {fingerprint} is already complete, skipping")
return EXIT_OK
try:
model, metrics = run_pipeline(cfg)
except GateError as err:
print(f"GATE FAILED: {err}", file=sys.stderr)
return EXIT_GATE_FAILED
run_dir.mkdir(parents=True, exist_ok=True)
joblib.dump(model, run_dir / "model.joblib")
config_json = json.dumps(dataclasses.asdict(cfg), indent=2, sort_keys=True)
(run_dir / "config.json").write_text(config_json)
# Written last: its presence means the whole run finished.
metrics_path.write_text(json.dumps(metrics, indent=2))
print(f"run {fingerprint} passed: {metrics}")
return EXIT_OK
if __name__ == "__main__":
sys.exit(main())Run it from the terminal:
python train.py --seed 7 --n-estimators 200
echo "exit code: $?"
python train.py --min-accuracy 0.999 --force
echo "exit code: $?"The second command raises the threshold above what the model reaches on a small test split, so you should see GATE FAILED and exit code 3.
Design choices in this CLI
- Defaults come from the dataclass.
TrainConfig.seedreads the class-level default, so the defaults are written once. If you copy them intoargparseas literals, the two will diverge. - The output folder is the fingerprint. Two runs with the same configuration map to the same folder, and a different configuration gets a different folder. Nothing is overwritten by accident.
metrics.jsonis written last. It acts as a completion marker. If the process dies after saving the model but before writing metrics, the next run sees an incomplete folder and redoes the work, instead of treating a half-finished run as done.maintakesargvand returns an int. Tests can callmain(["--seed", "1"])without launching a subprocess, andsys.exit(main())handles the real exit code.
Testing the CLI contract
The exit codes are part of your public interface, so test them like any other behavior.
# test_cli.py
from train import EXIT_GATE_FAILED, EXIT_OK, main
def test_gate_failure_returns_distinct_code(tmp_path):
code = main(["--min-accuracy", "1.01", "--out", str(tmp_path)])
assert code == EXIT_GATE_FAILED
assert not list(tmp_path.iterdir()) # nothing is written on failure
def test_second_run_is_skipped(tmp_path):
assert main(["--out", str(tmp_path)]) == EXIT_OK
assert main(["--out", str(tmp_path)]) == EXIT_OK
assert len(list(tmp_path.iterdir())) == 1An accuracy can never exceed 1.0, so a gate of 1.01 fails regardless of seed. That makes the first test reliable instead of depending on a lucky split.
Running in CI
CI (continuous integration) runs your checks automatically on every push or pull request, in a clean machine. That is useful for a training pipeline for two reasons. A clean machine proves the pipeline does not depend on files only you have. And a failing exit code blocks the merge.
The following GitHub Actions workflow runs the tests, then runs the pipeline and stores the outputs.
# .github/workflows/train.yml
name: train
on:
pull_request:
push:
branches: [main]
jobs:
train:
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
- run: pytest -q
- run: python train.py --out artifacts
- uses: actions/upload-artifact@v4
with:
name: model-and-metrics
path: artifacts/Each step stops the job on a non-zero exit code. If pytest fails, training never starts. If the gate fails, the exit code 3 fails the job and the artifact upload is skipped, so a weak model is never published as an artifact.
What to run in CI
Full training on every pull request is often too slow or costly. A common split:
- Every pull request: unit tests, the determinism test, and a smoke run of the pipeline on a small data sample or with few estimators.
- Merge to main, or a nightly schedule: the full training run with the real gate.
Keep the smoke settings in flags, not in a separate code path. For example, python train.py --n-estimators 5 --min-accuracy 0.5 exercises the same code as production with cheaper numbers.
Common CI gotchas
- Piping hides failures. In
python train.py | tee log.txt, the shell reports the exit code oftee, not Python. Useset -o pipefailin bash, or avoid the pipe. - Secrets in logs. If the pipeline later needs credentials for a tracking server or storage, pass them as environment variables from the CI secret store. Never accept them as flags, which appear in process lists and logs.
- Ephemeral disks. The CI machine is deleted after the job. Anything you want to keep must be uploaded as an artifact or pushed to storage.
- Timeouts. Set
timeout-minutesso a hung run does not consume your quota for hours.
Running under an orchestrator
An orchestrator is a tool that schedules tasks, tracks their state, retries them, and shows you a history. Examples are Airflow, Prefect, Dagster, and Kubeflow Pipelines. You need one when runs happen on a schedule, when stages need different hardware, or when you want retries and alerts without writing them yourself.
There are two ways to connect your code to an orchestrator.
| Approach | How it works | Strength | Cost |
|---|---|---|---|
| Wrap the CLI | The orchestrator task runs `python train.py ...` in a container or shell | The same command runs everywhere; very little orchestrator-specific code | The orchestrator sees one opaque task, so it cannot retry or cache individual stages |
| Wrap the stages | Each stage function becomes an orchestrator task | Per-stage retries, caching, and visibility | Stage code is tied to one tool, and data passed between tasks needs care |
Wrapping the CLI is the safer starting point. Move to stage-level tasks when a single stage is expensive enough that you want to retry or cache it alone.
Here is a stage-level version using Prefect (pip install prefect). It reuses the same stage functions and the same gate.
# flow.py
from prefect import flow, task
from pipeline import (
TrainConfig,
check_gate,
evaluate,
load_data,
split,
train,
)
@task(retries=2, retry_delay_seconds=30)
def fit_and_score(cfg: TrainConfig):
X, y = load_data()
X_train, X_test, y_train, y_test = split(X, y, cfg)
model = train(X_train, y_train, cfg)
return model, evaluate(model, X_test, y_test)
@task # no retries: a weak model stays weak
def gate(metrics, cfg: TrainConfig):
check_gate(metrics, cfg)
@flow
def training_flow(seed: int = 42, n_estimators: int = 100):
cfg = TrainConfig(seed=seed, n_estimators=n_estimators)
model, metrics = fit_and_score(cfg)
gate(metrics, cfg)
return metrics
if __name__ == "__main__":
print(training_flow())The retry policy follows the failure types from earlier. fit_and_score may fail from transient causes such as a flaky data download, so it retries. gate fails for a deterministic reason, so it does not.
Rules for orchestrator-friendly stages
An orchestrator may run a task more than once, on a different machine, after a partial failure. Your stages should therefore:
- Produce the same output when given the same inputs and config (idempotent).
- Write results to a location derived from the config fingerprint, not to a shared fixed path like
model.pkl. - Avoid relying on local state from a previous task. If tasks run on different workers, a file written by one is not visible to the next unless it is in shared storage.
- Write outputs completely or not at all, for example by writing to a temporary name and renaming, or by writing a completion marker last as the CLI does.
Choosing where to run what
| Situation | Best fit |
|---|---|
| Trying a new idea on your machine | CLI with flags |
| Checking that a change did not break the pipeline | CI with tests and a smoke run |
| Producing the model that will be promoted | CI on main, or an orchestrator, with the full gate |
| Retraining on a schedule or when new data arrives | Orchestrator |
| One stage takes hours and fails often | Orchestrator with stage-level retries |
You do not have to pick one. A typical setup uses all three: developers use the CLI, CI guards every change, and an orchestrator handles scheduled retraining. Because they all call the same entry point, a result from one is comparable with a result from another.
Summary of failure signals
Decide in advance what each outcome looks like to the caller:
| Outcome | Exit code | Caller should |
|---|---|---|
| Run complete, gate passed | 0 | Continue, publish artifacts |
| Gate failed | 3 | Stop, report the metric, do not retry |
| Bad flags | 2 (set by `argparse`) | Fix the invocation |
| Uncaught exception | 1 (Python default) | Retry if transient, otherwise investigate |
Exercise
Your CI job runs python train.py --out artifacts | tee train.log. The gate fails and train.py exits with code 3, but the CI job shows as successful. Why does this happen, and how do you fix it?
Show answer
In a bash pipeline the exit status is that of the last command, which is tee, and tee succeeds. The exit code 3 from Python is discarded. Fix it by enabling set -o pipefail (for example bash -o pipefail -c "python train.py --out artifacts | tee train.log"), or by dropping the pipe and redirecting output with > train.log while letting CI capture the log.
Exercise
A teammate changes n_estimators from 100 to 200 and reruns python train.py with the default --out artifacts. Will the skip check in main skip the run? What if they change the training data file but keep the same config?
Show answer
The first run is not skipped. The new n_estimators changes the fingerprint, so the output goes to a different folder with no metrics.json. The second case is skipped wrongly, because the fingerprint covers only the config, and the old metrics.json still exists. The fix is to include a data version (such as a content hash) in the fingerprint input, or to pass --force when data changes.
Exercise
In the Prefect flow, why does gate have no retries setting while fit_and_score has retries=2?
Show answer
A gate failure is deterministic. With the same seed, data, and config, a retry produces the same metrics and fails again, wasting time. fit_and_score can fail for transient reasons, such as a network error while loading data, so a retry can succeed.