Module 8 · Information Systems · Lesson 8 · Week 8

Instruction session · Wednesday, December 2, 2026 · one hour of demonstration, one hour of group work

DAG Automation

The twelve tasks of the package of Lesson 7 become a Prefect flow: the same three layers, now with tasks in parallel, retries chosen task by task, a cache for what never changes, a schedule, and a server that keeps every run and shows it in a UI.

DAGPrefect 3 · @task · @flowFutures and wait_forRetries and statesCache vs idempotencyDeployment with cron

Project ritual

Daily · 15 minutes

Each group reports the progress of its deliverables, the work planned for this session and the blockers that require a decision.

15:00
What I didWhat I will doBlockersProgress
Agenda · two hours
One hour orchestrating the package, one hour orchestrating yours

In the first hour the professor turns the runner of Lesson 7 into a Prefect flow, live and with a coding agent, in four steps, and compares each step with the reference package 0.2.0. In the second hour each group does the same with the DataApp it packaged in Lesson 7.

0:22 · step 01Tasks and flowAgent: flows.pyThe graph of tasks; futures and wait_for; downloads in parallel
0:32 · step 02Failures and cacheAgent: options of each taskRetries, retry condition, cache of downloads, state hooks
0:42 · step 03TestsAgent: tests/test_flows.pyprefect_test_harness and the fake TCGplayer
0:48 · step 04DeploymentAgent: serve, READMEA cron at 06:00 UTC, the local server and its UI
1:00 · groupsYour DataApp as a flowEach groupPrompt 05 over the package of the group; prepares Lesson 9
Where the work happensOn the computer, in a terminal, over a copy of lab/lesson-7/tcg_dataapp/ with pip install 'prefect>=3.4,<4'. The reference package of this lesson is lab/lesson-8/tcg_dataapp/, and the lab of the session replays the four steps in the browser, with the runs recorded on 12/11/2026.
0:15 · From a runner to an orchestrator
What the runner of Lesson 7 did by hand

The 160 lines of pipeline.py ordered the tasks, retried them and logged them. An orchestrator does those jobs for any pipeline, and adds the ones that a runner written in class did not have.

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 at run time
parallelismnone: one task at a timeindependent tasks run at the same time, in threads
retriesone rule for every task, with a growing pauseretries, retry_delay_seconds and retry_condition_fn per task
what never changesdownloaded again at every runcache by inputs, with the result persisted
historyops.pipeline_runs in the warehouseevery state of every run in the Prefect server, and the same table by 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
0:18 · Theory
A pipeline is a directed acyclic graph

Each task is a node, and each edge says that one task needs the output of another. The graph is directed, because a dependency has a sense, and acyclic, because a task cannot wait for itself. Two tasks without a path between them can run at the same time.

Directed

The edge has a sense

build_gold needs every price loaded; nothing in the loads needs the gold layer. The edge goes from the load to the model and never back.

Acyclic

No task waits for itself

A cycle has no first task, so it cannot start. The runner of Lesson 7 refused it before running; Prefect cannot even express it, because a future exists only after its task was submitted.

Only true edges

A false edge costs time

In Lesson 7 each price waited for the products, which no price needs. Without that edge, the five downloads start at once, and the run falls from about 40 s to about 9 s of tasks.

the flow of tcg-dataapp 0.2.0 · 17 task runs
extract_sets ─▶ extract_products ─────────────────────────────┐
fetch_prices_<day> ×5 ─▶ load_prices_<day> ×5 ───────────────┴▶ build_gold ─▶ check_quality ─┬▶ freeze_reports ─┐
                                                                                            └▶ export_marts ───┴▶ write_report

Step 01 · 0:22 · Tasks and flow

The same layers, wrapped in tasks

The first step writes flows.py: one Prefect task over each function of the three layers, and one flow that submits them and passes their futures along. The layers themselves do not change.

Files

pyproject.toml (0.2.0, prefect), src/tcg_dataapp/flows.py, the subcommand flow of cli.py.

Review before moving on
  • Do the five fetch_prices start in the same second?
  • Does each task open its own DuckDB connection?
  • Does check_quality still give 5,951 = 5,951 keys and 524 cells?
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.
Step 01 · Theory
Tasks, flows and futures in Prefect 3

