Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 1 of 6 · Concept · 20 min · revision 2

From Notebook to Pipeline: Steps, Artifacts and DAGs

Turn a training notebook into step functions that read and write artifacts with content hashes, order the steps as a DAG, skip unchanged steps with a cache keyed on code, parameters and input hashes, and see why a retried ingest must overwrite its partition instead of appending to it.

Contentsand lesson path

What you will learn

  • Decompose training into pipeline steps (ingest, validate, transform, train, evaluate, register) with explicit inputs and outputs, and run them with an orchestrator such as Airflow, Prefect or Kubeflow Pipelines.

01. Why it matters

A training notebook is a good place to explore, and a poor place to run a model every night. Its cells share variables in memory, so the result depends on which cells ran, in which order, and what was left over from yesterday. When one cell fails at 3 a.m., the only safe recovery is to run everything again, and nobody can say which data produced the model in production.

A pipeline fixes this by splitting the work into steps: functions with explicit inputs and outputs. Each output is an artifact, a file such as a CSV, a fitted preprocessor or a metrics report, stored where the next step can read it. Because a step only sees what it is given, you can rerun it alone, retry it after a failure, skip it when nothing it reads has changed, and record which inputs produced each artifact. That record is called lineage.

Here you build these ideas in plain Python, to see the mechanism before an orchestrator hides it. The next lesson, the orchestration lab, runs the same kind of pipeline with Prefect. You need Python 3.12 with NumPy, pandas and scikit-learn; every script runs in about a second.

Terminal
mkdir pipeline-basics && cd pipeline-basics
python3.12 -m venv .venv && source .venv/bin/activate
python -m pip install "numpy==2.5.5" "pandas==3.1.1" "scikit-learn==1.9.1"

02. Steps with explicit inputs and outputs

The script below is a notebook rewritten as four steps: ingest creates the raw data (here generated with a fixed seed, in real life read from a database), split makes a stratified train and test split, train fits a logistic regression and evaluate computes the test AUC. No step touches a global variable. Each one reads files named in its arguments and returns a small artifact record: the path of the file it wrote and the first 12 characters of the SHA-256 hash of its bytes.

The hash is the important part. A path names a location, and the file at that location can be replaced tomorrow. A content hash names the content: two files with the same hash hold the same bytes, and any change to the data, even one row, gives a different hash. Passing records with hashes between steps is what makes caching and lineage possible.

Python · steps.py
import hashlib
import json
from pathlib import Path

import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split

OUT = Path("artifacts")


def save(df_or_dict, name):
    """Write an artifact and return a small record: where it is and what it holds."""
    OUT.mkdir(exist_ok=True)
    path = OUT / name
    if isinstance(df_or_dict, pd.DataFrame):
        df_or_dict.to_csv(path, index=False)
    else:
        path.write_text(json.dumps(df_or_dict, sort_keys=True))
    digest = hashlib.sha256(path.read_bytes()).hexdigest()
    return {"path": str(path), "sha256": digest[:12]}


def ingest(n_rows=600, seed=7):
    rng = np.random.default_rng(seed)
    tenure = rng.integers(1, 73, n_rows)
    calls = rng.poisson(1.5, n_rows)
    logit = 0.8 * calls - 0.05 * tenure
    churned = (rng.random(n_rows) < 1 / (1 + np.exp(-logit))).astype(int)
    df = pd.DataFrame({"tenure": tenure, "calls": calls, "churned": churned})
    return save(df, "raw.csv")


def split(raw, test_size=0.25, seed=0):
    df = pd.read_csv(raw["path"])
    train, test = train_test_split(df, test_size=test_size, random_state=seed,
                                   stratify=df["churned"])
    return {"train": save(train, "train.csv"), "test": save(test, "test.csv")}


def train(train_set, C=1.0):
    df = pd.read_csv(train_set["path"])
    model = LogisticRegression(C=C).fit(df[["tenure", "calls"]], df["churned"])
    params = {"coef": model.coef_.round(4).tolist(),
              "intercept": model.intercept_.round(4).tolist()}
    return save(params, "model.json")


def evaluate(model_art, test_set):
    params = json.loads(Path(model_art["path"]).read_text())
    df = pd.read_csv(test_set["path"])
    score = df[["tenure", "calls"]].to_numpy() @ np.array(params["coef"][0])
    auc = roc_auc_score(df["churned"], score + params["intercept"][0])
    return save({"auc": round(float(auc), 3)}, "metrics.json")


