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 2 of 6 · Lab · 30 min · revision 2

Lab: Orchestrate an End-to-End Training Pipeline

Build an ingest, validate, transform, train, evaluate and register pipeline as Prefect 3 tasks on a local Prefect server: watch a timed-out ingest retry without duplicating rows, see unchanged steps come back as Cached on a rerun, rerun a failed training step without repeating the work before it, and load the registered preprocessor-plus-model bundle with its lineage card.

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. Goal and setup

The previous lesson built steps, content hashes, a cache and an idempotent loader by hand. You write a churn-model pipeline with six steps, run it with Prefect 3, and check four promises that a pipeline should keep: a failed step is retried automatically, a retry does not duplicate data, a rerun skips steps whose code and inputs have not changed, and a step that crashed can be rerun without repeating the work before it.

In Prefect, a task is a Python function decorated with @task, and a flow is the function decorated with @flow that calls the tasks. The Prefect server stores every run and its state. Each task run ends in a state such as Completed, Failed or Cached, which the flow can read.

You need: Python 3.12 and two terminals.

Project layout at the end of the lab
pipeline-lab/
├── prefect.toml      Prefect settings for this folder
├── source.py         stand-in for the upstream database
├── data_steps.py     step 1: ingest and validate tasks
├── features.py       step 2: transform task (the fitted preprocessor)
├── model_steps.py    step 3: train, evaluate and register tasks
├── flow.py           step 3: the flow that wires the tasks together
├── try_ingest.py, try_transform.py, show_registry.py   checks
├── data/raw/day=YYYY-MM-DD/part.csv    one partition per logical date
├── artifacts/<data hash>/              split, preprocessor and models
└── registry/churn/vN/                  registered bundles and cards
Terminal
mkdir pipeline-lab && cd pipeline-lab
python3.12 -m venv .venv && source .venv/bin/activate
python -m pip install "prefect==3.9.3" "scikit-learn==1.9.1"
python -m pip install "pandas==3.1.1" "numpy==2.5.5"

Prefect reads prefect.toml from the folder you run commands in. home keeps Prefect files inside the lab instead of ~/.prefect. persist_by_default stores task results on disk, which caching across runs needs. The server keeps its database in memory, so the lab leaves no database behind and the history is gone when you stop the server.

TOML · prefect.toml
# Prefect reads prefect.toml from the directory you run commands in.
home = ".prefect"                     # keep Prefect's files inside the lab

[api]
url = "http://127.0.0.1:8731/api"     # the server started in the setup step

[server.database]
# In-memory: run history disappears when the server stops. Delete the setting
# below to keep it in .prefect/prefect.db instead.
connection_url = """sqlite+aiosqlite:///file::memory:?cache=shared\
  &uri=true&check_same_thread=false"""

[server.ui]
enabled = false                       # faster start; set true to browse runs

[results]
persist_by_default = true             # caching across runs needs stored results

Start the server in a second terminal, inside pipeline-lab with the virtual environment active, and leave it running. It takes 10 to 30 seconds to start.

Terminal (leave running)
prefect server start --port 8731

02. Step 1: An ingest task that is safe to retry

source.py plays the upstream system. It seeds its random generator with the date, so a given day always returns the same rows. data_steps.py holds the first two tasks. ingest writes one partition per logical date and replaces it with os.replace, so a retry or a backfill rewrites the same 800 rows instead of adding more. With flaky=True it fails on its first attempt after writing, like a database whose reply is lost. validate checks that the required columns exist and that null rates are low; the next lesson turns this into a full set of checks.

CACHED = INPUTS + TASK_SOURCE is the cache policy for the later tasks. Prefect builds the cache key from the task inputs and the source code of the task function. Its default policy also includes the flow run id, which means results are reused only inside one run; leaving out the run id is what allows reuse across runs. ingest has no cache policy because the upstream data may change.

Python · source.py
"""A stand-in for the upstream customer database: 800 labelled rows per day."""
import numpy as np
import pandas as pd