A flow is a Python function decorated with @flow, and a task is a function decorated with @task. Calling .submit() on a task returns a future at once, and passing that future to another task is what creates the edge of the graph.

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_for=[...]build_gold, write_reportan edge without data: wait, but receive nothing
wait()end of the flowwaits for every future before reading the states
flows.py · the edges
sets = extract_sets.submit(s, now)
prods = extract_products.submit(
    s, now, wait_for=[sets])
loads = []
for day in s.price_dates:
    raw = fetch_prices_archive.submit(
        s.base_url, s.category,
        s.sets, day)
    loads.append(
        load_prices.submit(s, day, raw))
gold = build_gold.submit(
    s, wait_for=[prods, *loads])
Threads and DuckDBThe default task runner of Prefect 3 runs tasks in threads. A DuckDB connection must not be shared between threads, so each task opens its own with warehouse(settings); in one process they share the same database, and the loads of different batches do not conflict.
Step 01 · Result
The same model, in about a quarter of the time

The first run of the flow, on 08/11/2026, against the archives of tcgcsv. The numbers of the model are those of Lessons 6 and 7; only the order of the work changed.

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
slowest stepthe five archives, about 23 s in allextract_products, about 8 s
model7 sets · 1,490 products · 5,951 prices in 5 captures · 5,951 = 5,951 keys · 524 cells
frozen reportmv_card_price_2026_09 with 1,226 rows · Pikachu ex 276/217 at US$ 1,049.08
17 / 17task runs Completed
5 at oncethe archives downloaded in parallel
Without a servertcg-dataapp flow starts a temporary Prefect server, runs the flow and stops it. Step 04 starts a server that stays.

Step 02 · 0:32 · Failures and cache

Retry what can improve, cache what never changes

A daily pipeline meets a source that is down, a model that is wrong and archives that it already downloaded. Each of these needs a different option, chosen task by task, and the reason of each option is part of the design.

Files

The options of the tasks in flows.py, the retry condition not_a_quality_error and the state hook log_state.

Review before moving on
  • Second run: do the five downloads end Cached and the fact keep 5,951 rows?
  • Source down: three attempts, then NotReady downstream and nothing written?
  • Does a QualityError run check_quality only once?
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.
Step 02 · Theory
Every task run passes through states

Prefect records each change of state of each task run in its server. The final state decides what the tasks downstream do: they run only after a Completed state, and after any other they end NotReady without running.

Completed · Cached

The task delivered a result

Cached is a Completed state whose result came from an earlier run with the same cache key. Downstream, both count as success.

Retrying · Failed

The task raised an exception

With retries left, the run goes to AwaitingRetry and starts again after the pause; the source of the rehearsal was retried after 1 s and 2 s. Without retries left, it ends Failed.

NotReady

The task never ran

Its upstream did not complete, so it stays Pending with the type NotReady. In the rehearsal, a source down left the eleven tasks downstream NotReady and wrote nothing.

A retry conditionretry_condition_fn receives the failed state and decides whether a retry can help. check_quality retries a broken connection, but not a QualityError: a grain that broke breaks again on the same data.
Step 02 · Theory
Cache the downloads, never the writes

A cached task does not run: its result is read from the result storage. That saves the download of an archive that cannot change, and it would also skip a write that the warehouse needs, which is why the two rules below go together.

TaskWrites?OptionReason
fetch_prices_<day>nocache_policy=INPUTS + TASK_SOURCE, persist_result=Truethe archive of a past day never changes; a change in the code of the task invalidates the cache
load_prices_<day>yesNO_CACHE, 3 retriesload_batch replaces the batch, so repeating it is safe
extract_prices_todayyesNO_CACHE, network retriestoday's prices change during the day
build_gold, freeze_reports, write_reportyesNO_CACHE, 0 retriesa wrong model does not become right by running again
Cache and idempotency are different answersIdempotency makes a repeated write harmless; cache avoids repeating work. If the warehouse file is deleted, a cached load would report success and leave the table empty. The downloads are cached and the loads are idempotent.
Step 02 · Result
Three runs, three behaviours

