Module 8 Β· Information Systems Β· Lesson 8 Β· Week 8

DAG Automation

Reference material for the session in which the professor turns the hand-written runner of the package tcg-dataapp into a Prefect 3 flow, live and with a coding agent: the pipeline as a directed acyclic graph, tasks and futures, retries and their conditions, a cache for what never changes, tests on a temporary server, and a deployment with a schedule and a UI. In the second hour each group orchestrates the DataApp it packaged in Lesson 7.

About this session

DAG Automation Β· 02/12/2026 Β· Prof. Afonso

Learning objective

By the end of the session, students should be able to structure the pipeline of a DataApp as a DAG in Prefect, with tasks and flows whose dependencies are explicit, choose for each task its retries, retry condition and cache policy, test the flow without the network, and schedule it as a deployment monitored in the Prefect UI.

Session strategy

Demonstration followed by group work. In the first hour the professor turns the hand-written runner of the tcg-dataapp package of Lesson 7 into a Prefect 3 flow, live and with a coding agent, in four steps guided by CREATE prompts (tasks and flow, failures and cache, tests, deployment), and compares each step with the reference package 0.2.0 and with the numbers measured in the rehearsal. In the second hour each group orchestrates the DataApp it packaged in Lesson 7 with the same method, writing the graph of its tasks, the options of each task with their reasons, tests with a fake source and a scheduled deployment.

Session structure

  1. Daily β€” 15 min
  2. From a runner to an orchestrator; the pipeline as a DAG β€” 7 min
  3. Step 01: tasks, flow and futures; the downloads in parallel β€” 10 min
  4. Step 02: retries, retry condition, cache and idempotency, state hooks β€” 10 min
  5. Step 03: tests with prefect_test_harness β€” 6 min
  6. Step 04: deployment with cron, local server and UI; comparison with Airflow β€” 12 min
  7. Second hour: each group orchestrates its DataApp with Prefect (prompt 05) β€” 60 min
Part IFoundations

1. How to read this material

This material accompanies Lesson 8, which has two hours. In the first, the professor turns the hand-written runner of the package tcg-dataapp, built in Lesson 7, into a Prefect 3 flow, live and with a coding agent, in four CREATE prompts. In the second hour each group orchestrates in the same way the DataApp that it packaged in Lesson 7, in an activity that is not graded and that prepares the graded testing activity of Lesson 9.

Part I explains why a pipeline that already runs needs an orchestrator and what a directed acyclic graph is. Parts II to V follow the four steps of the session: tasks and flow, failures and cache, tests, and the deployment. Part VI gathers the prompts, the reference numbers, the mistakes found in the rehearsal and the comparison with Airflow. Every number was measured on 08/11/2026 with the reference package of lab/lesson-8/tcg_dataapp/ (version 0.2.0), Prefect 3.9.2, DuckDB 2.0.0 and Python 3.14; every date of the model is Unix time in seconds, as in Lessons 6 and 7.

2. From a runner to an orchestrator

The runner of Lesson 7, in pipeline.py, did three jobs: it sorted the twelve tasks so that each one came after its dependencies, it retried a failed task with a growing pause, and it wrote every attempt to ops.pipeline_runs. These jobs are the same in every pipeline, which is why they are the core of the tools called orchestrators. An orchestrator does them for any graph of tasks and adds what a runner written in class does not have: tasks that run at the same time when nothing orders them, options of retry and cache chosen task by task, a schedule kept outside the code, and a server that keeps the history of every run and shows it in an interface.

JobRunner of Lesson 7Prefect flow of Lesson 8
order of the tasksorder(), a topological sort written by handthe futures passed between tasks build the graph as the flow runs
parallelismnone: one task at a timeindependent tasks run at the same time, in threads
retriesone rule for every taskretries, retry_delay_seconds and retry_condition_fn per task
what never changesdownloaded again at every runcache by inputs, with the result persisted
historyops.pipeline_runsevery state of every run in the server, and the same table through hooks
schedulea line of crontaba deployment with a cron, served by a process
monitoringtcg-dataapp statusa UI with the graph, the states and the logs of each run

The three layers of the package do not change. The flow is a new module, flows.py, which calls the same functions of etls/, processors/ and views/ that the runner called, and the runner itself stays in the package so that the two can be compared on the same data.

3. The pipeline as a directed acyclic graph

A pipeline can be described as a graph in which each task is a node and each edge states that a task needs the output, or the effect, of another. The graph is directed, because a dependency has a sense: the gold layer needs the loaded prices, and no load needs the gold layer. It is acyclic, because a cycle would have no first task and could never start. These two properties are what allow a topological order to exist, and an orchestrator only needs that order and the states of the tasks to decide what to run next.

The graph also says what may run at the same time: two tasks without a path between them do not depend on each other, and an orchestrator can run them in parallel. A false edge, which states a dependency that the data does not have, therefore costs time without adding safety. In Lesson 7 each extraction of prices waited for the extraction of the products, although a price archive does not need the catalogue; the only task that needs both is build_gold, which joins them. Removing that edge lets the five archives download at once, and the run falls from about forty seconds to about nine seconds of tasks.

the flow of tcg-dataapp 0.2.0 Β· 17 task runs
extract_sets ─▢ extract_products ──────────────────────────┐
fetch_prices_2026-03-01 ─▢ load_prices_2026-03-01 ─┐        β”‚
fetch_prices_2026-05-01 ─▢ load_prices_2026-05-01 ──        β”‚
fetch_prices_2026-07-01 ─▢ load_prices_2026-07-01 ─┼────────┴▢ build_gold ─▢ check_quality ─┬▢ freeze_reports ─┐
fetch_prices_2026-09-01 ─▢ load_prices_2026-09-01 ──                                        β””β–Ά export_marts ───┴▢ write_report
fetch_prices_2026-11-07 ─▢ load_prices_2026-11-07 β”€β”˜