def fetch(day: str) -> pd.DataFrame:
    rng = np.random.default_rng(int(day.replace("-", "")))   # same day, same rows
    n = 800
    plan = rng.choice(["basic", "standard", "premium"], n, p=[0.5, 0.3, 0.2])
    tenure = rng.integers(1, 73, n)
    fee = (rng.normal(45, 12, n) + np.select(
        [plan == "standard", plan == "premium"], [20, 45], 0)).round(2)
    calls = rng.poisson(1.2, n)
    logit = -1.0 + 0.7 * calls - 0.045 * tenure + 0.02 * (fee - 60)
    return pd.DataFrame({
        "customer_id": [f"{day}-{i:04d}" for i in range(n)],
        "tenure_months": tenure,
        "monthly_fee": fee,
        "support_calls": calls,
        "plan": plan,
        "region": rng.choice(["north", "south", "east", "west"], n),
        "churned": (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int),
    })
Python · data_steps.py
import hashlib
import os
from pathlib import Path

import pandas as pd
from prefect import task
from prefect.cache_policies import INPUTS, TASK_SOURCE
from prefect.runtime import task_run

import source

CACHED = INPUTS + TASK_SOURCE        # same task code + same inputs -> reuse the result
REQUIRED = ["tenure_months", "monthly_fee", "support_calls", "plan", "region",
            "churned"]


def artifact(path):
    digest = hashlib.sha256(Path(path).read_bytes()).hexdigest()[:12]
    return {"path": str(path), "sha256": digest}


@task(retries=2, retry_delay_seconds=1)
def ingest(day: str, flaky: bool = False) -> dict:
    part = Path(f"data/raw/day={day}")             # one partition per logical date
    part.mkdir(parents=True, exist_ok=True)
    source.fetch(day).to_csv(part / "part.csv.tmp", index=False)
    os.replace(part / "part.csv.tmp", part / "part.csv")   # overwrite, never append
    attempt = task_run.run_count
    if flaky and attempt == 1:
        print(f"    ingest attempt {attempt}: rows written, then the reply timed out")
        raise TimeoutError("upstream reply timed out")
    rows = len(pd.read_csv(part / "part.csv"))
    print(f"    ingest attempt {attempt}: {rows} rows in {part}")
    return artifact(part / "part.csv")


@task(cache_policy=CACHED)
def validate(raw: dict) -> dict:
    df = pd.read_csv(raw["path"])
    missing = sorted(set(REQUIRED) - set(df.columns))
    if missing:
        raise ValueError(f"missing columns: {missing}")
    worst = df[REQUIRED].isna().mean().max()
    if worst > 0.02:
        raise ValueError(f"null rate {worst:.3f} is above 0.02")
    print(f"    validate: {len(df)} rows, highest null rate {worst:.3f}")
    return raw

Every Prefect task keeps the plain function in .fn. Calling it runs the code without the orchestrator, which is the easiest way to test a step on its own. Outside a task run, run_count is 0.

Python · try_ingest.py
import pandas as pd

from data_steps import ingest, validate

first = ingest.fn("2026-11-02")      # .fn calls the plain function, no orchestrator
again = ingest.fn("2026-11-02")      # a rerun of the same logical date
print("same artifact both times:", first == again)
print("rows on disk:", len(pd.read_csv(again["path"])))
print("validated:", validate.fn(again))
Terminal
python try_ingest.py
Expected output
    ingest attempt 0: 800 rows in data/raw/day=2026-11-02
    ingest attempt 0: 800 rows in data/raw/day=2026-11-02
same artifact both times: True
rows on disk: 800
    validate: 800 rows, highest null rate 0.000
validated: {'path': 'data/raw/day=2026-11-02/part.csv', 'sha256': '17ab7bc03427'}

03. Step 2: Fit the preprocessor on training rows and save it

