flows.pyThe graph of tasks; futures and wait_for; downloads in parallelInstruction session · Wednesday, December 2, 2026 · one hour of demonstration, one hour of group work
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.
Project ritual
Each group reports the progress of its deliverables, the work planned for this session and the blockers that require a decision.
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.
flows.pyThe graph of tasks; futures and wait_for; downloads in paralleltests/test_flows.pyprefect_test_harness and the fake TCGplayerserve, READMEA cron at 06:00 UTC, the local server and its UIlab/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.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.
| Job | Runner of Lesson 7 | Prefect flow of Lesson 8 |
|---|---|---|
| order of the tasks | order(), a topological sort written by hand | the futures passed between tasks build the graph at run time |
| parallelism | none: one task at a time | independent tasks run at the same time, in threads |
| retries | one rule for every task, with a growing pause | retries, retry_delay_seconds and retry_condition_fn per task |
| what never changes | downloaded again at every run | cache by inputs, with the result persisted |
| history | ops.pipeline_runs in the warehouse | every state of every run in the Prefect server, and the same table by hooks |
| schedule | a line of crontab | a deployment with a cron, served by a process |
| monitoring | tcg-dataapp status | a UI with the graph, the states and the logs of each run |
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.
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.
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.
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.
extract_sets ─▶ extract_products ─────────────────────────────┐
fetch_prices_<day> ×5 ─▶ load_prices_<day> ×5 ───────────────┴▶ build_gold ─▶ check_quality ─┬▶ freeze_reports ─┐
└▶ export_marts ───┴▶ write_reportStep 01 · 0:22 · Tasks and flow
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.
pyproject.toml (0.2.0, prefect), src/tcg_dataapp/flows.py, the subcommand flow of cli.py.
fetch_prices start in the same second?check_quality still give 5,951 = 5,951 keys and 524 cells?[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.
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.
| Piece | In flows.py | What it does |
|---|---|---|
@task | ten tasks, one per step | a unit with its own state, retries and cache |
@flow | tcg_pipeline(with_today) | the run: parameters, logs, final state |
.submit() | every task of the flow | sends the task to the task runner and returns a future |
| future as argument | load_prices.submit(s, day, raw) | the load waits for raw and receives its result |
wait_for=[...] | build_gold, write_report | an edge without data: wait, but receive nothing |
wait() | end of the flow | waits for every future before reading the states |
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])warehouse(settings); in one process they share the same database, and the loads of different batches do not conflict.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.
| Measure | Runner (Lesson 7) | Flow (Lesson 8) |
|---|---|---|
| tasks | 12, one at a time | 17 task runs, the downloads in parallel |
| first task to last | about 40 s | about 9 s |
| whole command | about 40 s | 17.4 s, with the temporary server |
| slowest step | the five archives, about 23 s in all | extract_products, about 8 s |
| model | 7 sets · 1,490 products · 5,951 prices in 5 captures · 5,951 = 5,951 keys · 524 cells | |
| frozen report | mv_card_price_2026_09 with 1,226 rows · Pikachu ex 276/217 at US$ 1,049.08 | |
tcg-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
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.
The options of the tasks in flows.py, the retry condition not_a_quality_error and the state hook log_state.
Cached and the fact keep 5,951 rows?NotReady downstream and nothing written?QualityError run check_quality only once?[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.
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.
Cached is a Completed state whose result came from an earlier run with the same cache key. Downstream, both count as success.
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.
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.
retry_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.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.
| Task | Writes? | Option | Reason |
|---|---|---|---|
fetch_prices_<day> | no | cache_policy=INPUTS + TASK_SOURCE, persist_result=True | the archive of a past day never changes; a change in the code of the task invalidates the cache |
load_prices_<day> | yes | NO_CACHE, 3 retries | load_batch replaces the batch, so repeating it is safe |
extract_prices_today | yes | NO_CACHE, network retries | today's prices change during the day |
build_gold, freeze_reports, write_report | yes | NO_CACHE, 0 retries | a wrong model does not become right by running again |
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.
| Run | What happens | Result |
|---|---|---|
| first | 17 task runs Completed | 5,951 prices; September frozen with 1,226 rows; 12 rows in the log |
| second | the five fetch_prices end Cached; the loads write again | set records 14, product records 2,980, fact still 5,951; report kept; 13.1 s |
| source down, 2 retries | six network tasks fail three times, with pauses of 1 s and 2 s | eleven tasks NotReady; flow Failed in about 3 s; nothing written |
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
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.
tests/test_flows.py; tests/conftest.py stays as it was.
monkeypatch, not by a flag in the code?[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.
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.
| Test | What it proves |
|---|---|
test_the_flow_builds_gold_and_logs_every_task | the flow gives the same model as the runner and logs each task |
test_a_second_run_reuses_the_downloads_and_keeps_the_grain | the cache of the downloads, and the grain after a rerun |
test_a_network_failure_is_retried_by_prefect | a source that fails once: extract_sets completed at attempt 2 |
test_a_task_that_keeps_failing_stops_everything_downstream | the flow fails, names the tasks and writes no report |
test_a_quality_error_is_not_retried | the retry condition: check_quality runs once |
| the 9 tests of Lesson 7 | the layers and the runner, unchanged |
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
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.
serve() in flows.py, the subcommand serve of cli.py, the README.
prefect deployment inspect show the cron 0 6 * * *?[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.
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.
# 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
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 7 | Prefect 3 | Apache Airflow | |
|---|---|---|---|
| the graph | a list of tasks with names of dependencies | Python calls; the graph appears as the flow runs, so loops and if are allowed | a DAG file parsed by the scheduler; operators or the TaskFlow API |
| to run once | the command | the function; a temporary server starts by itself | a scheduler, a metadata database and an executor |
| schedule | crontab, outside the code | the deployment, separate from the flow | part of the DAG definition |
| passing data | a shared context | results of futures, in memory or persisted | XCom, meant for small values |
| history and UI | a table and status | server with UI; Prefect Cloud as a service | web server with UI; managed services in the clouds |
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.
docs/dag.md: the tasks, the reason of each edge, what can run in parallelflows.py over the existing layerstests/test_flows.py with a fake sourceReadings and a video assigned on Adalove for this week, on directed acyclic graphs and on Prefect, with the reading material of the session.
Core concepts of directed acyclic graphs and their role in pipeline orchestration.
Video on Prefect tasks, flows, dependencies, error handling and scheduling. Optional.
The architecture of Prefect and its event-driven approach to orchestration, scheduling and monitoring.
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.
DAG Automation · 02/12/2026 · Prof. Afonso
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.
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.