Module 8 · Information Systems · Lesson 7 · Week 7

DataApp Package with Layered Architecture

Reference material for the session in which the professor builds, live and with a coding agent, a Python package that automates everything Lesson 6 did by hand: the extraction of the TCGplayer prices, the idempotent load of the landing table, the gold layer and its quality gates, the frozen and live reports and the five answers, in three layers and one pipeline with retries and a run log. In the second hour each student packages the DataApp of the group in the graded activity.

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
Part IFoundations

1. How to read this material

This material accompanies Lesson 7, which has two hours. In the first, the professor builds live, with a coding agent and four CREATE prompts, a Python package that does on its own everything that Lesson 6 did by hand in the lab of the browser. In the second hour each student packages the DataApp of the group in the graded DataApp Packaging activity, whose statement and criteria are given in class and are not kept in this public repository.

Part I explains why a DataApp needs a package and how its three layers divide the work. Parts II to V follow the four steps of the session: the package, the ETL layer, the processor layer, and the pipeline with the view layer. Part VI gathers the prompts, the tests, the reference numbers and the mistakes found in the rehearsal. Every number was measured on 07/11/2026 with the reference package of lab/lesson-7/tcg_dataapp/, DuckDB 2.0.0 and Python 3.12; every date is Unix time in seconds, as in Lesson 6.

2. From the lab to a DataApp

The lab of Lesson 6 answered five questions about the prices of the Pokémon TCG sets of 2026, once, with a person who pasted SQL into an editor and read the results. A DataApp answers the same questions every day without a person: it fetches new prices, rebuilds the model, checks it and publishes the answers, and when one of these steps fails it must say which one and leave the published data as it was. Each manual step of the lab therefore becomes a function that can run, fail, be retried and be tested, and the order of the steps, which in the lab was in the head of the professor, becomes a graph of tasks.