if __name__ == "__main__":
    raw = ingest()
    print("ingest   ->", raw)
    parts = split(raw)
    print("split    ->", parts["train"])
    print("         ->", parts["test"])
    model = train(parts["train"])
    print("train    ->", model)
    print("evaluate ->", evaluate(model, parts["test"]))
    print("metrics  :", Path("artifacts/metrics.json").read_text())
Terminal
python steps.py
Expected output
ingest   -> {'path': 'artifacts/raw.csv', 'sha256': 'd3dcd77e2ce9'}
split    -> {'path': 'artifacts/train.csv', 'sha256': 'c2e097a477cf'}
         -> {'path': 'artifacts/test.csv', 'sha256': '2712436ec38d'}
train    -> {'path': 'artifacts/model.json', 'sha256': '7b885033a4a1'}
evaluate -> {'path': 'artifacts/metrics.json', 'sha256': '5dfafb05c6ca'}
metrics  : {"auc": 0.828}

Run the script twice and the hashes do not change, because every step is deterministic: the data generator, the split and the solver all use fixed seeds or no randomness at all. If a step wrote the current time into its output, its hash would change on every run and nothing downstream could be reused. Keep timestamps and run ids in separate metadata, not inside the artifact you hash.

03. A DAG gives the order and the parallelism

Once each step declares what it reads, the steps form a directed acyclic graph (DAG): an arrow from step A to step B means B reads an artifact of A, and no chain of arrows may lead back to where it started. A topological order lists every step after all the steps it depends on. Steps whose inputs are all ready at the same time can run in parallel on different workers.

Python's standard library has a small topological sorter, graphlib. The graph below is the usual training pipeline, plus a profile step that writes a data report for people and feeds nothing else.

Python · dag.py
from graphlib import CycleError, TopologicalSorter

# Each step lists the steps whose artifacts it reads (lists keep the order stable).
DEPENDS_ON = {
    "ingest": [],
    "validate": ["ingest"],
    "profile": ["ingest"],              # data report for humans; nothing needs it
    "transform": ["validate"],
    "train": ["transform"],
    "evaluate": ["train", "transform"],  # needs the model and the test split
    "register": ["evaluate", "train"],
}

print("order:", " -> ".join(TopologicalSorter(DEPENDS_ON).static_order()))

ts = TopologicalSorter(DEPENDS_ON)
ts.prepare()
wave = 1
while ts.is_active():
    ready = sorted(ts.get_ready())       # steps whose inputs all exist
    print(f"wave {wave}: {', '.join(ready)}")
    ts.done(*ready)
    wave += 1

bad = {**DEPENDS_ON, "transform": ["validate", "evaluate"]}  # a loop back
try:
    list(TopologicalSorter(bad).static_order())
except CycleError as err:
    print("rejected:", err.args[0], "->", " -> ".join(err.args[1]))
Terminal
python dag.py
Expected output
order: ingest -> validate -> profile -> transform -> train -> evaluate -> register
wave 1: ingest
wave 2: profile, validate
wave 3: transform
wave 4: train
wave 5: evaluate
wave 6: register
rejected: nodes are in a cycle -> transform -> train -> evaluate -> transform

profile and validate both need only ingest, so wave 2 can run them at the same time. Everything else is a chain, so the pipeline takes six waves however many workers you have. The last part adds an arrow from evaluate back to transform. The sorter refuses the graph and names the loop before any step runs; Airflow likewise refuses to load a DAG file that contains a cycle.

04. Caching by input hash, and lineage for free

A cache lets a pipeline skip a step whose result it already has. The runner below builds a cache key from three things: the source code of the step function, its parameters, and the content hashes of its input artifacts. If any of the three changes, the key changes and the step runs. If none changes, the runner checks that the files it recorded still have the recorded hashes and reuses them. ingest is never cached, because it reads an outside source that may have changed since the last run.

Python · cached_run.py
import hashlib
import inspect
import json
import sys
from pathlib import Path

import steps

INDEX = Path("cache.json")


def sha(path):
    return hashlib.sha256(Path(path).read_bytes()).hexdigest()[:12]


def cache_key(fn, params, inputs):
    """Step code + parameters + content hashes of the inputs."""
    blob = json.dumps({"code": inspect.getsource(fn), "params": params,
                       "inputs": [a["sha256"] for a in inputs]}, sort_keys=True)
    return hashlib.sha256(blob.encode()).hexdigest()[:12]


def records(result):
    return [result] if "path" in result else list(result.values())


