Sub topic 10
Automating the lifecycle with pipelines
This chapter assumes you can train and evaluate a supervised model in Python and have used Git and the command line. It also assumes you know in general how a web service is deployed. Earlier chapters covered data versioning, reproducibility, experiment tracking and the registry. Here you connect those pieces into a process that runs without anyone clicking through it.
Why a notebook is not a pipeline
A notebook run by hand works for exploration. It fails as a production process for four reasons:
- The steps run in whatever order the author remembers.
- Hidden state, such as variables left over from earlier cells, changes the result.
- Nobody else can rerun it with a new dataset without reading the whole thing.
- It cannot run at 3 a.m. when fresh data arrives.
A pipeline is a set of named steps with declared inputs and outputs, run in dependency order by a program. Each step does one job: ingest data, validate it, build features, train, evaluate, register. The steps are connected by artifacts, which are files or records such as a dataset snapshot, a feature table, a model file or a metrics report.
The pipeline as a directed acyclic graph
Orchestration tools represent a pipeline as a directed acyclic graph (DAG). Each node is a step. Each edge says "this step needs the output of that one." "Acyclic" means no step can depend on itself, directly or through other steps. That property guarantees a valid run order exists.
The two diamonds are quality gates. A gate is a step whose job is to stop the run. Without the data gate, a broken upstream export trains a model on garbage and publishes it. Without the release gate, every run produces a "new version" regardless of quality. The should_promote function from the CI/CD discussion is a typical release gate: an absolute floor plus a comparison with production.
What an orchestrator provides
You can write a pipeline as a shell script. Orchestrators such as Airflow, Dagster, Prefect, Kubeflow Pipelines and cloud-managed equivalents add features that scripts lack:
| Capability | What it does | Why it matters for ML |
|---|---|---|
| Dependency ordering | Runs steps only after their inputs exist | Training never starts on a half-written dataset |
| Scheduling and triggers | Starts runs on a clock, on new data, or on an alert | Supports scheduled and drift-triggered retraining |
| Retries and timeouts | Reruns failed steps with limits | Absorbs transient failures such as a flaky data source |
| Caching | Skips steps whose inputs are unchanged | Saves hours of GPU time on reruns |
| Parameters | Passes values like dates or hyperparameters into a run | One definition serves many runs |
| Run history | Records what ran, with which inputs, and the result | Feeds lineage and audits |
| Resource control | Assigns CPU, memory or GPU per step | Feature steps and training steps need different hardware |
Building the core idea in plain Python
The caching idea is the heart of most orchestrators. Give each step a fingerprint computed from its name, its parameters and the fingerprints of its upstream steps. If the fingerprint has been seen before, reuse the stored output. If an upstream step changes, every downstream fingerprint changes too, so only the affected part reruns.
This runnable sketch uses the standard library's graphlib to order the steps.
import hashlib
import json
from graphlib import TopologicalSorter
def step_key(name, params, upstream_keys):
payload = json.dumps(
{"step": name, "params": params, "upstream": upstream_keys}, sort_keys=True
)
return hashlib.sha256(payload.encode()).hexdigest()[:12]
def run_pipeline(steps, deps, params, cache):
keys, outputs, executed = {}, {}, []
for name in TopologicalSorter(deps).static_order():
upstream = sorted(deps.get(name, ()))
step_params = params.get(name, {})
key = step_key(name, step_params, [keys[u] for u in upstream])
if key not in cache:
inputs = {u: outputs[u] for u in upstream}
cache[key] = steps[name](inputs, step_params)
executed.append(name)
keys[name] = key
outputs[name] = cache[key]
return outputs, executed
def ingest(inputs, p):
return [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
def validate(inputs, p):
data = inputs["ingest"]
if len(data) < p["min_rows"]:
raise ValueError("too few rows: stopping the pipeline")
return data
def train(inputs, p):
data = inputs["validate"]
return {"mean": p["scale"] * sum(data) / len(data)}
def evaluate(inputs, p):
model, data = inputs["train"], inputs["ingest"]
return round(sum(abs(x - model["mean"]) for x in data) / len(data), 3)
steps = {"ingest": ingest, "validate": validate, "train": train, "evaluate": evaluate}
deps = {"validate": {"ingest"}, "train": {"validate"}, "evaluate": {"train", "ingest"}}
cache = {}
params = {"validate": {"min_rows": 5}, "train": {"scale": 1.0}}
_, ran = run_pipeline(steps, deps, params, cache)
print("first run:", ran) # all four steps run
_, ran = run_pipeline(steps, deps, params, cache)
print("same params:", ran) # nothing runs: every step is cached
params["train"]["scale"] = 1.1
_, ran = run_pipeline(steps, deps, params, cache)
print("changed train:", ran) # only train and evaluate runA real orchestrator persists the cache in an artifact store instead of a dictionary. The logic is the same. Notice that raising an exception in validate stops everything downstream. That is how a gate works in practice: it fails loudly.
Triggers
A pipeline needs a reason to start. The common triggers are:
- Schedule. Run nightly or weekly. This is simple and predictable, but it retrains even when nothing changed.
- New data. Run when a partition lands in storage or a table is updated. This follows the data more closely and needs a reliable arrival signal.
- Code change. Run on a merge to the main branch, usually a smaller version that tests the pipeline code on sample data.
- Monitoring alert. Run when drift or a quality metric crosses a threshold. A later chapter covers the retraining decision itself.
- Manual. A person starts a run with chosen parameters. Keep this path available, and make it call the same pipeline definition as every other trigger.
Common errors
Steps that are not idempotent. A step is idempotent if running it twice with the same inputs gives the same result and no extra side effects. Retries make this essential. A step that appends rows to a table will duplicate data on every retry. Write outputs to a path keyed by run or partition, and overwrite rather than append.
Cache keys that miss inputs. The sketch above keys only on parameters and upstream results. If you edit the code of train but not its parameters, the cache returns a stale model. Include a code version, such as the Git commit hash or a hash of the function's source, in the key. The same applies to data read from outside the pipeline: key on a dataset version or content hash, not on a table name.
Reading "latest" inside a step. A step that queries "the newest data" gives different results on a rerun, which breaks the reproducibility you built earlier. Pass an explicit date or snapshot ID as a pipeline parameter instead.
Passing large objects between steps in memory. Steps often run in separate containers. Exchange data through the artifact store and pass only references, such as paths or IDs, between steps.
Gates that warn but do not stop. A validation step that logs a message and continues protects nothing. Decide per check whether it blocks the run or only raises an alert, and write that down.
Training-serving mismatch. If the pipeline builds features with one implementation and the serving system uses another, accuracy drops in production without any pipeline failure. Share the feature code or use a feature store.
Backfills that overwhelm resources. Rerunning a year of daily partitions at once can saturate the cluster. Limit concurrency per pipeline.
Exercise
A nightly pipeline's train step reads "all rows in the orders table" and writes its model to a fixed path, appending a new record to a metrics table each time. A transient network error makes the step retry twice. Name two problems this design causes and how to fix each.
Show answer
First, the metrics table gets duplicate rows because the append is not idempotent. Fix it by writing the metrics record keyed by run ID (or partition) and overwriting it on retry. Second, reading "all rows" means the input changes between the original attempt and the retries, so the runs are not reproducible. Fix it by passing a dataset snapshot ID or date as a pipeline parameter and reading exactly that version. Writing the model to a fixed path has a related risk. Write it to a path that includes the run ID and let the registry step decide which version is current.
Exercise
In the Python sketch, you edit the body of evaluate to compute a different error measure but change no parameters. Does the cache rerun evaluate? How would you change step_key so that it does?
Show answer
No. The key depends only on the step name, its parameters and the upstream keys, so the cached result is returned. To fix it, add a code identifier to the key, for example a hash of inspect.getsource(function) or the Git commit hash, as an extra field in the JSON payload. Changing the code then changes the key of that step and of every step downstream of it.