The extraction of prices of Lesson 7 is split in two tasks in the flow, a download and a load. The split is not cosmetic: the download only reads from the network, while the load writes to the warehouse, and Part III shows that the two need opposite options of cache.

Part IITasks and flow

4. Tasks, flows and futures in Prefect 3

In Prefect a flow is a Python function decorated with @flow, and a task is a function decorated with @task. A task called inside a flow becomes a task run, with its own state, retries, cache and logs. Calling .submit() on a task sends it to the task runner and returns a future at once; passing that future as an argument to another task makes the second wait for the first and receive its result, and passing it in wait_for makes the second wait without receiving anything. The graph is therefore not declared in a separate structure, as in the runner of Lesson 7: it is the trace of the calls that the flow makes, which also allows loops and conditions in ordinary Python, such as one download per capture date and one extra task when with_today is true.

PieceIn flows.pyWhat it does
@taskten tasks, one per stepa unit with its own state, retries and cache
@flowtcg_pipeline(with_today)the run: parameters, logs, final state
.submit()every task of the flowsends the task to the task runner and returns a future
future as argumentload_prices.submit(s, day, raw)the load waits for raw and receives its result
wait_forbuild_gold, write_reportan edge without data
wait()end of the flowwaits for every future before reading the states
.with_options()the network tasksa copy of the task with other retries, taken from the settings

The default task runner of Prefect 3 runs the submitted tasks in a pool of threads. A DuckDB connection must not be used by two threads at the same time, so each task opens its own connection through the context manager warehouse(settings) and closes it at the end. In one process, connections to the same file share one database instance, and the loads of different batches, which delete and insert different rows, do not conflict.

5. The flow of the reference package

The module below is the whole of the orchestration. Each task is a thin wrapper over a function of a layer; the options of each task, discussed in Part III, are in its decorator; and the flow reads the settings from the environment, because a deployment runs it in another process that receives only environment variables and the parameters of the deployment.

src/tcg_dataapp/flows.py
"""The pipeline of Lesson 7 as a Prefect flow.

The hand-written runner of pipeline.py ordered the tasks, retried them and
logged them. Here Prefect does those three jobs: each step is a task, the
dependencies are the futures passed from one task to the next (or wait_for),
retries and their pauses are options of the task, and every state of every
run goes to the Prefect server, which shows them in its UI. The layers below
(etls, processors, views) are the same functions of Lesson 7.

Two rules decide the options of each task:

- a task that writes to the warehouse is never cached, because skipping it
  would skip the write; it is idempotent instead, so a retry or a rerun is safe;
- the download of a past day is cached by its inputs, because the archive of
  a past day never changes, so a rerun does not download it again.
"""
from __future__ import annotations

import datetime
from contextlib import contextmanager

import duckdb
from prefect import flow, get_run_logger, task
from prefect.cache_policies import INPUTS, NO_CACHE, TASK_SOURCE
from prefect.futures import wait
from prefect.runtime import flow_run

from tcg_dataapp.config import Settings
from tcg_dataapp.etls import extract
from tcg_dataapp.etls.landing import load_batch
from tcg_dataapp.etls.tcgcsv import TcgcsvClient
from tcg_dataapp.pipeline import LOG_DDL
from tcg_dataapp.processors import gold, quality
from tcg_dataapp.views import report


def make_client(settings: Settings) -> TcgcsvClient:
    """The source; the tests replace this function with a fake TCGplayer."""
    return TcgcsvClient(settings.base_url, settings.category)


@contextmanager
def warehouse(settings: Settings):
    """One connection per task: tasks run in threads, and a DuckDB connection must not be shared between them."""
    settings.db_path.parent.mkdir(parents=True, exist_ok=True)
    con = duckdb.connect(str(settings.db_path))
    try:
        yield con
    finally:
        con.close()


def _unix(moment: datetime.datetime | None) -> int | None:
    return int(moment.timestamp()) if moment else None


def log_state(tsk, task_run, state) -> None:
    """State hook: one row of ops.pipeline_runs per task run, as the runner of Lesson 7 wrote."""
    settings = Settings()
    with warehouse(settings) as con:
        for statement in con.extract_statements(LOG_DDL):
            con.execute(statement).fetchall()
        con.execute(
            "INSERT INTO ops.pipeline_runs VALUES (?, ?, ?, ?, ?, ?, ?)",
            [str(task_run.flow_run_id).replace("-", "")[:12], task_run.name if tsk.task_run_name else tsk.name,
             task_run.run_count, state.type.value.lower(), _unix(task_run.start_time),
             extract.now_unix(), (state.message or "")[:500]],
        ).fetchall()


def not_a_quality_error(tsk, task_run, state) -> bool:
    """Retry condition: a wrong model does not become right by running again."""
    try:
        state.result()
    except quality.QualityError:
        return False
    except Exception:  # noqa: BLE001 - any other failure (network, timeout) is worth a retry
        return True
    return True


WRITES = dict(cache_policy=NO_CACHE, on_completion=[log_state], on_failure=[log_state])


@task(name="extract_sets", retries=3, retry_delay_seconds=[2, 4, 8], **WRITES)
def extract_sets(settings: Settings, captured_at: int) -> int:
    with warehouse(settings) as con:
        return extract.extract_sets(con, make_client(settings), settings.sets, captured_at)


@task(name="extract_products", retries=3, retry_delay_seconds=[2, 4, 8], **WRITES)
def extract_products(settings: Settings, captured_at: int) -> int:
    with warehouse(settings) as con:
        return extract.extract_products(con, make_client(settings), settings.sets, captured_at)


@task(name="fetch_prices_archive", task_run_name="fetch_prices_{day}", retries=3, retry_delay_seconds=[2, 4, 8],
      cache_policy=INPUTS + TASK_SOURCE, persist_result=True)
