pyproject.toml, config.py, cli.pyPython packaging; the three layers and their directionInstruction session · Friday, November 27, 2026 · one hour of demonstration, one hour of graded activity
Everything that Lesson 6 built by hand in the browser becomes one Python package that runs on its own: it collects the prices of TCGplayer, loads the landing table, builds the gold layer, checks it, freezes the monthly reports and writes the answers, in one command that can run every day.
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 builds the package live with a coding agent, in four steps, and compares each step with the reference package of the repository. In the second hour each student packages the DataApp of the group in the graded activity.
pyproject.toml, config.py, cli.pyPython packaging; the three layers and their directionetls/Extraction from TCGplayer; the idempotent load of a batchprocessors/The gold layer of Lesson 6 as package data; quality gatespipeline.py, views/A DAG with retries and a run log; report and Parquetpip install -e ., the command tcg-dataapp and pytest. The reference package is in lab/lesson-7/tcg_dataapp/ of the module.The lab answered the questions once, with a person pasting SQL. A DataApp answers them every day without anyone, so each manual step must become a function that can run, fail, be retried and be tested.
| In the lab of Lesson 6 | In the package | Layer |
|---|---|---|
| the professor captured the data once, by script | etls/tcgcsv.py and etls/extract.py, at every run | ETLs |
| the JSON was kept in the localStorage | etls/landing.py: db_ingestion in a DuckDB file, loaded in replaceable batches | ETLs |
| the SQL of steps 01 to 04 was pasted in the editor | processors/sql/*.sql, run by processors/gold.py | Processors |
| the grain test was read on the screen | processors/quality.py stops the run when it fails | Processors |
| the five questions were run by hand | views/questions.py, out/report.md and out/marts/*.parquet | Views |
| the order of the steps was in the head of the professor | pipeline.py: tasks, dependencies, retries and a log | pipeline |
A layered architecture separates what the user reads, the rules that build it and the movement of data. The dependency points one way only, so a layer can be replaced or tested without touching the layer above it.
The five questions, the report in Markdown and the Parquet files of the marts. They read the gold layer and never the landing table, so a change in the source does not reach them.
The dimensions, the fact, the cube, the mart and the reports as SQL files of the package, and the checks that stop the run when the model is wrong.
The client of the source, the extraction and the load into db_ingestion. Nothing is cleaned here: the record is kept as it arrived, so the model can always be rebuilt.
views → processors → etls, the extraction is tested alone with a fake source, and the reports are tested over a fake landing table, which is what the tests of step 04 do.The lab reproduces the session in a simulated editor. The agent writes the files of the reference package, and the panels show each request to the API, each batch that enters db_ingestion, the objects of the gold layer and the tasks of the pipeline.
The public daily mirror of TCGplayer, with no key.
A batch loaded twice is replaced, not added.
Four SQL files of the package, every object a view over db_ingestion.
The five questions in report.md and three Parquet files of the marts.
ops.pipeline_runs, in about 40 s.out/alerts.log when it fails.Step 01 · 0:20 · Package
The first step builds only the structure: a project that installs, a command that answers and three empty layers that say what each one may import. The rest of the lesson fills the layers.
pyproject.toml, src/tcg_dataapp/{etls,processors,views}/, config.py, cli.py, tests/test_cli.py.
pip install -e '.[dev]' work in a new virtual environment?tcg-dataapp --version answer 0.1.0?[C] Character
You are a Python engineer who packages data applications. In Lesson 6 the
model of the TCGplayer prices was built by hand in the browser; now it
becomes an installable package that does everything on its own.
[R] Request
Create the skeleton of the package tcg-dataapp in the folder tcg_dataapp/:
1. pyproject.toml (setuptools, src layout, Python >= 3.11): dependencies
duckdb and py7zr; extra dev with pytest; console script
tcg-dataapp = tcg_dataapp.cli:main; the SQL files of
tcg_dataapp.processors as package data.
2. src/tcg_dataapp/ with three empty layers, each a subpackage with a
docstring that says what it does and what it may import:
- etls: extraction from TCGplayer and load into db_ingestion;
- processors: the gold layer and its checks;
- views: questions and reports read from gold.
3. config.py: a frozen dataclass Settings read from environment variables
with defaults (TCG_DB_PATH=warehouse/tcg.duckdb, TCG_OUT_DIR=out,
TCG_BASE_URL=https://tcgcsv.com, TCG_CATEGORY=3, TCG_SETS with the 7
sets of 2026, TCG_PRICE_DATES with 2026-03-01, 2026-05-01, 2026-07-01,
2026-09-01 and 2026-11-07, TCG_FROZEN_MONTH=2026-09, TCG_RETRIES=3,
TCG_RETRY_DELAY=2).
4. cli.py with argparse: --version and the subcommands run, status and
report, each printing "not implemented" for now; __main__.py so that
python -m tcg_dataapp works.
5. tests/test_cli.py checking --version; README.md with install and run.
Facts (confirm before use):
- The 7 sets are the groupId 24541, 24587, 24655, 24688, 24722, 24837 and
24831 of category 3 on tcgcsv.com.
- pip install -e '.[dev]' and pytest must pass in a new virtual env.
[E] Example
[project.scripts]
tcg-dataapp = "tcg_dataapp.cli:main"
[A] Adjustments
- A layer imports only from the layers below it: views -> processors ->
etls. config is imported by any of them.
- Every date of the project is Unix time in seconds (UTC), as in Lesson 6.
- No code of extraction or SQL yet: this step is only the structure.
[T] Type of output
The files, the tree of the folder and the output of pip install and pytest.
[E] Extras
Show the plan before editing. Record this prompt in docs/prompts.md.
Stop at the end.
A package is code with a declared name, version, dependencies and entry points, which any machine can install the same way. pyproject.toml is the single file that declares all of it.
| Piece | In tcg-dataapp | Why |
|---|---|---|
| build system | setuptools | turns the project into a wheel that pip installs |
| src layout | src/tcg_dataapp/ | the tests import the installed package, not a loose folder |
| dependencies | duckdb, py7zr; extra dev with pytest | the environment is reproducible from the file |
| entry point | tcg-dataapp = tcg_dataapp.cli:main | one command for people and for the scheduler |
| package data | processors/sql/*.sql | the SQL travels inside the wheel |
| editable install | pip install -e . | a change in the code is live without reinstalling |
pyproject.toml
README.md
src/tcg_dataapp/
__init__.py __main__.py
config.py cli.py
pipeline.py
etls/ tcgcsv.py
extract.py
landing.py
processors/ gold.py
quality.py
sql/01..04_*.sql
views/ questions.py
report.py
tests/ conftest.py
test_*.pyStep 02 · 0:28 · ETLs
The first layer with code brings the data in. A run that fails in the middle, or runs twice, must leave the landing table as one good run would, which is why every load replaces its batch.
etls/tcgcsv.py, etls/landing.py, etls/extract.py, tests/test_landing.py.
[C] Character
You are the same engineer. The package exists; now its first layer, which
brings the data in.
[R] Request
In src/tcg_dataapp/etls/:
1. tcgcsv.py: class TcgcsvClient(base_url, category) with groups(),
products(group_id), prices_today(group_id) and
prices_archive(day, group_ids), which downloads
/archive/tcgplayer/prices-<day>.ppmd.7z, extracts only the files
<day>/3/<groupId>/prices of the sets asked and returns
{group_id: [price records]}. Standard library plus py7zr.
2. landing.py: the table db_ingestion (timestamp BIGINT, data_json JSON,
data_tag VARCHAR); a function run(con, sql, params) that executes and
consumes the result; load_batch(con, data_tag, timestamp, records) that
replaces the batch (data_tag, timestamp) inside one transaction; counts.
3. extract.py: unix(day, hour=12) in UTC; extract_sets, extract_products
(drop imageUrl and keep only Number, Rarity, Card Type, HP and Stage in
extendedData), extract_prices_archive (batch at noon UTC of the day)
and extract_prices_today (batch at noon UTC of today).
4. tests/test_landing.py: a batch loaded twice is replaced, not
duplicated; the timestamp is BIGINT.
Facts measured on 07/11/2026 (confirm before use):
- sets 7, products 1,490, prices 657, 896, 1,153, 1,414 and 1,831 on the
five dates; the five archives take about 3 s each.
- The archive of a day holds every category; only 2 to 7 of the sets
exist in it, depending on the date.
[E] Example
load_batch(con, "tcgplayer.price.v1", unix("2026-09-01"), records)
[A] Adjustments
- DuckDB 2.0 keeps the result of execute() open until it is read; the
next statement on the same connection fails. Consume every result.
- tcgcsv.com has no key and no CORS; send a User-Agent and pause 0.2 s
between calls.
- A record is loaded exactly as it arrived, except the fields removed to
save space; no cleaning in this layer.
[T] Type of output
The files and the output of pytest.
[E] Extras
Show the plan before editing. Record this prompt in docs/prompts.md.
Stop at the end.
A pipeline is rerun after a failure, by a scheduler or by mistake. An idempotent load makes the result independent of how many times it ran, and that is what allows a retry to be automatic.
The records of one tag captured at one moment form a batch. load_batch deletes the batch and inserts it again inside one transaction.
The prices of today are loaded with the timestamp of noon of the day, not of the run, so two runs on the same day keep one price per product.
The prices of a past date come from the daily archive of tcgcsv, a 7z file of every category, from which only the files of the seven sets are extracted.
execute() stays open until it is read, and the next statement on the same connection fails with a ResourceInUse error. The rehearsal hit it at the last task of the run; the package reads every result through a small function run(con, sql).Step 03 · 0:38 · Processors
The SQL of the lab becomes package data, run in order by one function. Two things change because the package runs every day: the dimensions must survive a catalogue captured many times, and a wrong model must stop the run.
processors/sql/01..04_*.sql, processors/gold.py, processors/quality.py.
[C] Character
You are the same engineer. The landing table is filled; now the layer
that turns it into the gold layer of Lesson 6.
[R] Request
In src/tcg_dataapp/processors/:
1. sql/01_dimensions.sql, 02_fact.sql and 03_cube_and_mart.sql: the SQL of
Lesson 6 (lab/lesson-6/sql), without its check queries, every object a
view; sql/04_live_reports.sql with report.v_card_price_latest and
report.v_set_value_latest.
2. gold.py: build_gold(con), which runs the four files statement by
statement from the package data (importlib.resources), and
freeze_month(con, month), which creates report.mv_card_price_<YYYY_MM>
and report.mv_set_value_<YYYY_MM> as tables from the LAST capture of
that month, only if they do not exist yet, and returns created, kept or
no data for each one.
3. quality.py: check_gold(con), which raises QualityError when a tag of
db_ingestion is empty, when the grain of gold.fact_price is broken or
when a price has no set, and otherwise returns the numbers it measured.
Facts measured on 07/11/2026 (confirm before use):
- fact_rows 5,951 = fact_grain_keys 5,951; fact_without_set 0; dates 5;
cube_cells 524; mv_card_price_2026_09 created with 1,226 rows.
- After a second run, db_ingestion has the catalogue twice (14 set
records, 2,980 product records) and the fact still 5,951 rows.
[E] Example
QUALIFY row_number() OVER (PARTITION BY data_json->>'productId'
ORDER BY timestamp DESC) = 1
[A] Adjustments
- Every run captures the catalogue again: dim_set and dim_product keep
only the last version of each id, or the grain of the fact breaks.
- A frozen report is never replaced; a month with two captures uses the
last one, because the price is semi-additive.
- The month must match YYYY-MM before it reaches the name of a table.
[T] Type of output
The files and the numbers returned by check_gold and freeze_month.
[E] Extras
Show the plan before editing. Record this prompt in docs/prompts.md.
Stop at the end.
In the lab the catalogue was captured once and the model was read by a person. Running daily, the same set and product arrive again at each run, and nobody looks at the grain before the report is written.
QUALIFY row_number() OVER (PARTITION BY productId ORDER BY timestamp DESC) = 1 keeps the last version of each product. Without it, the second run doubles every price of the fact.
check_gold raises an error when a tag is empty, when the grain breaks or when a price has no set. The reports that depend on it are skipped, so a wrong number is never published.
freeze_month creates the tables of a month only if they do not exist, from the last capture of that month, because two captures of the same card must not add up.
| Run | set records | product records | fact rows = grain keys | frozen report |
|---|---|---|---|---|
| first | 7 | 1,490 | 5,951 = 5,951 | created (1,226 rows) |
| second | 14 | 2,980 | 5,951 = 5,951 | kept |
Step 04 · 0:46 · Pipeline and views
The last step writes the layer that users read and the pipeline that runs the twelve tasks in order. Then the package runs end to end in one command, and the tests prove the behaviour without the network.
views/questions.py, views/report.py, pipeline.py, cli.py, tests/conftest.py, tests/test_pipeline.py.
tcg-dataapp run end with twelve tasks ok?out/report.md and three Parquet files?[C] Character
You are the same engineer. The two lower layers exist; now the layer that
users read and the pipeline that runs everything in order.
[R] Request
1. views/questions.py: the five questions of Lesson 6 as a dictionary
key -> (description, SQL), reading the last capture
(SELECT max(date_unix) FROM gold.dim_date) instead of a fixed date; Q3
on the last capture of each month.
2. views/report.py: write_report(con, out_dir, run_id) writes
out/report.md with one Markdown table per question; export_marts writes
card_price, set_value and card_price_latest to out/marts/*.parquet.
3. pipeline.py: dataclass Task(name, run, depends_on, retries); order()
in topological order, raising on an unknown dependency or a cycle;
run(settings, client=None, con=None, with_today=False) that runs every
task after its dependencies, retries a failure with a growing pause,
skips the dependents of a task that still fails, and logs every attempt
in ops.pipeline_runs (run_id, task, attempt, status, started_at,
ended_at in Unix time, detail).
Tasks: extract_sets -> extract_products -> one extract_prices_<day>
per date (and extract_prices_today with --with-today) -> build_gold ->
check_quality -> freeze_reports and export_marts -> write_report.
4. cli.py: run, status (rows per tag and the last run, on a read-only
connection) and report.
5. tests/test_pipeline.py with a FakeClient of two sets in conftest.py:
topological order and cycle; a full run; a second run keeps the frozen
report and the grain; a failure retried and logged; a task that keeps
failing skips its dependents; a month with two captures freezes the
last one.
Facts measured on 07/11/2026 (confirm before use):
- tcg-dataapp run: 12 tasks ok in about 40 s, almost all of it in the
extraction; out/report.md and three Parquet files.
- pytest: 9 tests pass in about 2 s, without network.
[E] Example
Task("check_quality", lambda c: quality.check_gold(c.con),
depends_on=("build_gold",), retries=0)
[A] Adjustments
- The checks and the gold layer are not retried: a wrong model does not
become right by running again.
- No orchestrator library: Lesson 8 replaces this runner with Prefect.
- The tests never touch the network.
[T] Type of output
The files, the output of tcg-dataapp run, tcg-dataapp status and pytest.
[E] Extras
Show the plan before editing. Record this prompt in docs/prompts.md.
Stop at the end.
Each task declares the tasks it depends on, and the runner orders them so that a task starts only after all of its dependencies succeeded. A cycle or an unknown dependency is refused before anything runs.
extract_sets ─▶ extract_products ─┬▶ extract_prices_2026-03-01 ─┐
├▶ extract_prices_2026-05-01 │
├▶ extract_prices_2026-07-01 ├▶ build_gold ─▶ check_quality ─┬▶ freeze_reports ─┐
├▶ extract_prices_2026-09-01 │ └▶ export_marts ───┴▶ write_report
└▶ extract_prices_2026-11-07 ─┘A failed task runs again up to TCG_RETRIES times, with a growing pause. The gold layer and the checks are not retried: a wrong model does not become right by running again.
When a task still fails, every task that depends on it is skipped and the run ends as FAILED, naming them. Nothing downstream of an error is published.
Every attempt is a row of ops.pipeline_runs, with the run, the task, the attempt, the status and the start and end in Unix time.
The run of the rehearsal, on 07/11/2026. Almost all the time is the download of the catalogue and of the five archives; the gold layer, the checks and the reports take less than half a second together.
ok extract_sets 0.73 s 7 ok extract_products 7.29 s 1490 ok extract_prices_2026-03-01 2.99 s 657 ok extract_prices_2026-05-01 3.55 s 896 ok extract_prices_2026-07-01 9.86 s 1153 ok extract_prices_2026-09-01 3.24 s 1414 ok extract_prices_2026-11-07 3.65 s 1831 ok build_gold 0.04 s 4 files ok check_quality 0.07 s 5951 = 5951 · 524 cells ok freeze_reports 0.01 s kept ok export_marts 0.09 s 3 Parquet files ok write_report 0.17 s out/report.md run 2406b123fe8f: OK
out/report.md, now recomputed at every run.The tests replace the client of tcgcsv by a fake one, with two small sets, and check the behaviours that matter for a daily run. They take two seconds and never depend on the source being online.
| Test | What it proves |
|---|---|
test_a_batch_loaded_twice_is_replaced_not_duplicated | the load is idempotent |
test_timestamps_are_unix_integers | the convention of dates holds |
test_order_respects_dependencies_and_rejects_cycles | the graph is valid before it runs |
test_full_run_builds_gold_and_freezes_the_month | the whole pipeline works end to end |
test_second_run_keeps_the_frozen_report_and_the_grain | a rerun changes nothing that must stay |
test_a_month_with_two_captures_freezes_only_the_last | the semi-additive rule in the frozen report |
test_a_failure_is_retried_and_logged | the retry and the run log |
test_a_task_that_keeps_failing_skips_its_dependents | nothing is published after an error |
test_version | the command is installed |
Each student packages the DataApp of the group with the same architecture: three layers in one direction, an installable package with a command, an idempotent load, the gold layer of the group and tests that run without the network.
lab/lesson-7/tcg_dataapp/ as a model of structuregraded-activity-package/student-namepipeline.py by Prefect: the same tasks become a flow with scheduling, retries and monitoring in an interface.Readings and videos assigned on Adalove for this week, on the medallion architecture and on Python packaging, with the reading material of the session.
Databricks documentation on the Bronze, Silver and Gold layers and the incremental gain in data quality.
Medallion architecture illustrated with Python and PySpark code moving data between layers.
Official guide to project structure, configuration files and building a Python package.
Video walkthrough of package structure, pyproject.toml, wheels and local testing. The reading material of this session is Lesson 7 material.
DataApp Package with Layered Architecture · 27/11/2026 · Prof. Afonso
By the end of the session, students should be able to structure a DataApp as an installable Python package in three layers (Views, Processors and ETLs), with an idempotent load, quality gates and a pipeline of tasks with dependencies, retries and a run log that goes from the extraction to the gold layer in one command, and to package the DataApp of the group in the same way.
Demonstration followed by a graded activity. In the first hour the professor builds the package live with a coding agent in four steps (package and layers, ETLs, processors, pipeline and views), pasting each CREATE prompt and comparing each step with the reference package, while the slides explain the concept of the step; the package then runs end to end and its tests run without the network. In the second hour each student packages the DataApp of the group in the graded DataApp Packaging activity and delivers it by pull request.