In the lab of Lesson 6In the packageLayer
the data captured once, by a script of the professoretls/tcgcsv.py and etls/extract.py, at every runETLs
the JSON kept in the localStorageetls/landing.py: db_ingestion in a DuckDB file, loaded in replaceable batchesETLs
the SQL of steps 01 to 04 pasted in the editorprocessors/sql/*.sql, run by processors/gold.pyProcessors
the grain test read on the screenprocessors/quality.py, which stops the runProcessors
the five questions run by handviews/questions.py, out/report.md, out/marts/*.parquetViews
the order of the stepspipeline.py: tasks, dependencies, retries and a logpipeline

3. Layered architecture

A layered architecture divides an application by responsibility and lets each layer depend only on the layer below it. In the DataApp the view layer holds what users read, the processor layer holds the rules that build it, and the ETL layer holds the movement of data from the source to the landing table. The direction views → processors → etls is a constraint on the imports of the code: the ETLs never import a view, and the views never read the landing table directly.

The constraint has two consequences that justify its cost. A change in a report cannot break the extraction, because nothing in the extraction depends on the report. And each layer can be tested alone: the extraction with a fake source, the processors with a small landing table, the views over a small gold layer. The tests of the reference package do exactly this, with a fake client of TCGplayer that has two sets and a handful of prices, and they run in two seconds without the network.

The three layers of the DataApp correspond to the medallion layers of Lesson 5 and of the self-study of this week, read from a different angle. The ETL layer writes the Bronze, kept as it arrived; the processor layer turns it into the Silver and Gold layers of the model; the view layer is what is served from the Gold layer. The medallion describes the state of the data, and the layers describe the code that moves it.

Part IIThe package

4. What makes a folder an installable package

A package is code with a declared name, version, dependencies and entry points, which any machine installs in the same way. Since PEP 621, all of this is declared in one file, pyproject.toml, which replaces the older setup.py. The reference package uses setuptools as build backend and the src layout, in which the code lives in src/tcg_dataapp/, so that the tests import the installed package and not a loose folder that happens to be in the current directory.

pyproject.toml of the reference package
[build-system]
requires = ["setuptools>=69"]
build-backend = "setuptools.build_meta"

[project]
name = "tcg-dataapp"
version = "0.1.0"
description = "DataApp of Lesson 6 as a package: TCGplayer prices from extraction to the gold layer, in three layers and one pipeline"
readme = "README.md"
requires-python = ">=3.11"
dependencies = [
    "duckdb>=1.4,<3",
    "py7zr>=0.22",
]

[project.optional-dependencies]
dev = ["pytest>=8"]

[project.scripts]
tcg-dataapp = "tcg_dataapp.cli:main"

[tool.setuptools.packages.find]
where = ["src"]

[tool.setuptools.package-data]
"tcg_dataapp.processors" = ["sql/*.sql"]

[tool.pytest.ini_options]
testpaths = ["tests"]
PieceIn tcg-dataappWhy
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 and is read with importlib.resources
editable installpip install -e '.[dev]'a change in the code is live without reinstalling

5. Configuration by environment

The settings of the DataApp are read from environment variables, with defaults that reproduce the lesson: the path of the DuckDB file, the folder of the outputs, the sets, the capture dates, the frozen month, the number of retries and the pause between them. The same package then runs in class, on a server or in the scheduler of Lesson 8 without a change in the code, and a test passes its own settings, with a temporary folder, without touching the files of the user.

src/tcg_dataapp/config.py
"""Settings of the DataApp, read from environment variables with defaults.

Every date is Unix time in seconds (UTC), as in Lesson 6.
"""
from __future__ import annotations

import os
from dataclasses import dataclass, field
from pathlib import Path

# Pokemon TCG sets released in 2026 (groupId on TCGplayer).
DEFAULT_SETS = (24541, 24587, 24655, 24688, 24722, 24837, 24831)
# Daily archives of tcgcsv used as capture dates, as in Lesson 6.
DEFAULT_PRICE_DATES = ("2026-03-01", "2026-05-01", "2026-07-01", "2026-09-01", "2026-11-07")


def _list(name: str, default: tuple) -> tuple:
    raw = os.environ.get(name)
    return tuple(x.strip() for x in raw.split(",") if x.strip()) if raw else default


@dataclass(frozen=True)
class Settings:
    db_path: Path = field(default_factory=lambda: Path(os.environ.get("TCG_DB_PATH", "warehouse/tcg.duckdb")))
    out_dir: Path = field(default_factory=lambda: Path(os.environ.get("TCG_OUT_DIR", "out")))
    base_url: str = field(default_factory=lambda: os.environ.get("TCG_BASE_URL", "https://tcgcsv.com"))
    category: int = field(default_factory=lambda: int(os.environ.get("TCG_CATEGORY", "3")))
    sets: tuple = field(default_factory=lambda: tuple(int(x) for x in _list("TCG_SETS", DEFAULT_SETS)))
    price_dates: tuple = field(default_factory=lambda: _list("TCG_PRICE_DATES", DEFAULT_PRICE_DATES))
    frozen_month: str = field(default_factory=lambda: os.environ.get("TCG_FROZEN_MONTH", "2026-09"))
    retries: int = field(default_factory=lambda: int(os.environ.get("TCG_RETRIES", "3")))
    retry_delay: float = field(default_factory=lambda: float(os.environ.get("TCG_RETRY_DELAY", "2")))
Part IIIThe ETL layer

6. The source: tcgcsv.com and its archives

The official API of TCGplayer requires a key granted to partners, and tcgcsv.com publishes every day a public copy of its catalogue and prices, without a key. The client of the package reads three endpoints for each set, the groups, the products and the prices of today, and one file per past day, the daily archive of prices, a 7z file with every category of TCGplayer. Of the 4,603 files of an archive, the client extracts only the files of the seven sets, which takes about three seconds per day.

The client sends a User-Agent and pauses for 0.2 seconds between calls, which is the courtesy that a public mirror expects. It raises an error when the source answers without success, and the pipeline turns that error into a retry. The source does not send the header that would allow a page of another site to read it, which is why Lesson 6 kept a captured copy in the lab and this lesson reads it from Python.

7. The landing table and the idempotent load

A pipeline is rerun after a failure, by a scheduler or by mistake, and an idempotent load makes the result independent of how many times it ran. The landing table keeps the three columns of Lesson 6 (timestamp in Unix time, data_json and data_tag), and the unit of load is the batch: the records of one tag captured at one timestamp. load_batch deletes the batch and inserts it again inside one transaction, so a second load of the same batch replaces the first, and a failure in the middle leaves the previous batch in place.

src/tcg_dataapp/etls/landing.py
"""The landing table db_ingestion: three columns, every record as it arrived.

    timestamp  BIGINT   Unix time of the capture (seconds, UTC)
    data_json  JSON     the record, with the field names of TCGplayer
    data_tag   VARCHAR  tcgplayer.set.v1, tcgplayer.product.v1 or tcgplayer.price.v1

A batch is the set of records of one tag captured at one timestamp. Loading
the same batch again replaces it, so a rerun never duplicates rows.
"""
from __future__ import annotations

import json

import duckdb

DDL = """
CREATE TABLE IF NOT EXISTS db_ingestion (
    timestamp BIGINT  NOT NULL,
    data_json JSON    NOT NULL,
    data_tag  VARCHAR NOT NULL
)
"""


def run(con: duckdb.DuckDBPyConnection, sql: str, params: list | None = None) -> list:
    """Execute one statement and consume its result.

    DuckDB 2.0 keeps the result of execute() open until it is read, and the
    next statement on the same connection fails while it is open.
    """
    return con.execute(sql, params or []).fetchall()


def ensure_table(con: duckdb.DuckDBPyConnection) -> None:
    run(con, DDL)


def load_batch(con: duckdb.DuckDBPyConnection, data_tag: str, timestamp: int, records: list[dict],
               extra_filter: tuple[str, list] | None = None) -> int:
    """Replace the batch (data_tag, timestamp) with the given records; return the rows written.

    extra_filter narrows what is replaced inside the batch, for loads split in
    parts, such as the prices of one set: ("data_json->>'groupId' = ?", [24541]).
    """
    ensure_table(con)
    where = "data_tag = ? AND timestamp = ?"
    params: list = [data_tag, timestamp]
    if extra_filter:
        where += f" AND {extra_filter[0]}"
        params += extra_filter[1]
    run(con, "BEGIN TRANSACTION")
    try:
        run(con, f"DELETE FROM db_ingestion WHERE {where}", params)
        if records:
            con.executemany(
                "INSERT INTO db_ingestion VALUES (?, ?, ?)",
                [(timestamp, json.dumps(r, separators=(",", ":"), ensure_ascii=False), data_tag) for r in records],
            ).fetchall()
        run(con, "COMMIT")
    except Exception:
        run(con, "ROLLBACK")
        raise
    return len(records)


def counts(con: duckdb.DuckDBPyConnection) -> list[tuple]:
    """Rows and Unix time range per tag; works on a read-only connection."""
    return run(con, "SELECT data_tag, count(*), min(timestamp), max(timestamp) FROM db_ingestion GROUP BY 1 ORDER BY 1")

The choice of the timestamp decides what counts as the same batch. The prices of a past date are loaded at noon UTC of that date, and the prices of today at noon UTC of today, not at the moment of the run: two runs on the same day then produce the same batch, and the model keeps one price per product and day. The catalogue, on the other hand, is loaded at the moment of the run, which keeps a history of its versions and moves the duty of choosing one to the processors.

Part IVThe processor layer

8. The gold layer as package data

The SQL of Lesson 6 becomes four files of the package, read with importlib.resources and run statement by statement by build_gold: the dimensions, the fact, the cube and the mart, all views, and the live reports. The check queries that the lab showed on the screen leave these files, because in a pipeline nobody reads them; their role passes to the quality gates.

src/tcg_dataapp/processors/gold.py
"""Builds the gold layer from the SQL files of the package and freezes monthly reports."""
from __future__ import annotations

import re
from importlib import resources

import duckdb

from tcg_dataapp.etls.landing import run

SQL_FILES = ("01_dimensions.sql", "02_fact.sql", "03_cube_and_mart.sql", "04_live_reports.sql")


def sql_text(name: str) -> str:
    return resources.files("tcg_dataapp.processors").joinpath("sql", name).read_text(encoding="utf-8")


def build_gold(con: duckdb.DuckDBPyConnection) -> list[str]:
    """Create or replace every view of gold, mart_collectors and the live reports."""
    for name in SQL_FILES:
        for statement in con.extract_statements(sql_text(name)):
            con.execute(statement).fetchall()
    return list(SQL_FILES)


def freeze_month(con: duckdb.DuckDBPyConnection, month: str) -> dict:
    """Materialize the reports of one month (YYYY-MM), once. An existing frozen report is kept as it is.

    A month can have more than one capture; the report takes the last one, because
    the price is semi-additive and two captures of the same card must not add up.
    """
    if not re.fullmatch(r"\d{4}-\d{2}", month):
        raise ValueError(f"month must be YYYY-MM, got {month!r}")
    suffix = month.replace("-", "_")
    run(con, "CREATE SCHEMA IF NOT EXISTS report")
    result = {}
    for name, source, columns in (
        (f"mv_card_price_{suffix}", "mart_collectors.card_price", "set_name, card, rarity, variant, market_price"),
        (f"mv_set_value_{suffix}", "mart_collectors.set_value", "set_name, prices, market_value"),
    ):
        exists = run(con, "SELECT count(*) FROM duckdb_tables() WHERE schema_name = 'report' AND table_name = ?", [name])[0][0]
        if exists:
            result[name] = "kept"
            continue
        last = f"(SELECT max(captured_at) FROM {source} WHERE month = ?)"
        rows = run(con, f"SELECT count(*) FROM {source} WHERE captured_at = {last}", [month])[0][0]
        if rows == 0:
            result[name] = "no data"
            continue
        run(con, f"CREATE TABLE report.{name} AS SELECT captured_at, {columns} FROM {source} WHERE captured_at = {last}", [month])
        result[name] = f"created ({rows} rows)"
    return result

9. A catalogue captured every day

In the lab the catalogue was captured once, and each set and product appeared once in the landing table. Running daily, the same set and product arrive again at every run, and a dimension that reads every record of its tag would have two versions of each product after the second run, which doubles every price of the fact through the join. The dimensions of the package keep only the last version of each id, which is a slowly changing dimension of type 1: the current attributes replace the old ones, and the history stays in the landing table.

the last version of each product, in processors/sql/01_dimensions.sql
QUALIFY row_number() OVER (PARTITION BY data_json->>'productId'
                           ORDER BY timestamp DESC) = 1;
Runset recordsproduct recordsfact rows = grain keysfrozen report
first71,4905,951 = 5,951created (1,226 rows)
second142,9805,951 = 5,951kept

10. Quality gates and frozen reports

A model that nobody reads before it is published needs checks that stop the run. check_gold raises an error when a tag of the landing table is empty, when the number of rows of the fact differs from the number of distinct keys of its grain, or when a price has no set; otherwise it returns the numbers it measured, which the run log keeps. The pipeline does not retry these checks, because a wrong model does not become right by running again, and it skips every report that depends on them, so a wrong number is never published.

src/tcg_dataapp/processors/quality.py
"""Checks that stop the pipeline when the gold layer is wrong."""
from __future__ import annotations

import duckdb

from tcg_dataapp.etls.landing import run


class QualityError(RuntimeError):
    pass


def check_gold(con: duckdb.DuckDBPyConnection) -> dict:
    """Return the measured numbers, or raise QualityError naming the check that failed."""
    m = {}
    for tag in ("tcgplayer.set.v1", "tcgplayer.product.v1", "tcgplayer.price.v1"):
        m[tag] = run(con, "SELECT count(*) FROM db_ingestion WHERE data_tag = ?", [tag])[0][0]
        if m[tag] == 0:
            raise QualityError(f"db_ingestion has no rows of {tag}")
    rows, keys = run(con, "SELECT count(*), count(DISTINCT (date_unix, product_id, variant)) FROM gold.fact_price")[0]
    m["fact_rows"], m["fact_grain_keys"] = rows, keys
    if rows != keys:
        raise QualityError(f"grain of gold.fact_price broken: {rows} rows for {keys} keys")
    orphans = run(con, "SELECT count(*) FROM gold.fact_price f LEFT JOIN gold.dim_set s ON s.set_id = f.set_id WHERE s.set_id IS NULL")[0][0]
    m["fact_without_set"] = orphans
    if orphans:
        raise QualityError(f"{orphans} prices of gold.fact_price have no set in gold.dim_set")
    m["dates"] = run(con, "SELECT count(*) FROM gold.dim_date")[0][0]
    m["cube_cells"] = run(con, "SELECT count(*) FROM gold.agg_price_cube")[0][0]
    return m

The frozen reports of Lesson 6 become a function of the month. freeze_month creates the tables of a month only if they do not exist, which is what keeps them frozen across daily runs, and it takes the last capture of that month: when a month has two captures, as November has after a run with the prices of today, the two prices of the same card must not add up, because the price is semi-additive. The month is validated as YYYY-MM before it becomes part of the name of a table.

Part VPipeline and views

11. The pipeline as a graph of tasks

Each task of the pipeline is a function of the run context, with a name and the names of the tasks it depends on. Before anything runs, order sorts the tasks so that each one comes after its dependencies, and refuses an unknown dependency or a cycle. The run then executes the tasks in that order, with the extraction of each capture date as a task of its own, so that a failure in one archive names the date that failed.

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 ─┘

A failed task runs again up to TCG_RETRIES times, with a pause that grows with each attempt, which absorbs the brief failures of a network source. A task that still fails is recorded as failed, every task that depends on it is skipped, and the run ends as FAILED, naming them. 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, which makes a run auditable after the fact; tcg-dataapp status reads that table.

src/tcg_dataapp/pipeline.py
"""The pipeline: tasks with dependencies, run in order, with retries and a log of every run.

Each task is a function of the run context. A task runs only after all the
tasks it depends on succeeded; a failure is retried, and a task that still
fails stops every task that depends on it. Every attempt is recorded in
ops.pipeline_runs, with Unix times, so a run can be audited afterwards.
"""
from __future__ import annotations

import time
import uuid
from dataclasses import dataclass, field
from typing import Callable

import duckdb

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

LOG_DDL = """
CREATE SCHEMA IF NOT EXISTS ops;
CREATE TABLE IF NOT EXISTS ops.pipeline_runs (
    run_id     VARCHAR,
    task       VARCHAR,
    attempt    INTEGER,
    status     VARCHAR,
    started_at BIGINT,
    ended_at   BIGINT,
    detail     VARCHAR
);
"""


@dataclass
class Task:
    name: str
    run: Callable[["Context"], object]
    depends_on: tuple = ()
    retries: int | None = None


@dataclass
class Context:
    settings: Settings
    con: duckdb.DuckDBPyConnection
    client: TcgcsvClient
    run_id: str
    captured_at: int
    results: dict = field(default_factory=dict)


def build_tasks(settings: Settings, with_today: bool = False) -> list[Task]:
    tasks = [
        Task("extract_sets", lambda c: extract.extract_sets(c.con, c.client, c.settings.sets, c.captured_at)),
        Task("extract_products", lambda c: extract.extract_products(c.con, c.client, c.settings.sets, c.captured_at),
             depends_on=("extract_sets",)),
    ]
    price_tasks = []
    for day in settings.price_dates:
        name = f"extract_prices_{day}"
        tasks.append(Task(name, lambda c, d=day: extract.extract_prices_archive(c.con, c.client, c.settings.sets, d),
                          depends_on=("extract_products",)))
        price_tasks.append(name)
    if with_today:
        tasks.append(Task("extract_prices_today",
                          lambda c: extract.extract_prices_today(c.con, c.client, c.settings.sets, extract.today()),
                          depends_on=("extract_products",)))
        price_tasks.append("extract_prices_today")
    tasks += [
        Task("build_gold", lambda c: gold.build_gold(c.con), depends_on=tuple(price_tasks), retries=0),
        Task("check_quality", lambda c: quality.check_gold(c.con), depends_on=("build_gold",), retries=0),
        Task("freeze_reports", lambda c: gold.freeze_month(c.con, c.settings.frozen_month),
             depends_on=("check_quality",), retries=0),
        Task("export_marts", lambda c: [p.as_posix() for p in report.export_marts(c.con, c.settings.out_dir)],
             depends_on=("check_quality",)),
        Task("write_report", lambda c: report.write_report(c.con, c.settings.out_dir, c.run_id).as_posix(),
             depends_on=("freeze_reports", "export_marts")),
    ]
    return tasks


def order(tasks: list[Task]) -> list[Task]:
    """Topological order of the tasks; raises on an unknown dependency or a cycle."""
    by_name = {t.name: t for t in tasks}
    for t in tasks:
        for d in t.depends_on:
            if d not in by_name:
                raise ValueError(f"task {t.name} depends on unknown task {d}")
    done, ordered, visiting = set(), [], set()

    def visit(t: Task):
        if t.name in done:
            return
        if t.name in visiting:
            raise ValueError(f"cycle at task {t.name}")
        visiting.add(t.name)
        for d in t.depends_on:
            visit(by_name[d])
        visiting.discard(t.name)
        done.add(t.name)
        ordered.append(t)

    for t in tasks:
        visit(t)
    return ordered


def _log(con, run_id, task, attempt, status, started, ended, detail):
    con.execute("INSERT INTO ops.pipeline_runs VALUES (?, ?, ?, ?, ?, ?, ?)",
                [run_id, task, attempt, status, started, ended, str(detail)[:500]]).fetchall()


def run(settings: Settings, tasks: list[Task] | None = None, client: TcgcsvClient | None = None,
        con: duckdb.DuckDBPyConnection | None = None, with_today: bool = False,
        echo: Callable[[str], None] = print) -> Context:
    own = con is None
    if own:
        settings.db_path.parent.mkdir(parents=True, exist_ok=True)
        con = duckdb.connect(str(settings.db_path))
    for statement in con.extract_statements(LOG_DDL):
        con.execute(statement).fetchall()
    ctx = Context(settings=settings, con=con,
                  client=client or TcgcsvClient(settings.base_url, settings.category),
                  run_id=uuid.uuid4().hex[:12], captured_at=extract.now_unix())
    failed: set[str] = set()
    try:
        for task in order(tasks or build_tasks(settings, with_today)):
            if any(d in failed for d in task.depends_on):
                failed.add(task.name)
                _log(con, ctx.run_id, task.name, 0, "skipped", extract.now_unix(), extract.now_unix(), "a dependency failed")
                echo(f"  skip  {task.name}  (a dependency failed)")
                continue
            attempts = 1 + (settings.retries if task.retries is None else task.retries)
            for attempt in range(1, attempts + 1):
                started = extract.now_unix()
                t0 = time.perf_counter()
                try:
                    result = task.run(ctx)
                except Exception as error:  # noqa: BLE001 - every failure is logged and retried
                    _log(con, ctx.run_id, task.name, attempt, "failed", started, extract.now_unix(),
                         f"{type(error).__name__}: {error}")
                    echo(f"  fail  {task.name}  attempt {attempt}/{attempts}: {type(error).__name__}: {error}")
                    if attempt == attempts:
                        failed.add(task.name)
                    else:
                        time.sleep(settings.retry_delay * attempt)
                    continue
                ctx.results[task.name] = result
                _log(con, ctx.run_id, task.name, attempt, "success", started, extract.now_unix(), result)
                echo(f"  ok    {task.name}  {time.perf_counter() - t0:5.2f} s  {result}")
                break
    finally:
        if own:
            con.close()
    ctx.results["_failed"] = sorted(failed)
    return ctx

12. The view layer

The view layer turns the gold layer into what users read: the five questions of Lesson 6, each one a query over the cube or the mart; a report in Markdown with one table per question; and the Parquet files of the marts, which a dashboard or a notebook reads without the DuckDB file. The questions read the last capture of the model, SELECT max(date_unix) FROM gold.dim_date, instead of the fixed date of the lab, so the report follows each new run; the question of the value of each set uses the last capture of each month, for the same semi-additive reason as the frozen reports.

src/tcg_dataapp/views/questions.py
"""The five questions of Lesson 6, each one an OLAP operation over the cube or the mart.

The dates are not fixed: every question reads the last capture of the model.
"""
from __future__ import annotations

import duckdb

LAST = "(SELECT max(date_unix) FROM gold.dim_date)"

QUESTIONS = {
    "q1_rarity_rollup": (
        "Roll-up: average and maximum market price of a card of each rarity, on the last capture",
        f"""SELECT rarity, prices, avg_market_price, max_market_price
            FROM gold.agg_price_cube WHERE grouping_id = 5 AND date_unix = {LAST}
            ORDER BY avg_market_price DESC""",
    ),
    "q2_top_cards_slice": (
        "Slice: the five most expensive cards of Ascended Heroes (ASC), on the last capture",
        f"""SELECT card, rarity, variant, market_price
            FROM mart_collectors.card_price WHERE set_code = 'ASC' AND captured_at = {LAST}
            ORDER BY market_price DESC LIMIT 5""",
    ),
    "q3_set_value_by_month": (
        "Pivot: market value of each set on the last capture of each month (semi-additive: one capture at a time)",
        """SELECT set_name, month, market_value
           FROM mart_collectors.set_value
           QUALIFY captured_at = max(captured_at) OVER (PARTITION BY month)
           ORDER BY set_name, month""",
    ),
    "q4_variant_dice": (
        "Dice: average price of each variant of the four lowest rarities, on the last capture",
        f"""SELECT rarity, variant, avg_market_price
            FROM gold.agg_price_cube
            WHERE grouping_id = 4 AND date_unix = {LAST}
              AND rarity IN ('Common', 'Uncommon', 'Rare', 'Double Rare')
            ORDER BY rarity, variant""",
    ),
    "q5_appreciation": (
        "The cards that appreciated most between their first and their last capture (first price >= US$ 5)",
        """WITH first_and_last AS (
                SELECT set_code, card, rarity, variant,
                       arg_min(market_price, captured_at) AS first_price,
                       min(captured_at)                   AS first_captured_at,
                       arg_max(market_price, captured_at) AS last_price
                FROM mart_collectors.card_price
                WHERE market_price IS NOT NULL
                GROUP BY ALL
                HAVING count(*) >= 2)
           SELECT set_code, card, rarity, variant, first_captured_at, first_price, last_price,
                  last_price - first_price AS gain_usd,
                  round(100 * (last_price / first_price - 1), 1) AS gain_pct
           FROM first_and_last WHERE first_price >= 5
           ORDER BY gain_pct DESC LIMIT 10""",
    ),
}


def answer(con: duckdb.DuckDBPyConnection, key: str) -> tuple[list[str], list[tuple]]:
    relation = con.sql(QUESTIONS[key][1])
    return relation.columns, relation.fetchall()


def answer_all(con: duckdb.DuckDBPyConnection) -> dict:
    return {key: answer(con, key) for key in QUESTIONS}

13. Running every day

The package has no scheduler: tcg-dataapp run runs once and ends. To run it every day, one line of crontab is enough, and the run log keeps what each execution did. A scheduler of the operating system, however, does not show the graph, does not retry a run that did not start and does not alert anyone; Lesson 8 replaces the runner of pipeline.py with Prefect, where the same tasks become a flow with scheduling, retries and monitoring in an interface.

crontab: every day at 06:00 UTC
0 6 * * * cd /path/to/project && .venv/bin/tcg-dataapp run --with-today >> out/cron.log 2>&1
Part VILab

14. The lab in four steps

The professor builds the package in a new folder with the four prompts below and compares each step with the reference package. Each prompt states the facts measured in the rehearsal, so that both the agent and the class can check the result.

Step 01 · Package and layers

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.

Review before moving on:

  • pip install -e '.[dev]' works in a new virtual environment
  • tcg-dataapp --version answers 0.1.0
  • each layer says what it may import

Step 02 · ETLs

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.

Review before moving on:

  • a batch loaded twice is replaced, not duplicated
  • the timestamps are BIGINT
  • the five archives give 657, 896, 1,153, 1,414 and 1,831 prices

Step 03 · Processors

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.

Review before moving on:

  • 5,951 rows = 5,951 keys of the grain; 524 cells; 1,226 rows frozen in September
  • a second run keeps the fact at 5,951 rows and the frozen report as it was

Step 04 · Pipeline and views

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.

Review before moving on:

  • tcg-dataapp run ends with twelve tasks ok in about 40 s
  • out/report.md and three Parquet files
  • 9 tests pass without network

15. Testing without the network

The tests replace the client of tcgcsv by a fake one with two sets, three products of the first and one of the second, and prices on two dates. The second set repeats the code of the first on purpose, as TCGplayer does with the code 30C, and the fake source also lists a set that the settings do not ask for. The nine tests run in about 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
tests/conftest.py
"""A fake TCGplayer with two sets, so the tests run without network."""
from __future__ import annotations

import pytest

from tcg_dataapp.config import Settings

SETS = {
    1: {"groupId": 1, "name": "Test Set One", "abbreviation": "TS1", "publishedOn": "2026-07-01T00:00:00", "categoryId": 3},
    2: {"groupId": 2, "name": "Test Set Two", "abbreviation": "TS1", "publishedOn": "2026-08-01T00:00:00", "categoryId": 3},
}


def card(pid, gid, name, number, rarity):
    return {"productId": pid, "groupId": gid, "name": name, "imageUrl": "x",
            "extendedData": [{"name": "Number", "value": number}, {"name": "Rarity", "value": rarity},
                             {"name": "CardText", "value": "long text"}]}


PRODUCTS = {
    1: [card(11, 1, "Card A", "001/010", "Common"), card(12, 1, "Card B", "002/010", "Rare"),
        {"productId": 13, "groupId": 1, "name": "Booster Box", "extendedData": []}],
    2: [card(21, 2, "Card C", "001/020", "Common")],
}
# prices per day of capture
PRICES = {
    "2026-08-01": {1: [{"productId": 11, "marketPrice": 1.0, "subTypeName": "Normal"},
                       {"productId": 12, "marketPrice": 10.0, "subTypeName": "Holofoil"}]},
    "2026-09-01": {1: [{"productId": 11, "marketPrice": 2.0, "subTypeName": "Normal"},
                       {"productId": 12, "marketPrice": 8.0, "subTypeName": "Holofoil"},
                       {"productId": 13, "marketPrice": 100.0, "subTypeName": "Normal"}],
                   2: [{"productId": 21, "marketPrice": 0.5, "subTypeName": "Normal"}]},
}


class FakeClient:
    def __init__(self, fail_times: int = 0):
        self.fail_times = fail_times
        self.calls = 0

    def groups(self):
        self.calls += 1
        if self.calls <= self.fail_times:
            raise ConnectionError("tcgcsv is down")
        return list(SETS.values()) + [{"groupId": 99, "name": "Other", "abbreviation": "OT", "publishedOn": "2020-01-01T00:00:00"}]

    def products(self, group_id):
        return PRODUCTS[group_id]

    def prices_archive(self, day, group_ids):
        return {g: PRICES[day].get(g, []) for g in group_ids}

    def prices_today(self, group_id):
        return PRICES["2026-09-01"].get(group_id, [])


@pytest.fixture
def settings(tmp_path):
    return Settings(db_path=tmp_path / "tcg.duckdb", out_dir=tmp_path / "out", sets=(1, 2),
                    price_dates=("2026-08-01", "2026-09-01"), frozen_month="2026-08", retries=1, retry_delay=0)

16. Reference numbers

MeasureValue
first run12 tasks ok in about 40 s; 7 sets, 1,490 products, 5,951 prices in 5 captures
gold layerfact 5,951 rows = 5,951 keys of the grain; 0 prices without set; 5 dates; 524 cells in the cube
frozen reportreport.mv_card_price_2026_09 with 1,226 rows; Pikachu ex 276/217 at US$ 1,049.08
second runcatalogue twice in the landing table (14 and 2,980 records), fact still 5,951 rows, frozen report kept
with --with-today on 08/11/20267,782 prices in 6 captures, the same after a second run on the same day; 697 cells
tests9 passed in about 2 s, without network

17. Recurring mistakes of agents

The traps below were found while the package was rehearsed on 07/11/2026, and the prompts already carry the corresponding adjustments.

DuckDB 2.0 and open results

In DuckDB 2.0 the result of execute() stays open until it is read, and the next statement on the same connection fails with a ResourceInUse error. In the rehearsal, a COPY that wrote a Parquet file left its result open and made the last task fail four times, with the retries of the pipeline; the package reads every result through a small function run(con, sql). The same version also refuses to create a table on a connection opened as read-only, which is why counts does not try to create the landing table.

Reruns

An agent that loads the prices of today with the moment of the run as timestamp creates a second price per product on each run of the day, and an agent that reads every record of the catalogue in the dimensions doubles the fact on the second run. Both errors pass a first run and appear only on the second, which is why a test runs the pipeline twice.

Layers and tests

Agents tend to call the network inside the tests, which makes them slow and fragile, and to import the report from the extraction to print a summary, which inverts the direction of the layers. The prompts ask for a fake client and for each layer to declare what it may import.

18. The second hour

The second hour is the graded DataApp Packaging activity. Each student packages the DataApp of the group with the architecture of this session: three layers in one direction, an installable package with a command, an idempotent load of the partner data, the gold layer that the group built in Lesson 6 and tests that run without the network. The four prompts of the session, adapted to the partner data, and the reference package serve as models of structure. The statement is the DataApp Packaging activity on Adalove: the work is individual, on a branch of the project repository named graded-activity-package/student-name, and is documented in a pull request whose link is the only thing submitted, by Friday, 27/11/2026, the day of the session. The criteria are those listed in the activity on Adalove.

19. Glossary

TermMeaning in this lesson
packagecode with a declared name, version, dependencies and entry points, installable with pip
src layoutthe code in src/<package>/, so that tests import the installed package
entry pointa command created on install, such as tcg-dataapp
layered architecturea division by responsibility in which each layer depends only on the layer below
batchthe records of one tag captured at one timestamp, the unit of load
idempotentgiving the same result however many times it runs
slowly changing dimension, type 1a dimension that keeps only the current version of each member
quality gatea check that stops the pipeline when the model is wrong
DAGa directed acyclic graph of tasks and their dependencies
run logops.pipeline_runs: one row per attempt of a task

20. Checklist

  • The package installs with pip install -e '.[dev]' and has a command.
  • Each layer imports only from the layers below it.
  • The settings come from environment variables with defaults.
  • Every load replaces its batch, and a rerun does not duplicate rows.
  • The dimensions keep the last version of each member.
  • A quality gate stops the run when the grain breaks.
  • A frozen report is created once, from the last capture of its month.
  • Every attempt of every task is logged, with Unix times.
  • The tests run without the network.

21. References and self-study