def fetch_prices_archive(base_url: str, category: int, sets: tuple, day: str) -> list[dict]:
    """Download the archive of one past day and keep the prices of the sets; no write, so it can be cached."""
    client = make_client(Settings(base_url=base_url, category=category))
    by_set = client.prices_archive(day, list(sets))
    return [price for set_id in sets for price in by_set.get(set_id, [])]


@task(name="load_prices", task_run_name="load_prices_{day}", retries=3, retry_delay_seconds=[1, 2, 4], **WRITES)
def load_prices(settings: Settings, day: str, records: list[dict]) -> int:
    with warehouse(settings) as con:
        return load_batch(con, "tcgplayer.price.v1", extract.unix(day), records)


@task(name="extract_prices_today", retries=3, retry_delay_seconds=[2, 4, 8], **WRITES)
def extract_prices_today(settings: Settings) -> int:
    with warehouse(settings) as con:
        return extract.extract_prices_today(con, make_client(settings), settings.sets, extract.today())


@task(name="build_gold", **WRITES)
def build_gold(settings: Settings) -> str:
    with warehouse(settings) as con:
        return gold.build_gold(con)


@task(name="check_quality", retries=2, retry_condition_fn=not_a_quality_error, **WRITES)
def check_quality(settings: Settings) -> dict:
    with warehouse(settings) as con:
        return quality.check_gold(con)


@task(name="freeze_reports", **WRITES)
def freeze_reports(settings: Settings) -> dict:
    with warehouse(settings) as con:
        return gold.freeze_month(con, settings.frozen_month)


@task(name="export_marts", retries=2, retry_delay_seconds=1, **WRITES)
def export_marts(settings: Settings) -> list[str]:
    with warehouse(settings) as con:
        return [p.as_posix() for p in report.export_marts(con, settings.out_dir)]


@task(name="write_report", **WRITES)
def write_report(settings: Settings, run_id: str) -> str:
    with warehouse(settings) as con:
        return report.write_report(con, settings.out_dir, run_id).as_posix()


@flow(name="tcg-dataapp", log_prints=True)
def tcg_pipeline(with_today: bool = False) -> dict:
    """Extract, load, build the gold layer, check it, freeze the month and write the reports."""
    logger = get_run_logger()
    settings = Settings()
    run_id = (flow_run.id or "local").replace("-", "")[:12]
    captured_at = extract.now_unix()
    with warehouse(settings) as con:
        for statement in con.extract_statements(LOG_DDL):
            con.execute(statement).fetchall()
    logger.info("db %s Β· sets %d Β· dates %s", settings.db_path, len(settings.sets), ", ".join(settings.price_dates))

    # the network tasks take their retries from the settings, with a pause that doubles: 2, 4, 8 s by default
    net = dict(retries=settings.retries,
               retry_delay_seconds=[settings.retry_delay * 2 ** i for i in range(max(settings.retries, 1))])

    # the catalogue: products after sets, so a missing set stops the run before 1,490 products are loaded
    sets_f = extract_sets.with_options(**net).submit(settings, captured_at)
    products_f = extract_products.with_options(**net).submit(settings, captured_at, wait_for=[sets_f])

    # the prices: the downloads depend on nothing and start at once, in parallel; each load waits for its download
    loads = []
    for day in settings.price_dates:
        raw = fetch_prices_archive.with_options(**net).submit(
            settings.base_url, settings.category, settings.sets, day)
        loads.append(load_prices.submit(settings, day, raw))
    if with_today:
        loads.append(extract_prices_today.with_options(**net).submit(settings, wait_for=[products_f]))

    # the model: one chain, and the two outputs of the checks in parallel
    gold_f = build_gold.submit(settings, wait_for=[products_f, *loads])
    quality_f = check_quality.submit(settings, wait_for=[gold_f])
    freeze_f = freeze_reports.submit(settings, wait_for=[quality_f])
    marts_f = export_marts.submit(settings, wait_for=[quality_f])
    report_f = write_report.submit(settings, run_id, wait_for=[freeze_f, marts_f])

    futures = {"extract_sets": sets_f, "extract_products": products_f, "build_gold": gold_f,
               "check_quality": quality_f, "freeze_reports": freeze_f, "export_marts": marts_f,
               "write_report": report_f}
    futures.update({f"load_prices_{d}": f for d, f in zip(settings.price_dates, loads)})
    if with_today:
        futures["extract_prices_today"] = loads[-1]
    wait(list(futures.values()))

    results, failed = {}, []
    for name, future in futures.items():
        if future.state.is_completed():
            results[name] = future.result()
        else:
            failed.append(name)
    if failed:
        raise RuntimeError(f"run {run_id} failed: {', '.join(sorted(failed))}")
    logger.info("run %s: OK Β· %s", run_id, results["check_quality"])
    return results


def serve(cron: str = "0 6 * * *") -> None:
    """A deployment of the flow on a schedule; needs a Prefect server (prefect server start)."""
    tcg_pipeline.serve(name="daily", cron=cron, parameters={"with_today": True},
                       description="TCGplayer prices of the 2026 sets, every day at 06:00 UTC",
                       tags=["m8-si", "lesson-8"])

At the end, the flow waits for every future and reads its final state. When any task did not complete, the flow raises an error that names those tasks, so the flow run ends Failed and its message says where the run stopped; when all completed, it returns the results of the tasks, which the command tcg-dataapp flow prints.

6. The first run

Without a server configured, tcg-dataapp flow starts a temporary Prefect server in the same process, runs the flow and stops the server, which is enough to run and to test the flow before step 04. The first run of the rehearsal reproduced the model of Lessons 6 and 7 exactly, in about a quarter of the time of the runner, because the five downloads ran at the same time and the slowest task became the extraction of the 1,490 products, which reads the catalogue of each set in turn.