transform splits the partition into training and test rows, fits a ColumnTransformer (scaling for numbers, one-hot encoding for categories) on the training rows only, and saves the fitted object as an artifact. Each data version gets its own folder, named after the raw data hash, so a run for another day never overwrites files that a cached result still points to.

Python · features.py
from pathlib import Path

import joblib
import pandas as pd
from prefect import task
from sklearn.compose import ColumnTransformer
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import OneHotEncoder, StandardScaler

from data_steps import CACHED, artifact

NUMERIC = ["tenure_months", "monthly_fee", "support_calls"]
CATEGORICAL = ["plan", "region"]


@task(cache_policy=CACHED)
def transform(raw: dict) -> dict:
    df = pd.read_csv(raw["path"])
    train, test = train_test_split(df, test_size=0.25, random_state=0,
                                   stratify=df["churned"])
    out = Path("artifacts") / raw["sha256"]       # one folder per data version
    out.mkdir(parents=True, exist_ok=True)
    prep = ColumnTransformer([
        ("num", StandardScaler(), NUMERIC),
        ("cat", OneHotEncoder(handle_unknown="ignore"), CATEGORICAL)])
    prep.fit(train)                               # statistics from training rows only
    joblib.dump(prep, out / "preprocessor.joblib")
    train.to_csv(out / "train.csv", index=False)
    test.to_csv(out / "test.csv", index=False)
    fee_mean = prep.named_transformers_["num"].mean_[1]
    print(f"    transform: fitted on {len(train)} rows, mean fee {fee_mean:.2f}")
    names = ["train.csv", "test.csv", "preprocessor.joblib"]
    return {n.split(".")[0]: artifact(out / n) for n in names}

Saving the fitted preprocessor matters because serving must transform requests exactly as training did. When serving code recomputes the transformation, for example by scaling each batch of requests with its own mean, the model receives inputs on a different scale from the one it learned. This mismatch is called training-serving skew. The script below measures it on five test rows.

Python · try_transform.py
import joblib
import pandas as pd
from sklearn.preprocessing import StandardScaler

from data_steps import ingest
from features import NUMERIC, transform

data = transform.fn(ingest.fn("2026-11-02"))
for name, art in data.items():
    print(f"{name:<13} {art['path']}")

prep = joblib.load(data["preprocessor"]["path"])
print("output columns:", len(prep.get_feature_names_out()))

batch = pd.read_csv(data["test"]["path"]).head(5)       # five requests at serving time
saved = prep.transform(batch)[:, :3]                     # training statistics
refit = StandardScaler().fit_transform(batch[NUMERIC])   # skew: batch statistics
print("monthly_fee of the first request, scaled:")
print(f"  saved preprocessor {saved[0, 1]:+.3f}   refit on 5 rows {refit[0, 1]:+.3f}")
Terminal
python try_transform.py
Expected output
    ingest attempt 0: 800 rows in data/raw/day=2026-11-02
    transform: fitted on 600 rows, mean fee 59.98
train         artifacts/17ab7bc03427/train.csv
test          artifacts/17ab7bc03427/test.csv
preprocessor  artifacts/17ab7bc03427/preprocessor.joblib
output columns: 10
monthly_fee of the first request, scaled:
  saved preprocessor -0.194   refit on 5 rows -0.500

The same fee becomes −0.194 with the training statistics and −0.500 when the five requests are scaled among themselves: the model would see a different customer. Teams with many models often move shared features into a feature store. Its offline store builds training sets with point-in-time correct history, its online store serves the latest values with low latency, and both read one feature definition, which removes one common source of skew. For a single model, saving the fitted preprocessor with the model, as step 3 does, solves the same problem.

04. Step 3: Train, evaluate, register, and run the flow

train fits a logistic regression on the transformed training rows and saves a Pipeline that holds the fitted preprocessor and the model, so serving loads one file. It reads the environment variable CRASH_TRAIN to simulate a worker that dies, which you use in step 5. evaluate scores the test rows, overall and per plan. register copies the bundle into a file-based registry with a model card: a JSON record of the day, parameters, metrics and the hashes of the training data, preprocessor and model. That card is the lineage. register is idempotent too: if a version with the same model hash exists, it returns that version.