def run_step(name, fn, inputs=(), cacheable=True, **params):
    index = json.loads(INDEX.read_text()) if INDEX.exists() else {}
    key = cache_key(fn, params, inputs)
    hit = index.get(key)
    if cacheable and hit and all(sha(r["path"]) == r["sha256"] for r in records(hit)):
        status, result = "cached", hit       # same key and the files are intact
    else:
        status, result = "ran", fn(*inputs, **params)
        index[key] = result
        INDEX.write_text(json.dumps(index, indent=1))
    print(f"{name:<9} {status:<7} key {key}  out {records(result)[0]['sha256']}")
    return result


C = float(sys.argv[sys.argv.index("--C") + 1]) if "--C" in sys.argv else 1.0
raw = run_step("ingest", steps.ingest, cacheable=False)   # the source may change
parts = run_step("split", steps.split, [raw], test_size=0.25)
model = run_step("train", steps.train, [parts["train"]], C=C)
metrics = run_step("evaluate", steps.evaluate, [model, parts["test"]])
print("auc:", json.loads(Path(metrics["path"]).read_text())["auc"])
Terminal
echo "--- run 1"; python cached_run.py
echo "--- run 2"; python cached_run.py
echo "--- run 3: train with C=0.05"; python cached_run.py --C 0.05
Expected output
--- run 1
ingest    ran     key 94654af39c83  out d3dcd77e2ce9
split     ran     key ffea3c1a407e  out c2e097a477cf
train     ran     key 1f3a84245b2a  out 7b885033a4a1
evaluate  ran     key 6957eb6e4c08  out 5dfafb05c6ca
auc: 0.828
--- run 2
ingest    ran     key 94654af39c83  out d3dcd77e2ce9
split     cached  key ffea3c1a407e  out c2e097a477cf
train     cached  key 1f3a84245b2a  out 7b885033a4a1
evaluate  cached  key 6957eb6e4c08  out 5dfafb05c6ca
auc: 0.828
--- run 3: train with C=0.05
ingest    ran     key 94654af39c83  out d3dcd77e2ce9
split     cached  key ffea3c1a407e  out c2e097a477cf
train     ran     key 26a933e5125e  out 981a5792320a
evaluate  ran     key faac7aac5e3b  out fac2610f4bb6
auc: 0.831

In run 2, ingest ran again and rewrote raw.csv, but the new file has the same hash, d3dcd77e2ce9, so the keys of split, train and evaluate are unchanged and all three are reused. In run 3 only the regularisation strength C of train changed. split is still cached, train gets a new key, and because the new model has a new hash, evaluate gets a new key too. The change flows down the graph through the hashes; no rule says "rerun everything after train".

The same records give you lineage. cache.json stores, for every key, the artifacts a step produced, and the key itself is built from the hashes of the step inputs. From the metrics file you can walk back to the model, the test split and the raw data that produced them. The AUC moved from 0.828 to 0.831, a difference far too small to trust on 150 test rows; the promotion-gate lesson shows how to decide when a gain is real.

05. Retries need idempotent steps

Orchestrators retry failed steps automatically, and that is only safe if the step is idempotent: running it twice with the same inputs leaves the same result as running it once. Ingest steps are where this most often goes wrong. A common failure is a lost acknowledgement: the rows reach the warehouse, the reply times out, the step is marked failed and the retry writes the rows again.

Daily pipelines are usually run for a logical date, the day of data a run is responsible for, which can differ from the day the run actually happens. A rerun for an old day is called a backfill. The script below loads the orders of two logical dates in two ways. load_append adds rows to one big file. load_overwrite writes each date into its own partition, a folder named after the date, and replaces the whole file. It writes to a temporary file first and then swaps it in with os.replace. Within one file system the rename is atomic, so a crash leaves no half-written partition. The first load of 2 November times out after writing; later that date is backfilled.

Python · partitions.py
import os
from pathlib import Path

import numpy as np
import pandas as pd


def rows_for(day):
    """The upstream system's 500 orders for one logical date."""
    rng = np.random.default_rng(int(day.replace("-", "")))
    return pd.DataFrame({"day": day, "amount": rng.gamma(2.0, 30.0, 500).round(2)})


def load_append(day, attempt, flaky):
    path = Path("lake_append/orders.csv")
    path.parent.mkdir(exist_ok=True)
    rows_for(day).to_csv(path, mode="a", header=not path.exists(), index=False)
    if flaky and attempt == 1:                     # rows are written, the ack is lost
        raise TimeoutError("lost the reply from the warehouse")