MeasureRunner (Lesson 7)Flow (Lesson 8)
tasks12, one at a time17 task runs, the downloads in parallel
first task to lastabout 40 sabout 9 s
whole commandabout 40 s17.4 s, with the temporary server
model7 sets Β· 1,490 products Β· 5,951 prices in 5 capturesthe same
grain and cube5,951 rows = 5,951 keys Β· 524 cellsthe same
frozen reportmv_card_price_2026_09, 1,226 rows, Pikachu ex 276/217 at US$ 1,049.08the same
Part IIIFailures and cache

7. States of a task run

Prefect records every change of state of every task run in its server, and the final state of a task decides what happens downstream. A task whose upstream tasks all ended in a Completed state runs; a task with an upstream in any other state does not run and ends Pending with the type NotReady, which the log shows as Upstream task run did not reach a COMPLETED state. Cached is a Completed state whose result came from an earlier run, so it counts as success for the tasks downstream.

A task that raises an exception with retries left goes to AwaitingRetry and starts again after its pause, and the number of runs of the task grows by one at each attempt. Without retries left, it ends Failed. The distinction between Failed and NotReady matters when reading a failed run: the failed tasks are where the cause is, and the NotReady tasks are only its consequence.

8. Retries and the retry condition

A retry is worth its cost only when the cause of the failure can disappear by itself, as in a network that drops a connection or a source that answers with an error for a few seconds. The network tasks of the flow take their number of retries from TCG_RETRIES and a pause that doubles at each attempt from TCG_RETRY_DELAY, 2, 4 and 8 seconds by default, which gives a source that is restarting time to come back without delaying a run much when it does not. The tasks that build the model have no retries, because a wrong model does not become right by running again on the same data.

check_quality sits between the two cases. It can fail because the file of the warehouse is momentarily locked, which a retry solves, or because the grain broke, which a retry does not solve. The option retry_condition_fn receives the failed state and decides: the function not_a_quality_error refuses the retry when the exception is a QualityError and accepts it for any other.

the retry condition of check_quality
def not_a_quality_error(tsk, task_run, state) -> bool:
    try:
        state.result()
    except quality.QualityError:
        return False
    except Exception:
        return True
    return True

9. Cache and idempotency

A cached task does not run: Prefect computes a key from the cache policy, finds a result stored under that key and returns it. The policy INPUTS + TASK_SOURCE computes the key from the arguments of the task and from its source code, so the key changes when the date changes and also when someone edits the task, which avoids reusing a result produced by an older version of the code. The result must be persisted, with persist_result=True, for a later run to find it; by default Prefect writes it under ~/.prefect/storage.

The archive of a past day never changes, so its download is cached, and the second run of the rehearsal read the five archives from the cache instead of the network. A write is the opposite case. If the load of a day were cached, a run after the file of the warehouse was deleted would report the load as Cached and leave the table empty. Every task that writes therefore uses NO_CACHE, and what makes it safe to repeat is idempotency: load_batch replaces its batch, the dimensions keep the last version of each member, and the frozen report is created only once. Cache avoids repeating work; idempotency makes repeating a write harmless.

TaskWrites?RetriesCacheReason
extract_sets, extract_products, extract_prices_todayyesTCG_RETRIES, 2, 4, 8 snonenetwork; the prices of today change during the day
fetch_prices_<day>noTCG_RETRIES, 2, 4, 8 sINPUTS + TASK_SOURCEthe archive of a past day never changes
load_prices_<day>yes3nonethe batch is replaced
build_gold, freeze_reports, write_reportyes0nonea wrong model does not improve by running again
check_qualityno2, except a QualityErrornoneretry condition
export_martsyes2nonewrites files that are overwritten

10. State hooks and the run log

The server of Prefect keeps the history of the runs, but the warehouse kept its own log in Lesson 7, and tcg-dataapp status reads it. The flow keeps that table through state hooks: the function log_state, attached to the tasks that write with on_completion and on_failure, receives the task, the task run and the final state, and writes one row with the identifier of the flow run, the name of the task, the number of runs of the task as the attempt, the state and the start and end in Unix time. A hook runs only on a final state, so the log has one row per task run instead of one per attempt, and a NotReady task, which never ran, has no row.

11. Three runs, three behaviours

The rehearsal ran the flow three times on the same warehouse, to check each behaviour that the options promise.

RunWhat happensResult
first17 task runs Completed5,951 prices; September frozen with 1,226 rows; 12 rows in the log
secondthe five fetch_prices end Cached; the loads write againset records 14, product records 2,980, fact still 5,951; report kept; 13.1 s
source down, TCG_RETRIES=2, TCG_RETRY_DELAY=1six network tasks fail three times, with pauses of 1 s and 2 seleven tasks NotReady; flow Failed in about 3 s; nothing written
the log of the run with the source down (excerpt)
Task run 'extract_sets-034' - Task run failed with exception: URLError(gaierror(-2, 'Name or service not known')) - Retry 1/2 will start 1.0 second(s) from now
Task run 'extract_sets-034' - Task run failed with exception: URLError(...) - Retry 2/2 will start 2.0 second(s) from now
Task run 'extract_sets-034' - Task run failed with exception: URLError(...) - Retries are exhausted
Task run 'extract_products-5fd' - Finished in state NotReady("Upstream task run '...' did not reach a 'COMPLETED' state.", type=PENDING)
Task run 'build_gold-9de' - Finished in state NotReady("Upstream task run '...' did not reach a 'COMPLETED' state.", type=PENDING)
Flow run 'lurking-eel' - Finished in state Failed('Flow run encountered an exception: RuntimeError: run bcc1015e747b failed: build_gold, check_quality, ...')
Part IVTests

12. Testing the flow without the network