The rehearsal of 08/11/2026. The state hook writes one row per task run into ops.pipeline_runs, with the number of attempts, so the warehouse keeps the same log as in Lesson 7.

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, 2 retriessix 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
Task run 'extract_sets-034' - Task run failed with exception: URLError(...) - 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.")
Flow run 'lurking-eel' - Finished in state Failed('... run bcc1015e747b failed: build_gold, check_quality, ...')

Step 03 · 0:42 · Tests

Testing the flow without the network

The nine tests of Lesson 7 test the runner. The flow needs its own tests, which run it on a temporary Prefect server, over the same fake TCGplayer of two sets, and check the behaviours of step 02.

Files

tests/test_flows.py; tests/conftest.py stays as it was.

Review before moving on
  • Do the 14 tests pass without network?
  • Does the second run download each archive only once?
  • Is the fake injected by monkeypatch, not by a flag in the code?
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.
Step 03 · Tests
Five tests of the flow, nine of the package

prefect_test_harness() starts a temporary server and database for the session, so the tests leave nothing in the Prefect of the user. The 14 tests take about 13 s, most of it the start of that server.

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_grainthe cache of the downloads, and the grain after a rerun
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 9 tests of Lesson 7the layers and the runner, unchanged
The settings come from the environmentA deployment runs the flow in another process, which reads only environment variables. The tests set them with monkeypatch.setenv and point the result storage of Prefect to a temporary folder, so the cache of one test does not leak into another.

Step 04 · 0:48 · Deployment

Every day at 06:00 UTC, with a UI

The last step replaces the crontab line of Lesson 7. A deployment gives the flow a name, a schedule and default parameters, and a process that serves it starts each scheduled run; the server keeps the history and shows it.

Files

serve() in flows.py, the subcommand serve of cli.py, the README.

Review before moving on
  • Does prefect deployment inspect show the cron 0 6 * * *?
  • Does a run triggered by hand appear in the UI with 18 task runs?
  • Are the next three runs scheduled?
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.
Step 04 · Theory
Server, deployment and the process that serves it

The server keeps the state of every run and serves the UI. The deployment is the record of what to run, when and with which parameters. The process of serve() polls the server and runs each flow run that is due.

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

# 2 · the deployment 'daily', served by this process
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 06:00
prefect deployment run 'tcg-dataapp/daily'
prefect flow-run ls --limit 5
18task runs in the triggered run, the five downloads Cached
7,782prices in 6 captures, with today; 697 cells
The time zone of the cronThe schedule has no time zone, so 06:00 is UTC, which is 03:00 in São Paulo. The UI shows the next three runs as Scheduled.
0:55 · Comparison
Prefect, Airflow and the runner of Lesson 7

The three run the same graph. They differ in how the graph is declared, in what must be running before the first task, and in where the history is kept.

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 if 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
Why Prefect in this moduleThe DataApp is a Python package that already runs on a laptop. Prefect adds the orchestration without a change in the layers and without infrastructure to install before the first run, which suits a pipeline of one team; Airflow suits many pipelines of many teams on a shared platform.
1:00 · Second hour · groups
The DataApp of the group as a Prefect flow

Each group orchestrates the pipeline of the DataApp it packaged in Lesson 7, with prompt 05 adapted to the partner data. The activity is not graded; its tests are the starting point of the graded activity of Lesson 9.

What to build
  • docs/dag.md: the tasks, the reason of each edge, what can run in parallel
  • flows.py over the existing layers
  • the options of each task, with a reason
  • tests/test_flows.py with a fake source
  • a deployment with a cron that fits the partner data
Questions to answer
  • Which edge of your graph is false, and what does it cost?
  • Which task writes, and is it idempotent?
  • Which failure is worth a retry, and which is not?
  • How often does the source of the partner change?
Next sessionLesson 9 is the graded Automated Testing activity: each student derives the quality scenarios of the DataApp with ATAM and a utility tree, writes test cases for them and runs them.
Self-study
Self-study for this session

Readings and a video assigned on Adalove for this week, on directed acyclic graphs and on Prefect, with the reading material of the session.

Reading material

Lesson 8 material

The flow of the reference package step by step, the four prompts, the options of each task, the tests, the deployment and the comparison with Airflow, with the numbers measured on 08/11/2026.

this repository· 45 min

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