flow.py calls each task with return_state=True, prints the state name and then asks for the result, which raises if the task failed. Prefect's own log lines carry times and random run names, so the commands below send them to a log file and keep the terminal for the stable lines that the flow prints.

Python · model_steps.py
import json
import os
import shutil
from pathlib import Path

import joblib
import pandas as pd
from prefect import task
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
from sklearn.pipeline import Pipeline

from data_steps import CACHED, artifact


@task(cache_policy=CACHED, retries=1, retry_delay_seconds=1)
def train(data: dict, C: float = 1.0) -> dict:
    if os.environ.get("CRASH_TRAIN"):             # simulate a worker that dies
        raise MemoryError("simulated: the training worker ran out of memory")
    df = pd.read_csv(data["train"]["path"])
    prep = joblib.load(data["preprocessor"]["path"])
    clf = LogisticRegression(C=C, max_iter=1000)
    clf.fit(prep.transform(df), df["churned"])
    bundle = Pipeline([("prep", prep), ("model", clf)])   # what serving will load
    path = Path(data["train"]["path"]).with_name(f"model-C{C}.joblib")
    joblib.dump(bundle, path)
    print(f"    train: logistic regression, C={C}")
    return artifact(path)


@task(cache_policy=CACHED)
def evaluate(model: dict, data: dict) -> dict:
    bundle = joblib.load(model["path"])
    test = pd.read_csv(data["test"]["path"])
    test["score"] = bundle.predict_proba(test)[:, 1]
    metrics = {"auc": round(roc_auc_score(test["churned"], test["score"]), 3)}
    for plan, g in test.groupby("plan"):
        metrics[f"auc_{plan}"] = round(roc_auc_score(g["churned"], g["score"]), 3)
    slices = "  ".join(f"{k[4:]} {v:.3f}" for k, v in metrics.items() if k != "auc")
    print(f"    evaluate: auc {metrics['auc']:.3f} | by plan: {slices}")
    return metrics


@task
def register(model: dict, data: dict, metrics: dict, day: str, params: dict) -> str:
    if metrics["auc"] < 0.70:                 # a minimal bar; lesson 4 builds a gate
        print(f"    register: auc {metrics['auc']} is below 0.70, not registered")
        return "rejected"
    root = Path("registry/churn")
    root.mkdir(parents=True, exist_ok=True)
    for card in sorted(root.glob("v*/card.json")):
        if json.loads(card.read_text())["model_sha256"] == model["sha256"]:
            print(f"    register: same model already registered as {card.parent.name}")
            return card.parent.name                 # idempotent: no duplicate version
    version = f"v{len(list(root.glob('v*'))) + 1}"
    (root / version).mkdir()
    shutil.copy(model["path"], root / version / "model.joblib")
    card = {"day": day, "params": params, "metrics": metrics,
            "data_sha256": data["train"]["sha256"], "model_sha256": model["sha256"],
            "preprocessor_sha256": data["preprocessor"]["sha256"]}
    (root / version / "card.json").write_text(json.dumps(card, indent=1))
    print(f"    register: saved as {version}")
    return version
Python · flow.py
import argparse
import sys

from prefect import flow

from data_steps import ingest, validate
from features import transform
from model_steps import evaluate, register, train


def step(task, *args, **kwargs):
    state = task(*args, return_state=True, **kwargs)
    print(f"{task.name:<10} {state.name}")
    return state.result()          # raises if the task failed, which fails the flow