The nine tests of Lesson 7 test the layers and the runner, and they keep passing. The flow has five tests of its own, which run it over the same fake TCGplayer of two sets in tests/conftest.py. Three choices make these tests isolated and fast enough. The fixture prefect_test_harness(), with the scope of the session, starts one temporary Prefect server and database for all the tests, so nothing is written to the Prefect of the user. The settings are passed by environment variables with monkeypatch.setenv, as a deployment would pass them. And the result storage of Prefect points to a temporary folder in each test, because otherwise the cache of the downloads of one test would be found by the next.

TestWhat it proves
test_the_flow_builds_gold_and_logs_every_taskthe flow gives the same model as the runner and logs each task
test_a_second_run_reuses_the_downloads_and_keeps_the_graineach archive is downloaded once in two runs; the grain and the frozen report hold
test_a_network_failure_is_retried_by_prefecta source that fails once: extract_sets completed at attempt 2
test_a_task_that_keeps_failing_stops_everything_downstreamthe flow fails, names the tasks and writes no report
test_a_quality_error_is_not_retriedthe retry condition: check_quality runs once

The 14 tests pass in about 13 seconds, most of it the start of the temporary server.

tests/test_flows.py
"""The Prefect flow over the fake TCGplayer: same results as the runner of Lesson 7, with Prefect doing the retries."""
import duckdb
import pytest
from prefect.settings import PREFECT_LOCAL_STORAGE_PATH, temporary_settings
from prefect.testing.utilities import prefect_test_harness

from tcg_dataapp import flows
from tcg_dataapp.processors import quality

from conftest import FakeClient


@pytest.fixture(scope="session", autouse=True)
def prefect_server():
    """A temporary Prefect server and database for the whole session."""
    with prefect_test_harness():
        yield


@pytest.fixture
def env(settings, monkeypatch, tmp_path):
    """The flow reads its settings from the environment, as it does when a deployment runs it."""
    monkeypatch.setenv("TCG_DB_PATH", str(settings.db_path))
    monkeypatch.setenv("TCG_OUT_DIR", str(settings.out_dir))
    monkeypatch.setenv("TCG_SETS", "1,2")
    monkeypatch.setenv("TCG_PRICE_DATES", "2026-08-01,2026-09-01")
    monkeypatch.setenv("TCG_FROZEN_MONTH", "2026-08")
    monkeypatch.setenv("TCG_RETRIES", "1")
    monkeypatch.setenv("TCG_RETRY_DELAY", "0")
    with temporary_settings({PREFECT_LOCAL_STORAGE_PATH: tmp_path / "prefect-results"}):
        yield settings


def use(monkeypatch, client):
    monkeypatch.setattr(flows, "make_client", lambda _settings: client)
    return client


def log(settings, task=None):
    con = duckdb.connect(str(settings.db_path), read_only=True)
    sql = "SELECT task, attempt, status FROM ops.pipeline_runs"
    rows = con.execute(sql + (" WHERE task = ?" if task else "") + " ORDER BY started_at, task", [task] if task else []).fetchall()
    con.close()
    return rows


def test_the_flow_builds_gold_and_logs_every_task(env, monkeypatch):
    use(monkeypatch, FakeClient())
    state = flows.tcg_pipeline(return_state=True)
    assert state.is_completed()
    results = state.result()
    assert results["check_quality"]["fact_rows"] == results["check_quality"]["fact_grain_keys"] == 6
    assert results["freeze_reports"]["mv_card_price_2026_08"].startswith("created")
    assert (env.out_dir / "report.md").exists()
    assert {t for t, _, s in log(env) if s == "completed"} == {
        "extract_sets", "extract_products", "load_prices_2026-08-01", "load_prices_2026-09-01",
        "build_gold", "check_quality", "freeze_reports", "export_marts", "write_report"}


def test_a_second_run_reuses_the_downloads_and_keeps_the_grain(env, monkeypatch):
    client = use(monkeypatch, FakeClient())
    calls = []
    original = client.prices_archive
    monkeypatch.setattr(client, "prices_archive", lambda day, groups: calls.append(day) or original(day, groups))
    flows.tcg_pipeline()
    second = flows.tcg_pipeline()
    assert sorted(calls) == ["2026-08-01", "2026-09-01"]  # each archive downloaded once: the second run hit the cache
    assert second["check_quality"]["fact_rows"] == 6
    assert second["freeze_reports"]["mv_card_price_2026_08"] == "kept"


def test_a_network_failure_is_retried_by_prefect(env, monkeypatch):
    use(monkeypatch, FakeClient(fail_times=1))
    assert flows.tcg_pipeline(return_state=True).is_completed()
    assert log(env, "extract_sets") == [("extract_sets", 2, "completed")]


def test_a_task_that_keeps_failing_stops_everything_downstream(env, monkeypatch):
    use(monkeypatch, FakeClient(fail_times=99))
    state = flows.tcg_pipeline(return_state=True)
    assert state.is_failed()
    assert "extract_sets" in state.message and "write_report" in state.message
    assert log(env, "extract_sets") == [("extract_sets", 2, "failed")]
    assert not (env.out_dir / "report.md").exists()


def test_a_quality_error_is_not_retried(env, monkeypatch):
    use(monkeypatch, FakeClient())
    calls = []

    def broken(con):
        calls.append(1)
        raise quality.QualityError("grain broken")

    monkeypatch.setattr(quality, "check_gold", broken)
    state = flows.tcg_pipeline(return_state=True)
    assert state.is_failed()
    assert len(calls) == 1
    assert not (env.out_dir / "report.md").exists()
Part VDeployment and monitoring

13. Server, deployment and the serving process

Running every day without a person requires three pieces. The server keeps the state of every run in its database and serves the UI. The deployment is the record, in the server, of what to run, when and with which parameters: the deployment daily of the flow tcg-dataapp has the cron 0 6 * * * and the parameter with_today set to true. The process started by flow.serve() registers the deployment, polls the server and runs each flow run that is due, and it is the only one of the three that executes code of the DataApp; when it stops, the scheduled runs wait.