def load_overwrite(day, attempt, flaky):
    part = Path(f"lake_overwrite/day={day}")       # one folder per logical date
    part.mkdir(parents=True, exist_ok=True)
    tmp = part / "part.csv.tmp"
    rows_for(day).to_csv(tmp, index=False)
    os.replace(tmp, part / "part.csv")             # swap in the whole file at once
    if flaky and attempt == 1:                     # rows are written, the ack is lost
        raise TimeoutError("lost the reply from the warehouse")


def with_retries(step, day, flaky=False, retries=2):
    for attempt in range(1, retries + 2):
        try:
            return step(day, attempt, flaky)
        except TimeoutError as err:
            print(f"  {step.__name__} attempt {attempt} failed: {err}")


for step in (load_append, load_overwrite):
    with_retries(step, "2026-11-02", flaky=True)   # first try times out, retry
    with_retries(step, "2026-11-03")
    with_retries(step, "2026-11-02")               # a backfill rerun of one day

append = pd.read_csv("lake_append/orders.csv")
over = pd.concat(pd.read_csv(p) for p in sorted(Path("lake_overwrite").glob("*/*.csv")))
for name, df in (("append", append), ("overwrite", over)):
    per_day = df.groupby("day").size().to_dict()
    print(f"{name:<9} rows per day {per_day}  total amount {df['amount'].sum():,.2f}")
Terminal
python partitions.py
Expected output
  load_append attempt 1 failed: lost the reply from the warehouse
  load_overwrite attempt 1 failed: lost the reply from the warehouse
append    rows per day {'2026-11-02': 1500, '2026-11-03': 500}  total amount 121,079.15
overwrite rows per day {'2026-11-02': 500, '2026-11-03': 500}  total amount 59,934.07

The appending loader now holds 1,500 rows for a 500-row day: one copy from the attempt that timed out, one from its retry and one from the backfill. A model trained on it sees those orders three times. The overwriting loader holds 500 rows per day however many times it runs, because each run replaces exactly the partition of its logical date. In a database the same idea is a delete-then-insert for one date inside a transaction, or a merge on a unique key.

06. How orchestrators package these ideas

An orchestrator runs the DAG for you: it schedules runs, starts steps on workers, retries failures, keeps the cache and records every run. The tools differ more in vocabulary than in ideas.

  • Apache Airflow calls a pipeline a DAG and a step a task. Each run has a logical date and a data interval to use as the partition key. Tasks pass small values through XCom and large data through storage such as S3.
  • Prefect turns Python functions into tasks and flows with decorators. Retries, result persistence and cache policies are task options; by default a task is cached only within one flow run.
  • Kubeflow Pipelines runs each component in its own container on Kubernetes and stores artifacts in object storage. Caching is on by default: a component with the same inputs and parameters reuses its earlier outputs while they still exist.
  • Managed platforms offer the same building blocks as a service: Amazon SageMaker Pipelines, Google Vertex AI Pipelines (which runs Kubeflow Pipelines definitions) and Azure Machine Learning pipelines all provide steps, artifact storage, caching, a run history and a model registry.

Whichever you choose, the design work is the one in this lesson: explicit artifacts, deterministic and idempotent steps, and the bookkeeping left to the tool.

07. Check your understanding

Practice check · 3 questions

Steps, DAGs and caches

Use the scripts and outputs of this lesson.

Q1. In run 2 of `cached_run.py`, `ingest` ran again and rewrote `raw.csv`, yet `split`, `train` and `evaluate` were reused. Why?
Q2. The output of `dag.py` puts `profile` and `validate` together in wave 2. What does that tell an orchestrator?
Q3. `load_overwrite` writes `part.csv.tmp` and then calls `os.replace` instead of writing `part.csv` directly. What does this extra step protect against?
Practice only: not graded, not saved, not evidence.

08. Apply it

The practice project starts from one of your own training notebooks. Do the design in plain Python first.

  1. List the steps of the notebook and, for each, the artifacts it reads and writes. Any variable that crosses a step boundary must become a file with a content hash.
  2. Write the dependencies as a dictionary like DEPENDS_ON and print the waves.
  3. Make the ingest step write one partition per logical date and replace it on every run. Run it three times for the same date and check that the row count does not change.

09. Review prompt

Without looking back, explain the difference between naming an artifact by its path and by its content hash; describe what a topological order is and how waves show which steps can run in parallel; list the three things that go into the cache key in cached_run.py and say why ingest is not cached; and describe what happens to an appending loader and to a partition-overwriting loader when a write succeeds but its acknowledgement is lost.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check