@flow(name="churn-training")
def training_pipeline(day: str, C: float = 1.0, flaky_ingest: bool = False) -> str:
    raw = step(ingest, day, flaky=flaky_ingest)
    checked = step(validate, raw)
    data = step(transform, checked)
    model = step(train, data, C=C)
    metrics = step(evaluate, model, data)
    return step(register, model, data, metrics, day=day, params={"C": C})


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--day", required=True, help="logical date, YYYY-MM-DD")
    parser.add_argument("--C", type=float, default=1.0)
    parser.add_argument("--flaky-ingest", action="store_true")
    args = parser.parse_args()
    final = training_pipeline(args.day, args.C, args.flaky_ingest, return_state=True)
    print(f"flow run   {final.name}")
    sys.exit(0 if final.is_completed() else 1)
Terminal
python flow.py --day 2026-11-02 --flaky-ingest 2> run1.log; echo "exit code $?"
grep -oE "Retry [0-9]/[0-9]" run1.log
Expected output
    ingest attempt 1: rows written, then the reply timed out
    ingest attempt 2: 800 rows in data/raw/day=2026-11-02
ingest     Completed
    validate: 800 rows, highest null rate 0.000
validate   Completed
    transform: fitted on 600 rows, mean fee 59.98
transform  Completed
    train: logistic regression, C=1.0
train      Completed
    evaluate: auc 0.816 | by plan: basic 0.851  premium 0.832  standard 0.700
evaluate   Completed
    register: saved as v1
register   Completed
flow run   Completed
exit code 0
Retry 1/2

The first ingest attempt wrote the partition and then raised TimeoutError; Prefect retried after one second, the second attempt replaced the same partition, and the row count is still 800. Every task completed and the model was registered as v1. The standard plan slice has an AUC of 0.700 against 0.816 overall, a warning sign that the promotion-gate lesson turns into a rule. The log shows what Prefect recorded. Its times and the suffixes of task run names differ on every run, so this output is illustrative.

Terminal
grep "Task run" run1.log | cut -c1-88
Illustrative output
18:57:35.572 | INFO    | Task run 'ingest-dcf' - Task run failed with exception: Timeout
18:57:36.596 | INFO    | Task run 'ingest-dcf' - Finished in state Completed()
18:57:36.616 | INFO    | Task run 'validate-f0e' - Finished in state Completed()
18:57:36.730 | INFO    | Task run 'transform-f7f' - Finished in state Completed()
18:57:36.821 | INFO    | Task run 'train-817' - Finished in state Completed()
18:57:36.898 | INFO    | Task run 'evaluate-8c1' - Finished in state Completed()
18:57:36.920 | INFO    | Task run 'register-757' - Finished in state Completed()

05. Step 4: Rerun the same day and watch the cache

Run the flow again for the same logical date.

Terminal
python flow.py --day 2026-11-02 2> run2.log; echo "exit code $?"
Expected output
    ingest attempt 1: 800 rows in data/raw/day=2026-11-02
ingest     Completed
validate   Cached
transform  Cached
train      Cached
evaluate   Cached
    register: same model already registered as v1
register   Completed
flow run   Completed
exit code 0

ingest ran, because it has no cache policy, and produced a partition with the same hash. The four tasks after it had the same code and the same inputs as in run 1, so Prefect returned their stored results as Cached without running them; their print lines are missing because their code did not execute. register runs on every flow run, and its hash check found the model already registered, so the registry still holds only v1.

06. Step 5: A step fails; rerun it without redoing the rest

Now process a new day, 3 November, with CRASH_TRAIN=1 so that train fails on every attempt. The task has retries=1, so Prefect tries it twice and then marks it Failed, and the flow fails with it. The steps before it have already completed and stored their results.

Terminal
CRASH_TRAIN=1 python flow.py --day 2026-11-03 2> run3.log; echo "exit code $?"
grep -oE "Retry [0-9]/[0-9]|Retries are exhausted" run3.log
Expected output
    ingest attempt 1: 800 rows in data/raw/day=2026-11-03
ingest     Completed
    validate: 800 rows, highest null rate 0.000
validate   Completed
    transform: fitted on 600 rows, mean fee 59.76
transform  Completed
train      Failed
flow run   Failed
exit code 1
Retry 1/1
Retries are exhausted