three terminals, in the folder of the project, with the virtual environment active
# 1 Β· the server and the UI at http://127.0.0.1:4200
prefect server start

# 2 Β· the deployment 'daily', served by this process (Ctrl+C stops it)
prefect config set PREFECT_API_URL=http://127.0.0.1:4200/api
tcg-dataapp serve                          # cron 0 6 * * *, with_today=True

# 3 Β· a run now, without waiting for the schedule
prefect deployment run 'tcg-dataapp/daily'
prefect flow-run ls --limit 5

In the rehearsal, the run triggered by hand had 18 task runs, the five downloads Cached and the prices of today added as a sixth capture: 7,782 prices, 697 cells in the cube, the same numbers as tcg-dataapp run --with-today in Lesson 7. The list of flow runs showed it Completed, followed by the next three runs of the deployment, Scheduled for 06:00 UTC of the following days.

14. The schedule and its time zone

A cron expression has five fields, minute, hour, day of the month, month and day of the week, and 0 6 * * * means minute zero of hour six of every day. The schedule of the deployment has no time zone, so Prefect reads it in UTC, and the run starts at 03:00 in SΓ£o Paulo. The choice of the hour follows the source: tcgcsv publishes the archive of each day after the end of that day, so a run in the early morning finds the data of the day before complete. For a group whose partner data changes once a week, a weekly cron such as 0 6 * * 1 fits better, because a daily run would only repeat the same work.

For a demonstration in class, tcg-dataapp serve --cron "*/15 * * * *" serves the same deployment every fifteen minutes, which shows scheduled runs becoming running and completed runs in the UI during the session.

15. Monitoring in the UI

The UI of the local server, at http://127.0.0.1:4200, lists the flow runs with their states and durations, and the page of a flow run draws the graph of its task runs over a time axis, so the five downloads appear side by side and the chain of the model after them. Each task run shows its state, its number of runs and its logs, and a failed run shows the exception of the failed task and the NotReady tasks that followed it. The page of the deployment shows its schedule, its parameters and its next runs, and a run can be triggered from it with other parameters.

The UI answers the questions that the log of Lesson 7 answered only with SQL: which run failed, at which task, after how many attempts, and how long each task took. It does not replace the quality gates, which check the data; the UI shows the execution, and the gates decide whether the result can be published.

16. Prefect, Airflow and the runner

Runner of Lesson 7Prefect 3Apache Airflow
the grapha list of tasks with names of dependenciesPython calls; the graph appears as the flow runs, so loops and conditions are alloweda DAG file parsed by the scheduler; operators or the TaskFlow API
to run oncethe commandthe function; a temporary server starts by itselfa scheduler, a metadata database and an executor
schedulecrontab, outside the codethe deployment, separate from the flowpart of the DAG definition
passing dataa shared contextresults of futures, in memory or persistedXCom, meant for small values
history and UIa table and statusserver with UI; Prefect Cloud as a serviceweb server with UI; managed services in the clouds

The three run the same graph, and they differ in where the graph is declared, in what must be running before the first task and in where the history is kept. Airflow was built to run many pipelines of many teams on a shared platform, which justifies a scheduler and a database that are always running. The DataApp of this module is a Python package of one team that already runs on a laptop, and Prefect adds orchestration to it without a change in the layers and without infrastructure to install before the first run, which is why the module uses it.

Part VILab

17. The lab in four steps

The professor starts from a copy of the package of Lesson 7 with Prefect installed, builds the flow with the four prompts below and compares each step with the reference package 0.2.0. Each prompt states the facts measured in the rehearsal, so that both the agent and the class can check the result.

Step 01 Β· Tasks and flow

Prompt 01 Β· CREATE
[C] Character
You are the Python engineer who wrote tcg-dataapp in Lesson 7. Its
pipeline.py orders the twelve tasks, retries them and logs them by hand.
Now Prefect 3 does that work, and the three layers stay as they are.

[R] Request
1. pyproject.toml: version 0.2.0 and the dependency prefect>=3.4,<4.
2. src/tcg_dataapp/flows.py with one Prefect task per step, each one a
   thin wrapper over the functions of etls/, processors/ and views/:
   extract_sets, extract_products, fetch_prices_archive (download only,
   returns the prices of the seven sets of one day), load_prices (writes
   one day with load_batch), extract_prices_today, build_gold,
   check_quality, freeze_reports, export_marts and write_report.
3. A flow tcg_pipeline(with_today: bool = False) that reads Settings()
   from the environment and submits the tasks with .submit(), passing the
   dependencies as futures or wait_for:
   extract_sets -> extract_products; each fetch_prices_<day> -> its
   load_prices_<day>; extract_products and every load -> build_gold ->
   check_quality -> freeze_reports and export_marts -> write_report.
   At the end, wait() on every future and fail the flow naming the tasks
   that did not complete.
4. A function make_client(settings) that returns the TcgcsvClient, so the
   tests can replace it.
5. cli.py: a subcommand flow [--with-today] that runs the flow once and
   prints its final state; the subcommand run of Lesson 7 stays.

Facts measured on 08/11/2026 (confirm before use):
- tcg-dataapp run (Lesson 7 runner, sequential): 12 tasks in about 40 s.
- tcg-dataapp flow: the five downloads run in parallel and the whole run
  takes about 9 s of tasks (17 s with the temporary server).

[E] Example
@task(name="load_prices", task_run_name="load_prices_{day}", cache_policy=NO_CACHE)
def load_prices(settings: Settings, day: str, records: list[dict]) -> int:
    with warehouse(settings) as con:
        return load_batch(con, "tcgplayer.price.v1", extract.unix(day), records)

[A] Adjustments
- Do not change etls/, processors/ or views/: the flow only calls them.
- Tasks run in threads: open one DuckDB connection per task (a context
  manager warehouse(settings)), never share one connection.
