Sub topic 8
Stages as a dependency graph
This chapter assumes you have read the earlier chapters on stages with explicit inputs and outputs and on configuration. You should be comfortable with Python dataclasses, scikit-learn, and pytest. You will turn the plain stage functions into a graph, learn what the graph guarantees, and see where it breaks.
From a straight line to a graph
A first pipeline function calls its stages one after another, as run_pipeline did earlier. The order is implied by the order of the lines. That is fine for five stages in a row. It stops working when the workflow has branches.
Suppose you want a baseline model, such as a classifier that always predicts the most common class. The baseline needs the split data. It does not need the trained model. The trained model does not need the baseline. Written as a script, you must pick an order that the data does not require. A reader cannot tell whether that order matters.
A dependency graph removes this ambiguity. Each stage names the stages whose outputs it consumes. The graph is directed, because an edge points from producer to consumer. It is acyclic, because no stage may depend on itself, directly or through other stages. This structure is a directed acyclic graph, or DAG.
A DAG gives you three things:
- A valid execution order. Any order in which every stage runs after its dependencies is correct.
- Independence. Two stages with no path between them do not affect each other. They can run in either order or at the same time.
- Impact analysis. If one stage changes, only the stages reachable from it need to run again.
The graph we will build
The pipeline below has a gate that compares the trained model against a baseline.
Two shapes appear here. split has two consumers, so its output fans out. gate has two producers, so their outputs fan in. The train and baseline stages are independent of each other.
Declaring the graph
The simplest honest representation is a mapping from stage name to its dependencies. Python's standard library provides graphlib.TopologicalSorter (Python 3.9 and later), so you do not need to write the sorting yourself.
Each stage is a function whose first parameter is the configuration. Its other parameters are named after the stages it depends on. The runner passes each dependency's output by keyword.
from dataclasses import dataclass
from graphlib import CycleError, TopologicalSorter
from typing import Any, Callable
@dataclass(frozen=True)
class Stage:
name: str
fn: Callable[..., Any]
deps: tuple = ()
def make_stages(*stages):
return {s.name: s for s in stages}
def build_order(stages):
graph = {s.name: set(s.deps) for s in stages.values()}
unknown = {d for deps in graph.values() for d in deps} - graph.keys()
if unknown:
raise ValueError(f"unknown dependencies: {sorted(unknown)}")
return list(TopologicalSorter(graph).static_order())
def run_graph(stages, cfg):
results = {}
for name in build_order(stages):
stage = stages[name]
inputs = {dep: results[dep] for dep in stage.deps}
results[name] = stage.fn(cfg, **inputs)
return resultsbuild_order does the validation first. A misspelled dependency name fails with a clear message instead of a KeyError halfway through a run. TopologicalSorter raises CycleError if the graph has a loop, so a cycle is also caught before any stage runs.
Keep this ordering of checks. A graph error found before training starts costs seconds. The same error found after the training stage costs the whole training run.
The stages
Now declare the stages. These reuse the configuration and functions from earlier chapters, adapted to take their inputs by dependency name. Put this block in the same file as the one above.
from sklearn.datasets import load_iris
from sklearn.dummy import DummyClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
@dataclass(frozen=True)
class TrainConfig:
seed: int = 42
test_size: float = 0.2
n_estimators: int = 100
min_accuracy: float = 0.8
def load_stage(cfg):
return load_iris(return_X_y=True)
def split_stage(cfg, load_data):
X, y = load_data
return train_test_split(
X, y, test_size=cfg.test_size, random_state=cfg.seed, stratify=y
)
def train_stage(cfg, split):
X_train, _, y_train, _ = split
model = RandomForestClassifier(
n_estimators=cfg.n_estimators, random_state=cfg.seed
)
return model.fit(X_train, y_train)
def baseline_stage(cfg, split):
X_train, X_test, y_train, y_test = split
model = DummyClassifier(strategy="most_frequent").fit(X_train, y_train)
return {"accuracy": accuracy_score(y_test, model.predict(X_test))}
def evaluate_stage(cfg, train, split):
_, X_test, _, y_test = split
return {"accuracy": accuracy_score(y_test, train.predict(X_test))}
def gate_stage(cfg, evaluate, baseline):
accuracy = evaluate["accuracy"]
if accuracy < cfg.min_accuracy:
raise ValueError(f"accuracy {accuracy:.3f} is below {cfg.min_accuracy}")
if accuracy <= baseline["accuracy"]:
raise ValueError("model does not beat the baseline")
return {**evaluate, "baseline_accuracy": baseline["accuracy"]}
STAGES = make_stages(
Stage("load_data", load_stage),
Stage("split", split_stage, ("load_data",)),
Stage("train", train_stage, ("split",)),
Stage("baseline", baseline_stage, ("split",)),
Stage("evaluate", evaluate_stage, ("train", "split")),
Stage("gate", gate_stage, ("evaluate", "baseline")),
)
if __name__ == "__main__":
results = run_graph(STAGES, TrainConfig())
print(results["gate"])Running the file prints the gate's output, a dictionary with the model accuracy and the baseline accuracy. The baseline on a stratified Iris split predicts one class out of three, so its accuracy is about 0.33.
The dependency tuple in Stage and the parameter names of the function say the same thing twice. That redundancy is a trap, and the testing section below shows how to catch it.
Execution order versus execution waves
static_order() returns one valid sequence. It hides the parallelism. To see which stages could run together, use the sorter's incremental interface. It reports the stages whose dependencies are all finished, which are the ready stages.
def waves(stages):
graph = {s.name: set(s.deps) for s in stages.values()}
sorter = TopologicalSorter(graph)
sorter.prepare()
groups = []
while sorter.is_active():
ready = sorted(sorter.get_ready())
groups.append(ready)
sorter.done(*ready)
return groups
print(waves(STAGES))For this graph the output is:
[['load_data'], ['split'], ['baseline', 'train'], ['evaluate'], ['gate']]baseline and train form a wave because both become ready as soon as split finishes. A runner that submits each wave to a thread or process pool would run them side by side. An orchestrator such as Airflow, Dagster, or Prefect does this scheduling for you. The structure you declared here is the same structure they consume.
Where graphs come from
The runner above takes an explicit declaration. Other tools build the graph differently. This affects how you can get it wrong.
| Source of edges | Examples | Typical mistake |
|---|---|---|
| Declared by name | This chapter's runner, Airflow `>>` | The declaration drifts from what the code really reads |
| Matched file outputs to inputs | DVC (`deps` and `outs` in `dvc.yaml`), Make | A stage reads a file it did not list as a dependency |
| Derived from function arguments | Dagster assets, Prefect task futures | Reading global state that the framework cannot see |
All three share one rule. The graph is only as accurate as the declared interface. If a stage touches something the graph does not know about, the tool will happily run stages in an order that breaks.
Hidden dependencies
A hidden dependency is a data flow that the graph does not record. Common forms:
- A stage writes a file and a later stage reads it by path, without listing the writer as a dependency.
- A stage mutates a shared object, such as a list passed to two stages.
- A stage reads a module-level variable that another stage sets.
- Two stages share a random generator, so the second stage's results depend on how many numbers the first one drew.
The last item in the list deserves attention. In the stages above, each model gets its own random_state from cfg.seed. No stage uses numpy's global generator. That choice is what keeps baseline and train independent. If both consumed the global generator, the wave order would change the results. The reproducibility chapter covered seeds. Here the point is that a seed in the configuration is a dependency the graph can see, and a shared global generator is not.
Failing early: testing the graph itself
The graph is code, so test it. These tests need no training and run in milliseconds.
import inspect
import pytest
def test_order_respects_dependencies():
order = build_order(STAGES)
position = {name: i for i, name in enumerate(order)}
for stage in STAGES.values():
for dep in stage.deps:
assert position[dep] < position[stage.name]
def test_declared_deps_match_function_parameters():
for stage in STAGES.values():
params = list(inspect.signature(stage.fn).parameters)
assert params[0] == "cfg"
assert tuple(params[1:]) == stage.deps or set(params[1:]) == set(stage.deps)
def test_cycle_is_rejected():
looped = make_stages(
Stage("a", lambda cfg, b: b, ("b",)),
Stage("b", lambda cfg, a: a, ("a",)),
)
with pytest.raises(CycleError):
build_order(looped)
def test_unknown_dependency_is_rejected():
broken = make_stages(Stage("a", lambda cfg, ghost: ghost, ("ghost",)))
with pytest.raises(ValueError):
build_order(broken)The second test closes the redundancy gap mentioned earlier. It compares the declared dependencies with the function signature. Without it, Stage("evaluate", evaluate_stage, ("train",)) would pass validation and then fail at call time with a TypeError about a missing argument. That failure comes after earlier stages have already run.
What changed, what must rerun
The graph answers the question "if I change X, what is stale?" Anything reachable from X. Because build_order returns dependencies before dependents, one pass is enough.
def downstream(stages, changed):
affected = {changed}
for name in build_order(stages):
if affected & set(stages[name].deps):
affected.add(name)
return affected
print(sorted(downstream(STAGES, "train")))
print(sorted(downstream(STAGES, "baseline")))The first call prints ['evaluate', 'gate', 'train']. The second prints ['baseline', 'gate']. Changing n_estimators affects train, so baseline stays valid and does not need to rerun. Changing test_size affects split, and everything after split becomes stale. The next chapter uses this reachability idea to decide which cached results to reuse.
Design decisions and failure modes
Stage granularity. Too few stages and the graph has no useful structure, so a change to the metric reruns training. Too many stages and you pay overhead for each node and spend effort serializing intermediate results. A reasonable boundary is a point where you would want to inspect the output, cache it, or retry from.
In-memory results versus artifacts. run_graph keeps every result in a dictionary, which works for one process. An orchestrator running stages on separate machines needs each output written somewhere durable, such as files or an artifact store. Stage functions that take and return plain, serializable values move to that setting with little change. Functions that return open file handles or database connections do not.
Wide fan-in. A gate that depends on many stages is a single point of failure and a long wait. If one of ten parallel evaluations fails, decide whether the gate should fail, skip that input, or wait for a retry. Make that choice in code, not by accident.
Dynamic graphs. Some workflows need a number of stages that depends on data, such as one training stage per customer segment. A static declaration cannot express that directly. You can generate the stages in a loop at definition time if the list is known from configuration. If it is only known after a stage runs, you need an orchestrator that supports dynamic task creation.
Exercises
Exercise
You add a stage report that reads metrics.json, which the evaluate stage writes to disk. You declare Stage("report", report_stage, ()) with no dependencies. The pipeline works on your machine, then fails in CI after the orchestrator runs report early. What is the problem, and how do you fix it?
Show answer
The dependency of report on evaluate is hidden. It exists through a file, but the graph does not record it, so the scheduler may run report before evaluate. Declare it as Stage("report", report_stage, ("evaluate",)), and have evaluate return the metrics so report receives them as an argument. Alternatively, if the file must be used, name evaluate as a dependency and treat the file path as the artifact it produces.
Exercise
Using the graph in this chapter, which stages need to rerun if you change only n_estimators in TrainConfig? Which stage's cached output could be reused?
Show answer
n_estimators is read only by train. The stages reachable from train are evaluate and gate, so train, evaluate, and gate must rerun. load_data, split, and baseline do not depend on it and could be reused.
Exercise
Add a stage report that depends on gate and returns a string such as "accuracy=0.967". Which two places in the code must change, and what does waves(STAGES) print afterward?
Show answer
Define report_stage(cfg, gate) that formats gate["accuracy"], and add Stage("report", report_stage, ("gate",)) to STAGES. The new wave list is [['load_data'], ['split'], ['baseline', 'train'], ['evaluate'], ['gate'], ['report']], because report becomes ready only after gate finishes.