Module 8 · Information Systems · Lesson 7 · Week 7

Instruction session · Friday, November 27, 2026 · one hour of demonstration, one hour of graded activity

DataApp Package with Layered Architecture

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.

Views · Processors · ETLspyproject.tomlIdempotent loadPipeline with retriesTests without networkGraded activity

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 building the package, one hour packaging your DataApp

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.

0:20 · step 01Package and layersAgent: pyproject.toml, config.py, cli.pyPython packaging; the three layers and their direction
0:28 · step 02ETLsAgent: etls/Extraction from TCGplayer; the idempotent load of a batch
0:38 · step 03ProcessorsAgent: processors/The gold layer of Lesson 6 as package data; quality gates
0:46 · step 04Pipeline and viewsAgent: pipeline.py, views/A DAG with retries and a run log; report and Parquet
1:00 · gradedDataApp PackagingEach studentThe DataApp of the group in three layers, delivered by pull request
Where the work happensOn the computer, in a terminal: a virtual environment, pip install -e ., the command tcg-dataapp and pytest. The reference package is in lab/lesson-7/tcg_dataapp/ of the module.
0:15 · From the lab to a package
Every manual step of Lesson 6 becomes code

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 6In the packageLayer
the professor captured the data once, by scriptetls/tcgcsv.py and etls/extract.py, at every runETLs
the JSON was kept in the localStorageetls/landing.py: db_ingestion in a DuckDB file, loaded in replaceable batchesETLs
the SQL of steps 01 to 04 was pasted in the editorprocessors/sql/*.sql, run by processors/gold.pyProcessors
the grain test was read on the screenprocessors/quality.py stops the run when it failsProcessors
the five questions were run by handviews/questions.py, out/report.md and out/marts/*.parquetViews
the order of the steps was in the head of the professorpipeline.py: tasks, dependencies, retries and a logpipeline
0:17 · Architecture
Three layers, each one depending only on the layer below

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.

Views

What the users read

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.

Processors

The rules of the model

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.

ETLs

The movement of data

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.

Why one directionIf the ETLs imported the views, a change of a report could break the extraction. With 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.
0:19 · Lab of the session
What the lab shows, from the API to the daily run

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.

Source · step 02

tcgcsv.com

The public daily mirror of TCGplayer, with no key.

  • /3/groups7 of 221
  • /3/{set}/products7 calls
  • prices-{day}.ppmd.7z5 × ~4 MB
▶
ETLs · step 02

db_ingestion

timestampBIGINT, Unixdata_jsonas it arriveddata_tagentity.v1
  • tcgplayer.set.v17
  • tcgplayer.product.v11,492
  • tcgplayer.price.v1 · 5 batches5,951

A batch loaded twice is replaced, not added.

▶
Processors · step 03

gold

Four SQL files of the package, every object a view over db_ingestion.

  • fact_price = grain keys5,951
  • agg_price_cube524 cells
  • mv_card_price_2026_091,226 frozen
▶
Views · step 04

out/

The five questions in report.md and three Parquet files of the marts.

pipeline.py · tcg-dataapp run · step 04
The boxes above as 12 tasks with dependencies, retries and a log in ops.pipeline_runs, in about 40 s.
ops/run_daily.sh + cron · step 05, in the lab
Every day at 06:00 UTC, one run at a time, one log per day and a line in out/alerts.log when it fails.
Open the lab →

Step 01 · 0:20 · Package

The skeleton of the 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.

Files

pyproject.toml, src/tcg_dataapp/{etls,processors,views}/, config.py, cli.py, tests/test_cli.py.

Review before moving on
  • Does pip install -e '.[dev]' work in a new virtual environment?
  • Does tcg-dataapp --version answer 0.1.0?
  • Does each layer say in its docstring what it may import?
Prompt 01 · CREATE
[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.
Step 01 · Theory
What makes a folder an installable package

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.

PieceIn tcg-dataappWhy
build systemsetuptoolsturns the project into a wheel that pip installs
src layoutsrc/tcg_dataapp/the tests import the installed package, not a loose folder
dependenciesduckdb, py7zr; extra dev with pytestthe environment is reproducible from the file
entry pointtcg-dataapp = tcg_dataapp.cli:mainone command for people and for the scheduler
package dataprocessors/sql/*.sqlthe SQL travels inside the wheel
editable installpip install -e .a change in the code is live without reinstalling
tcg_dataapp/
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_*.py

Step 02 · 0:28 · ETLs

Extraction and an idempotent load

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.

Files

etls/tcgcsv.py, etls/landing.py, etls/extract.py, tests/test_landing.py.

Review before moving on
  • Is a batch (tag and timestamp) loaded twice replaced, not duplicated?
  • Are the timestamps BIGINT, in Unix time?
  • Do the five archives give 657, 896, 1,153, 1,414 and 1,831 prices?
Prompt 02 · CREATE
[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.
Step 02 · Theory
Idempotency: the same run twice gives the same table

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 batch

Tag + timestamp

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 price of today

Noon UTC of the day

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 archive

One past day

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.

A trap of DuckDB 2.0The result of 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 gold layer of Lesson 6, now inside the package

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.

Files

processors/sql/01..04_*.sql, processors/gold.py, processors/quality.py.

Review before moving on
  • Do the dimensions keep only the last version of each set and product?
  • 5,951 rows = 5,951 keys of the grain, 524 cells, 1,226 rows frozen in September?
  • After a second run, is the frozen report "kept" and the fact still 5,951 rows?
Prompt 03 · CREATE
[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.
Step 03 · Theory
A model that runs every day

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.

Last version wins

Slowly changing dimension, type 1

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.

Quality gates

The run stops

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.

Frozen once

The last capture of the month

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.

Runset recordsproduct recordsfact rows = grain keysfrozen report
first71,4905,951 = 5,951created (1,226 rows)
second142,9805,951 = 5,951kept

Step 04 · 0:46 · Pipeline and views

The pipeline that runs everything, and what it delivers

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.

Files

views/questions.py, views/report.py, pipeline.py, cli.py, tests/conftest.py, tests/test_pipeline.py.

Review before moving on
  • Does tcg-dataapp run end with twelve tasks ok?
  • Are there out/report.md and three Parquet files?
  • Do the 9 tests pass without network?
Prompt 04 · CREATE
[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.
Step 04 · Theory
A pipeline is a graph of tasks

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.

the twelve tasks of tcg-dataapp run
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 ─┘
Retries

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.

Skips

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.

Run log

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.

Step 04 · Result
One command, twelve tasks, about forty seconds

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.

tcg-dataapp run
  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
12 / 12tasks ok, logged in ops.pipeline_runs
9 passedpytest in about 2 s, without network
The same answers as the labPikachu ex 276/217 frozen at US$ 1,049.08 in September; the five answers of Lesson 6 in out/report.md, now recomputed at every run.
Step 04 · Tests
Testing a pipeline without the network

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.

TestWhat it proves
test_a_batch_loaded_twice_is_replaced_not_duplicatedthe load is idempotent
test_timestamps_are_unix_integersthe convention of dates holds
test_order_respects_dependencies_and_rejects_cyclesthe graph is valid before it runs
test_full_run_builds_gold_and_freezes_the_monththe whole pipeline works end to end
test_second_run_keeps_the_frozen_report_and_the_graina rerun changes nothing that must stay
test_a_month_with_two_captures_freezes_only_the_lastthe semi-additive rule in the frozen report
test_a_failure_is_retried_and_loggedthe retry and the run log
test_a_task_that_keeps_failing_skips_its_dependentsnothing is published after an error
test_versionthe command is installed
1:00 · Second hour · graded
DataApp Packaging

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.

What to use
  • the four prompts of this session, adapted to the partner data
  • the reference package lab/lesson-7/tcg_dataapp/ as a model of structure
  • the gold layer that the group built in Lesson 6
How to deliver
  • the statement is the DataApp Packaging activity on Adalove
  • individual work on a branch graded-activity-package/student-name
  • a pull request with the documentation of the package; only the link is submitted
  • deadline: Friday, 27/11, the day of the session
Next sessionLesson 8 replaces the runner of pipeline.py by Prefect: the same tasks become a flow with scheduling, retries and monitoring in an interface.
Self-study
Self-study for this session

Readings and videos assigned on Adalove for this week, on the medallion architecture and on Python packaging, with the reading material of the session.

About this session

DataApp Package with Layered Architecture · 27/11/2026 · Prof. Afonso

Learning objective

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.

Session strategy

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.

Session structure

  1. Daily — 15 min
  2. From the lab to a package; the three layers — 5 min
  3. Step 01: pyproject.toml, src layout and the layers — 8 min
  4. Step 02: ETLs and the idempotent load — 10 min
  5. Step 03: the gold layer as package data and quality gates — 8 min
  6. Step 04: pipeline, views, run and tests — 14 min
  7. Graded DataApp Packaging activity — 60 min