The non-zero exit code is what a scheduler or a CI job would act on. Fix the cause (here, unset the variable) and run the same day again.

Terminal
python flow.py --day 2026-11-03 2> run4.log; echo "exit code $?"
Expected output
    ingest attempt 1: 800 rows in data/raw/day=2026-11-03
ingest     Completed
validate   Cached
transform  Cached
    train: logistic regression, C=1.0
train      Completed
    evaluate: auc 0.855 | by plan: basic 0.844  premium 0.769  standard 0.919
evaluate   Completed
    register: saved as v2
register   Completed
flow run   Completed
exit code 0

This is a new flow run, not a resumed one. validate and transform come back Cached because the failed run stored their results under the same keys, so only the failed step and the steps after it do real work.

07. Step 6: Inspect the registry and use the bundle

The script lists the versions with their lineage, checks each model file against the hash in its card, and scores three raw requests for 4 November with the newest bundle.

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

import joblib

import source

root = Path("registry/churn")
versions = sorted(root.glob("v*"), key=lambda p: int(p.name[1:]))
for v in versions:
    card = json.loads((v / "card.json").read_text())
    digest = hashlib.sha256((v / "model.joblib").read_bytes()).hexdigest()[:12]
    intact = digest == card["model_sha256"]
    print(f"{v.name}  day {card['day']}  auc {card['metrics']['auc']}  "
          f"train data {card['data_sha256']}  model file intact: {intact}")

bundle = joblib.load(versions[-1] / "model.joblib")     # preprocessor + model in one
requests = source.fetch("2026-11-04").drop(columns="churned").head(3)
requests["p_churn"] = bundle.predict_proba(requests)[:, 1].round(3)
print(f"scoring with {versions[-1].name}:")
columns = ["customer_id", "plan", "support_calls", "p_churn"]
print(requests[columns].to_string(index=False))
Terminal
python show_registry.py
Expected output
v1  day 2026-11-02  auc 0.816  train data cb4776b51a1d  model file intact: True
v2  day 2026-11-03  auc 0.855  train data 14f8afe3a499  model file intact: True
scoring with v2:
    customer_id     plan  support_calls  p_churn
2026-11-04-0000 standard              1    0.059
2026-11-04-0001  premium              3    0.619
2026-11-04-0002 standard              0    0.127

Each card names the hash of the training split that produced its version, so you can trace v2 back to the partition of 3 November and the exact rows it was trained on. The same six steps map directly onto other orchestrators: an Airflow DAG with one task per step and the logical date as the partition key, or a Kubeflow pipeline with one container component per step. Stop the server with Ctrl+C when you are done.

08. Check your understanding

Practice check · 3 questions

Reading the runs

Use the code and outputs of this lab.

Q1. You remove `support_calls` from `NUMERIC` in `features.py` and rerun the flow for 2026-11-03. `transform` still reports `Cached`. Why?
Q2. In step 5, the second run for 2026-11-03 trained a model while `validate` and `transform` were `Cached`. What made that possible?
Q3. In step 4, `register` printed that the same model was already registered as v1. Why does it compare model hashes instead of always adding a version?
Practice only: not graded, not saved, not evidence.

09. Apply it

For the practice project, move your own notebook into this structure.

  1. Give every step a task with explicit artifact inputs and outputs, and decide which tasks get CACHED and which must run every time.
  2. Make each value that changes behaviour, such as a feature list or a threshold, a task parameter, then change it and confirm that only the affected tasks rerun.
  3. Add a schedule with flow.serve(name="daily", cron="0 3 * * *") and pass the logical date to the flow, instead of reading the current date inside a task.

10. Review prompt

Without looking back, explain what goes into Prefect's default cache key and why this lab uses INPUTS + TASK_SOURCE instead; describe what .fn gives you when testing a task; say where the preprocessor is fitted, on which rows, and how serving gets the same transformation; and explain why the second run for 3 November did not repeat validate and transform.

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