- The downloads depend on nothing and must start at once; only the writes
  wait for what they need.
- Every date stays Unix time in seconds.

[T] Type of output
The files, the graph of the flow in text and the output of
tcg-dataapp flow, with the final numbers of check_quality.

[E] Extras
Show the plan before editing. Record this prompt in docs/prompts.md.
Stop at the end.

Review before moving on:

  • the five fetch_prices start in the same second
  • each task opens its own DuckDB connection
  • check_quality still gives 5,951 = 5,951 keys and 524 cells

Step 02 Β· Failures and cache

Prompt 02 Β· CREATE
[C] Character
You are the same engineer. The flow runs; now it must survive a source
that fails, never retry what cannot improve, and not download again what
never changes.

[R] Request
1. Retries: the tasks that use the network (extract_sets,
   extract_products, fetch_prices_archive, extract_prices_today) take
   retries from TCG_RETRIES and a pause that doubles from TCG_RETRY_DELAY
   (2, 4, 8 s by default), applied in the flow with .with_options().
2. A retry condition on check_quality: a QualityError is never retried;
   any other exception is.
3. Cache: fetch_prices_archive uses cache_policy=INPUTS + TASK_SOURCE and
   persist_result=True, because the archive of a past day never changes.
   Every task that writes to the warehouse uses cache_policy=NO_CACHE.
4. State hooks: on_completion and on_failure write one row per task run
   to ops.pipeline_runs (run_id, task, attempt = run_count, status,
   started_at, ended_at in Unix time, detail), the same table as Lesson 7.
5. Run it three times and show: the first run; a second run in which the
   five downloads end Cached and the fact still has 5,951 rows; a run with
   TCG_BASE_URL=https://tcgcsv.invalid and TCG_RETRIES=2, in which the
   network tasks fail after two retries and every dependent ends NotReady.

[E] Example
@task(name="check_quality", retries=2, retry_condition_fn=not_a_quality_error,
      cache_policy=NO_CACHE, on_completion=[log_state], on_failure=[log_state])

[A] Adjustments
- Caching a write would skip the write: idempotency, not cache, makes a
  write safe to repeat.
- Do not cache extract_prices_today: today's prices change during the day.
- A task that ends NotReady never ran; do not count it as failed in the log.

[T] Type of output
The diff of flows.py, the three runs (states of each task) and the rows
of ops.pipeline_runs of each run.

[E] Extras
Show the plan before editing. Stop at the end.

Review before moving on:

  • second run: five Cached and the fact still 5,951 rows
  • source down: three attempts, eleven NotReady, nothing written
  • a QualityError runs check_quality once

Step 03 Β· Tests

Prompt 03 Β· CREATE
[C] Character
You are the same engineer. The nine tests of Lesson 7 test the runner;
the flow needs its own tests, still without network.

[R] Request
tests/test_flows.py, reusing the FakeClient of tests/conftest.py:
1. A session fixture with prefect_test_harness(), so the tests use a
   temporary Prefect server and database.
2. A fixture that sets TCG_DB_PATH, TCG_OUT_DIR, TCG_SETS=1,2,
   TCG_PRICE_DATES=2026-08-01,2026-09-01, TCG_FROZEN_MONTH=2026-08,
   TCG_RETRIES=1 and TCG_RETRY_DELAY=0 with monkeypatch, points
   PREFECT_LOCAL_STORAGE_PATH to tmp_path, and replaces
   flows.make_client with the fake.
3. Five tests:
   - the flow completes, the fact has 6 rows = 6 keys, August is frozen,
     report.md exists, and ops.pipeline_runs has every task completed;
   - a second run downloads each archive only once (cache) and keeps the
     grain and the frozen report;
   - a source that fails once is retried by Prefect: extract_sets logged
     with attempt 2, completed;
   - a source that keeps failing fails the flow, logs extract_sets with
     attempt 2, failed, and writes no report;
   - a QualityError runs check_quality once and writes no report.

[E] Example
state = flows.tcg_pipeline(return_state=True)
assert state.is_failed()

[A] Adjustments
- The tests never touch the network, and the nine tests of Lesson 7 keep
  passing.
- The fake is injected by monkeypatch, never by a flag in the code.

[T] Type of output
The file and the output of pytest.

[E] Extras
Show the plan before editing. Stop at the end.

Review before moving on:

  • 14 tests pass without network
  • the second run downloads each archive once
  • the fake is injected by monkeypatch

Step 04 Β· Deployment

Prompt 04 Β· CREATE
[C] Character
You are the same engineer. The flow runs and is tested; now it must run
every day without anyone typing a command, and its runs must be visible.

[R] Request
1. flows.py: a function serve(cron="0 6 * * *") that calls
   tcg_pipeline.serve(name="daily", cron=cron,
   parameters={"with_today": True}, tags=["m8-si", "lesson-8"]).
2. cli.py: a subcommand serve [--cron].
3. README.md: how to start the local server and the deployment in two
   terminals, how to trigger a run by hand, and where to see the runs:
     terminal 1: prefect server start
     terminal 2: prefect config set PREFECT_API_URL=http://127.0.0.1:4200/api
                 tcg-dataapp serve
     terminal 3: prefect deployment run 'tcg-dataapp/daily'
     UI:         http://127.0.0.1:4200
4. Run it: start the server, serve the deployment, trigger one run, and
   show the scheduled runs of the next days and the states of the tasks of
   the run you triggered.

Facts measured on 08/11/2026 (confirm before use):
- the triggered run of the deployment, with today's prices: 18 task runs,
  the five downloads Cached, 7,782 prices in 6 captures, 697 cells.
- the cron has no timezone, so 06:00 is UTC (03:00 in Sao Paulo).

[E] Example
prefect deployment inspect 'tcg-dataapp/daily'

[A] Adjustments
- serve() keeps the process alive: it is the worker of the deployment;
  stop it with Ctrl+C.
- Do not create an account on Prefect Cloud; the local server is enough.
- The README replaces the crontab line of Lesson 7.

[T] Type of output
The files, the output of the three terminals and a description of what
the UI shows on the page of the run (graph, states, logs).

[E] Extras
Show the plan before editing. Stop at the end.

Review before moving on:

  • prefect deployment inspect shows the cron 0 6 * * *
  • a run triggered by hand appears in the UI with 18 task runs
  • the next three runs are scheduled

18. The second hour

In the second hour each group orchestrates the pipeline of the DataApp that it packaged in Lesson 7, with the prompt below adapted to the partner data. The first deliverable is the graph itself, in docs/dag.md, with the reason of each edge, because the false edges and the tasks that can run in parallel appear only when the graph is written down. The options of each task must come with their reasons, in the terms of Part III: what can fail for an external reason, what a retry cannot fix, and which tasks write. The activity is not graded; its tests and its graph are the starting point of Lesson 9, in which each student derives quality scenarios for the DataApp and turns them into test cases.

Prompt 05 Β· CREATE Β· the DataApp of the group
[C] Character
You are the orchestration engineer of our group. The DataApp of the group
was packaged in three layers in Lesson 7; its pipeline still runs by
hand or by a hand-written runner.

[R] Request
1. docs/dag.md: the tasks of our pipeline, the dependency of each one and
   why it exists, drawn as a graph in text; which tasks can run in
   parallel; which tasks write and which only read or download.
2. src/<package>/flows.py: one Prefect task per step over the existing
   functions, and one flow that submits them with their dependencies.
3. For each task, its options with a reason: retries and the pause (only
   for what can fail for an external reason), a retry condition where a
   retry cannot help, a cache policy (NO_CACHE for every write), a timeout
   for calls to the partner API or to ClickHouse.
4. tests/test_flows.py with prefect_test_harness and a fake source: a run
   that completes, a failure that is retried, a failure that stops the
   dependents.
5. A deployment served with a cron that fits the partner data (how often
   does the source change?), and one run triggered and seen in the UI.

[E] Example
raw = fetch_orders.submit(day)            # download, no write
loaded = load_orders.submit(day, raw)     # write, waits for raw

[A] Adjustments
- Keep the three layers: the flow only calls them.
- Credentials of ClickHouse and of the partner API come from environment
  variables and never enter the repository.
- Every date stays Unix time in seconds.

[T] Type of output
The files, the output of one flow run and of pytest, and the cron chosen
with its reason.

19. Reference numbers

MeasureValue
first tcg-dataapp flow17 task runs Completed; about 9 s from the first task to the last; 17.4 s with the temporary server
model7 sets, 1,490 products, 5,951 prices in 5 captures; 5,951 rows = 5,951 keys; 524 cells
frozen reportreport.mv_card_price_2026_09 with 1,226 rows; Pikachu ex 276/217 at US$ 1,049.08
second runfive downloads Cached; fact 5,951 rows; frozen report kept; 13.1 s
source downsix network tasks Failed after 3 attempts; eleven NotReady; about 3 s; nothing written
deployment run with today18 task runs; 7,782 prices in 6 captures; 697 cells; next three runs scheduled at 06:00 UTC
runner of Lesson 712 tasks in about 40 s
tests14 passed in about 13 s, without network

20. Recurring mistakes of agents

The traps below were met or avoided while the flow was rehearsed on 08/11/2026, and the prompts already carry the corresponding adjustments.

One connection for every task

An agent that opens one DuckDB connection in the flow and passes it to the tasks makes threads share it, which fails at random when two tasks run at the same time. Each task opens and closes its own connection.

Cache on a write

Agents tend to add a cache to every task to make the second run faster. A cached load reports success without writing, which is invisible while the warehouse exists and wrong as soon as it is rebuilt. Only the downloads are cached.

Settings as parameters

Agents tend to pass the object Settings as a parameter of the flow, which works when the flow is called from Python. The parameters of a deployment, however, are stored in the server as JSON and validated against the signature of the flow, so the flow of the reference package receives only with_today and reads the rest from the environment, as the process that serves the deployment does.

The cache between tests

The persisted result of a download is found by the next test with the same inputs, so a test that counts downloads passes or fails depending on the order of the tests. Each test points the result storage to its own temporary folder.

Reading a failed run

A NotReady task never ran and is not a cause. The tasks that need attention are the Failed ones, whose logs carry the exception. In the version of the rehearsal, a NotReady task does not show its custom run name, so the loads that waited for a failed download appear as load_prices-c26 and not as load_prices_2026-03-01.

21. Glossary

TermMeaning in this lesson
DAGa directed acyclic graph of tasks and their dependencies
orchestratora tool that runs a graph of tasks in order, with retries, schedule and history
flowa function decorated with @flow; one execution is a flow run
taska function decorated with @task; one execution is a task run
futurethe promise of the result of a submitted task, which creates an edge when passed on
statethe situation of a run: Completed, Cached, Failed, NotReady, Scheduled and others
retry conditiona function that decides whether a failed task is retried
cache policythe rule that computes the key under which a result is reused
idempotentgiving the same result however many times it runs
deploymentthe record of what to run, when and with which parameters
crona schedule in five fields: minute, hour, day of the month, month, day of the week

22. Checklist

  • The graph of the pipeline is written down, with the reason of each edge.
  • Tasks without a dependency between them run in parallel.
  • Each task opens its own connection to the warehouse.
  • Retries are set only where the cause of a failure can disappear by itself.
  • A retry condition refuses to retry a broken model.
  • Only what never changes is cached; every write is idempotent and not cached.
  • The tests run the flow on a temporary server, without network.
  • A deployment has a cron that fits the source, read in UTC.
  • A failed run can be read in the UI: the Failed task, its exception and the NotReady tasks after it.

23. References and self-study