Module 8 · Information Systems · Lesson 4 · Week 3

ETL: Object Storage to Data Warehouse

Reference material for the session in which a coding agent builds, in four rounds, the pipeline that takes the Bronze layer of the pharmacy chain from a local MinIO to the Silver layer of a DuckDB warehouse. It explains ETL and ELT, how a query engine reads Object Storage, the transformation techniques and the quarantine, the warehouse and the load strategies, and it brings the measurements of reference, the four prompts in full and the lab script.

About this session

ETL: Object Storage to Data Warehouse · 29/10/2026 · Prof. Afonso

Learning objective

By the end of the session, students should be able to build with a coding agent an ETL pipeline that extracts JSON, Parquet and CSV files from a local MinIO, cleans, formats, converts and enriches them with every rejected row in quarantine, and loads the Silver layer of a DuckDB warehouse in full and incremental modes, justifying each choice with measurements.

Session strategy

Practice and theory interleaved. The groups send four prompts to a coding agent (specification, extraction, transformation and load), and while the agent writes each step the professor explains its mechanism with animations and measured examples. Each round ends with a review against the expected counts, and the session closes with the verification of accounting, idempotency and privacy.

Session structure

  1. Daily — 15 min
  2. Running case, target architecture and local MinIO with the Bronze layer — 10 min
  3. Round 1: prompt for spec, plan and tasks; ETL and ELT and the Bronze to Silver contract — 15 min
  4. Round 2: prompt for the extraction; Object Storage, file formats and partitions — 17 min
  5. Round 3: prompt for the transformation; cleaning, formatting, type conversion, enrichment and quarantine — 18 min
  6. Round 4: prompt for the load; Data Warehouse and Data Lake, full and incremental loads — 20 min
  7. Verification: accounting, idempotency, privacy and lineage — 12 min
  8. Quality attribute scenarios, closing and self-study — 13 min
Part IFoundations

1. How to read this material

This material accompanies Lesson 4, in which practice and theory are interleaved. Each round of the session starts with a prompt to a coding agent, and while the agent writes the files the slides explain the mechanism that those files implement. The same order is kept here, so that a group that missed part of the session can rebuild it alone.

Parts I to IV correspond to the four explanation blocks of the session. Part I places the pipeline between the layers of the medallion architecture defined in Lesson 3 and compares ETL and ELT. Part II explains how a query engine reads files from Object Storage and why the format and the layout of the keys decide the cost of the extraction. Part III covers the four transformation techniques named in the description of the session and the quarantine, and Part IV covers the warehouse, the load strategies and the design of the Silver tables. Part V is the lab, with the setup, the four prompts in full, the verification and the mistakes that coding agents usually make in this kind of pipeline.

Every number in this material was measured on 26/10/2026 on the professor's machine, with DuckDB 2.0.0 and a local MinIO, using the generator of the lab. The numbers are therefore reproducible, but they describe one machine and a local object store. On Amazon S3 each request adds tens of milliseconds of latency and a price, so the differences in requests and bytes shown here become larger differences in time and cost.

2. The case and the target architecture

The pharmacy chain of the module has six stores (CMP-01 Campinas, STS-02 Santos, SOR-03 Sorocaba, JUN-04 Jundiaí, BAU-05 Bauru and FRA-06 Franca) and forty products, part of them continuous-use medicines. Lesson 3 defined the contracts of the Bronze, Silver and Gold layers for the weekly stock-out indicator of the purchasing team. This lesson builds the step between Bronze and Silver, which turns what the sources sent into conformed entities with a declared grain.

Three sources deliver files to Bronze every day, each with a different format and different defects. The POS terminals send the sale lines of the day as newline-delimited JSON. The ERP sends a Parquet extract with the stock position of each store and product. The supplier ACME Distribuição Farmacêutica sends a CSV of deliveries separated by semicolons, encoded in Latin-1, with Portuguese headers, decimal commas and dates in the dd/mm/yyyy format. The store and product master files are CSV files of the ERP.

Bronze layout in the bucket pharmacy-lake
bronze/source=pos/entity=sale_line/ingestion_date=YYYY-MM-DD/batch_2300.json
bronze/source=pos/entity=sale_line/ingestion_date=2026-10-18/batch_0815_resend.json
bronze/source=erp/entity=stock_position/ingestion_date=YYYY-MM-DD/extract.parquet
bronze/source=supplier/entity=delivery/ingestion_date=YYYY-MM-DD/acme_0930.csv
bronze/source=erp/entity=store/ingestion_date=2026-10-12/store.csv
bronze/source=erp/entity=product/ingestion_date=2026-10-12/product.csv

The generator of the lab, generate_bronze.py, writes fourteen days of this layout, from 12/10 to 25/10/2026, and plants defects with a fixed seed. Store BAU-05 sends sold_at as dd/mm/yyyy HH:MM:SS in local time, while the other stores send ISO 8601 with the offset -03:00. Store SOR-03 sends unit_price as text with a decimal comma. About one line in ten has a store code in lower case, in title case or surrounded by spaces. One per cent of the lines of each batch is posted twice. On 17/10 the terminal of JUN-04 lost its connection after sending part of the day and resent the whole day in a second file the next morning. In the ERP, audits correct the stock count of two days earlier, and the correction arrives in a later extract, while JUN-04 often closes the day without a count.

The target is a DuckDB database file, warehouse/pharmacy.duckdb, used as a test Data Warehouse. Its schema silver holds the tables store, product, sale_line, stock_position and delivery, plus quarantine, which keeps the rejected rows with their reason, and load_log, which records every run. DuckDB plays two roles in the pipeline: it is the engine that reads the bucket and transforms the rows, and it is the warehouse that stores the result. In a production platform the second role would belong to a warehouse such as ClickHouse or Redshift, discussed in section 11, while the code of the extraction and of the transformation would stay the same.

SourcesPOS JSON, ERP Parquet, supplier CSV
BronzeMinIO, read-only, partitioned by ingestion date
Extract and transformDuckDB with httpfs, SQL rules, quarantine
SilverDuckDB warehouse, MERGE by key, load log
GoldLessons 5 and 6: modelling and cubes

3. ETL and ELT

Every data pipeline extracts data from a source, transforms it and loads it into a target. ETL and ELT name the two orders in which the last two steps can happen. In ETL, the transformation runs in an engine outside the warehouse, and the warehouse receives only conformed data. In ELT, the raw data is loaded into the warehouse first and transformed there, usually in SQL, by the computation of the warehouse itself. The difference seems a matter of order, but the place where the transformation runs determines who pays for the computation, what the warehouse stores and how a wrong rule is corrected.

ETL was the dominant pattern while warehouses were expensive appliances whose capacity was sized in advance, and it remains the right choice when the warehouse charges by byte stored or scanned, when sensitive fields must be removed before the data lands, or when the logic needs code that SQL does not express well. ELT became common with cloud warehouses that separate storage from computation and scale both on demand, such as BigQuery, Snowflake and Redshift, and with tools such as dbt, which let analysts own the transformation as versioned SQL. Its main advantage is that the raw tables stay in the warehouse, so a rule can be corrected and rerun without a new extraction.

AspectETL · transform, then loadELT · load, then transform
Computationan engine outside the warehouse (Python, Spark, Dask, DuckDB)the warehouse itself, in SQL
What the warehouse storesonly conformed dataraw and conformed data, including the sensitive fields of the raw
Correcting a rulererun the engine from the raw copy, which must still exist somewherererun the SQL over the raw tables
Fits whenthe warehouse is expensive, data must be masked before landing, or the logic needs general codethe warehouse scales cheaply, analysts own the SQL, and the raw data may be kept under the same governance
Main riskthe engine becomes a second platform to operatethe warehouse fills with raw tables that nobody conforms

The medallion architecture combines the two. The raw data is kept, as ELT requires, but in Bronze, in Object Storage, outside the warehouse. The pipeline then transforms with an engine before writing Silver, which is ETL from the point of view of the warehouse. This explains why Lesson 3 described the medallion as a form of ELT: from the point of view of the lake, the data is loaded first and transformed later. Both descriptions are correct, and what matters for the design is which system holds the raw data and under which access rules.

A measured comparison

The cost of each order was measured with the generator at 73,500 sales per day, which produced 1,120,749 POS lines in fifteen days. The ETL path of this lesson extracted, transformed and loaded them in about 6 seconds and wrote 1,096,943 conformed sale lines, none with a CPF. The ELT path loaded the same files into a raw schema of text columns in 2.9 seconds and 33 MiB. The ELT landing is faster because it does nothing to the data, and the time of the transformation simply moves to the next step. What does not move is the consequence for governance: from the first second, the warehouse held the CPF of the customer in all 1,120,749 rows, and the treatment that Silver promised under the LGPD now depends on the access rules of a second system.

Decision for the group

The partner data of the project may contain personal data. Before choosing an order for the pipeline of the project, the group must know which fields are personal, who may read the raw data and where it is allowed to be stored. The data viewpoint of Lesson 3 is the place to record that decision.

4. The Bronze to Silver contract

A layer of the medallion architecture is defined by the guarantee it gives to the next layer, and not by the place where its files are kept. Bronze guarantees only that what arrived was kept, exactly as it arrived, with the moment of ingestion. Silver guarantees that each entity has one row per declared grain, that each column has a declared type, that rows breaking a rule are kept apart with a reason, that sensitive fields have been removed and that each row can be traced to the file that produced it. The transformation of this lesson is the code that fulfils these guarantees.

PropertyBronze · rawSilver · workingGold · curated
Contenteach delivery as it arrived, resends includedone row per declared grainfacts and dimensions of an indicator
Typestext, except what the format carriesdeclared types, enforcedbusiness types and units
Invalid rowskeptin quarantine, with a reasonabsent
Sensitive fieldspresent, access restrictedremoved or pseudonymisedabsent
Lineagekey of the object and partitionsource_file, ingestion_date, run_id, loaded_atreference to the Silver rows
Can be rebuilt fromthe sources onlyBronzeSilver

The last row of the table is the reason why Bronze is read-only. Silver can be rebuilt from Bronze whenever a rule changes, and that is possible only while Bronze still holds what the sources sent. A pipeline that cleaned Bronze in place, or deleted the night batch of JUN-04 after the resend, would make any error of the transformation permanent.

The grain of each Silver table follows from the sources. A sale line is identified by sale_id. A stock position is identified by the store, the product and the date of the count, so that an audit correction of the same key replaces the older count instead of adding a row. A delivery is identified by id_entrega. The Silver of this lesson is conformed and stays close to the shape of the sources. Lesson 5 will model it in Third Normal Form or Data Vault, and Lesson 6 will build the cubes of Gold on top of it, so a star schema here would anticipate decisions that belong to those lessons.

The accounting of rows

A consequence of the contract is that every row read from Bronze must have a destination. After the removal of copies, each row is either in a Silver table or in the quarantine, and the pipeline must be able to prove it with counts. For the fourteen days of the lab, the 21,353 POS lines read become 21,000 unique sales, of which 20,891 go to Silver and 109 to the quarantine. A pipeline that loads 20,891 sale lines but cannot say where the other 462 rows went has lost data, even if every query over Silver returns plausible results.

Part IIExtraction

5. Object Storage

Object Storage is the storage of the Data Lake. Amazon S3 defined the interface that most services and products now follow, including MinIO, which the lab runs locally in a container. Data is kept as objects inside buckets, each object identified by a key and accessed through HTTP requests: PUT writes an object, GET reads it, HEAD returns its metadata and a GET on the bucket with the parameter list-type=2 lists the keys that start with a prefix.

Three properties of this kind of storage shape the way a pipeline reads it. The first is that the namespace is flat. The key bronze/source=pos/entity=sale_line/ingestion_date=2026-10-17/batch_2300.json is one string, and the slashes only look like folders. The segments in the form name=value follow the convention of Hive, which query engines read as partition columns, so the layout of the keys works as the index of the lake. The second property is that objects are written whole and never edited. An object can be replaced, but not changed in the middle, while a read can ask for a byte range with the Range header. This is what allows an engine to read the footer and a few columns of a Parquet file without downloading the rest. The third property is that requests are billed and slow compared with a local disk. On S3 each LIST, HEAD and GET has a price and a latency of tens of milliseconds, so thousands of small files cost more to list and open than a few large files with the same bytes.

These properties explain why Object Storage became the foundation of the lake. Storage is separated from computation, so DuckDB on a laptop, Spark on a cluster and Redshift Spectrum read the same objects without copying them. Capacity grows without a schema, which is what allows Bronze to keep every delivery as it arrived. Durability is a property of the service, and the price per gigabyte is lower than that of the disks of a database, which makes it cheap to keep the whole history.

Reading the bucket from DuckDB

DuckDB reads Object Storage through the extension httpfs. The credentials are declared once in a secret, and every function that reads files accepts s3:// paths and glob patterns. With MinIO, the secret needs the endpoint, path-style URLs and SSL disabled, because the local service answers on localhost:9000 without a certificate.

Python · connection to the MinIO
import os, duckdb
from dotenv import load_dotenv

load_dotenv()
con = duckdb.connect(os.environ["WAREHOUSE_PATH"])
con.execute("INSTALL httpfs; LOAD httpfs;")
con.execute("""
  CREATE OR REPLACE SECRET lake (
    TYPE s3, KEY_ID ?, SECRET ?, REGION ?,
    ENDPOINT ?, URL_STYLE 'path', USE_SSL ?)""",
  [os.environ["S3_ACCESS_KEY"], os.environ["S3_SECRET_KEY"], os.environ["S3_REGION"],
   os.environ["S3_ENDPOINT"], os.environ["S3_USE_SSL"].lower() == "true"])
print(con.sql("SELECT count(*) FROM glob('s3://pharmacy-lake/bronze/**')"))
Secrets

The credentials come from .env, which is in .gitignore and never committed. If the secret is written with an f-string, the password ends up in the logs of the agent and in any traceback, which is why the example passes it as a parameter. Check with git check-ignore .env before the first commit.

6. File formats and how they are read

Each format of the case tells the engine a different amount about itself, and the options of the reader exist to supply what the file does not say. A CSV file is text organised by rows, and it carries no types, no encoding and no schema beyond the header line. The reader must therefore be told the separator, whether there is a header, the encoding and, if types are to be inferred, the formats of decimals and dates. A newline-delimited JSON file carries field names and a few types, such as number and string, but each line may differ from the others, so the reader infers a schema from a sample. A Parquet file carries its schema, the type of each column, the division of the rows into row groups, the position of each column chunk inside the file and the minimum and maximum values of each chunk, all in a footer at the end of the file.

FormatWhat the file carriesWhat the reader must be toldReader in the case
CSVrows of text and a headerseparator, header, encoding; text columns to avoid wrong inferenceread_csv(files, delim=';', header=true, encoding='latin-1', all_varchar=true)
JSON Linesone object per line, field names, a few typesthat it is newline-delimited, and the columns, because inference fails when one terminal sends a price as textread_json(files, format='newline_delimited', columns={...})
Parquetschema, types, row groups, column chunks, statistics, compressiononly the files and the partitioningread_parquet(files, hive_partitioning=true)

The extraction reads CSV and JSON as text, with every column declared as VARCHAR, and leaves every conversion to the transformation. The reason is practical. If the reader inferred the type of unit_price as a decimal from the first lines, the first price of SOR-03 written as "12,90" would abort the run. Read as text, the same value reaches the transformation, where a failed conversion becomes a quarantine reason. Two more options of the reader belong to every extraction. The option filename='source_file' adds the key of the object to each row, the first link of the lineage of Silver, and hive_partitioning=true turns ingestion_date=2026-10-17 in the key into a column of the row.

The same query in three formats

To measure what each format costs, the typed POS lines of fourteen days at 73,500 sales per day, 1,046,514 rows ordered by sale_id, were written to the bucket as CSV, JSON Lines and Parquet. DuckDB ran two queries over each file with its HTTP caches disabled, and the HTTP log of DuckDB gave the requests and the bytes received.

FormatSizecount(*): read, GETs, timesum(quantity) of CMP-01: read, GETs, time
CSV90 MiB118.37 MiB · 62 · 0.225 s120.22 MiB · 63 · 0.219 s
JSON Lines200 MiB232.44 MiB · 117 · 0.384 s232.44 MiB · 117 · 0.359 s
Parquet25 MiB0.03 MiB · 1 · 0.006 s0.12 MiB · 7 · 0.011 s

The count over Parquet reads only the footer, which already stores the number of rows of each row group. The sum of one store reads the footer, uses the minimum and maximum of store_code in each row group to skip the groups that cannot contain CMP-01, and downloads only the chunks of the two columns the query needs, store_code and quantity, in the groups that remain. The skipping works well here because the rows are ordered by sale_id, which begins with the store code, so the lines of each store are concentrated in a few row groups. CSV and JSON have neither a footer nor statistics, so both queries download the whole file, and slightly more than its size because the reader fetches overlapping blocks to find the line boundaries. On a laptop with a local MinIO the difference is a fraction of a second. On S3, with a latency and a price for each request and a price for each byte scanned in services such as Athena, the same ratio is the cost of the pipeline.

Why Bronze is not all Parquet

Bronze keeps what the source sent, in the format in which it was sent, because converting it at the entrance would already be a transformation that could fail or lose information. The ERP already exports Parquet, while the POS terminals and the supplier do not. A common design is to keep the original files in Bronze and write the conformed Silver in a columnar format, which in this lesson is the storage of the DuckDB warehouse itself.

7. Partitions and incremental extraction

A partition is a subset of the files of an entity that shares the value of a column written in the key, here the ingestion date. The full load reads every partition, and the incremental load must read only the partitions that arrived after the last run. There are three ways of asking DuckDB for one new day, and they do not cost the same.

How the extraction asks for the day 26/10LISTHEADGETReadTime
glob of all days, no filter (full load, 15 days)1164814.15 MiB0.228 s
glob of all days with WHERE ingestion_date = '2026-10-26'116185.35 MiB0.16 s
explicit list of the files of the new partition1120.63 MiB0.044 s
Parquet of the ERP, glob with the same WHERE1020.01 MiB< 0.01 s

With Parquet, the filter on the partition column is applied to the list of files before any of them is opened, a technique called partition pruning, and only the file of the new day is read. With JSON, in DuckDB 2.0.0, the same filter still opened the sixteen files of the glob and read part of seventeen of them before discarding their rows, so it read eight times more than necessary. The behaviour depends on the engine, on its version and on the reader of each format, and a pipeline that relies on it can become slow after an upgrade without any change in its code. The rule written in the AGENTS.md of the lab follows from this measurement: the incremental extraction computes the list of new files from the keys and reads only that list, which costs the same in any engine and any format.

Python · list the files of the new partitions
import re

BRONZE = "s3://pharmacy-lake/bronze"

def list_partitions(con, entity_path, after=None):
    """Keys of the files of entity_path whose ingestion_date is greater than after."""
    keys = [r[0] for r in con.execute(
        "SELECT file FROM glob(?) ORDER BY file", [f"{BRONZE}/{entity_path}/*/*"]).fetchall()]
    def day(key):
        return re.search(r"ingestion_date=(\d{4}-\d{2}-\d{2})", key).group(1)
    return [k for k in keys if after is None or day(k) > str(after)]

files = list_partitions(con, "source=pos/entity=sale_line", after="2026-10-25")
# ['s3://pharmacy-lake/bronze/source=pos/entity=sale_line/ingestion_date=2026-10-26/batch_2300.json']

The watermark and late files

The value after is the watermark, the highest ingestion date already loaded, which the pipeline reads from its load log. A watermark by partition assumes that a file is always written in the partition of the day on which it arrived. If a source writes a late file in the partition of an earlier day, the incremental load will not see it, because that partition is already behind the watermark. Two answers are common. The first is to keep, in the load log, the list of files already read and to compare it with the listing, which detects any new key regardless of its partition. The second is to make the ingestion layer always write in the partition of the arrival date, which is what the convention ingestion_date of Lesson 3 assumes. The lab uses the second, and the pause of block 2 asks the group to think about the first.

Many small files

The number of files matters as much as their size. Each file of the glob costs at least one HEAD and one GET, and listings return at most one thousand keys per page. A supplier that writes one CSV per delivery, around three hundred files of four hundred bytes each day, would produce more than one hundred thousand objects in a year, and a full load would spend more time in requests than in reading data. The usual remedy is compaction: a job concatenates the small files of each partition into one larger file. Compaction can be done outside Bronze, in a staging area, so that Bronze still keeps what the source sent.

8. Large volumes

The description of the session on Adalove mentions Spark and Dask as tools for extraction at scale. Each answers the same question, what to do when the data does not fit in the memory or the time budget of one process, in a different way, and the choice depends on the volume, on the existing code of the team and on who will operate the platform.

DuckDB

An embedded analytical database that executes queries in vectors of rows, in parallel threads, and spills intermediate results to disk when an operator exceeds the memory limit. It processes the 1.1 million lines of the benchmark in seconds and fits most Silver loads up to hundreds of gigabytes on one machine.

Apache Spark

A distributed engine that divides the files into partitions processed by executors on several machines. Its original abstraction, the RDD of the self-study, is an immutable collection divided in partitions, built by lazy transformations and recomputed from its lineage after a failure. Spark SQL and DataFrames are built on it.

Dask

A Python library that divides a dataframe into many pandas dataframes and schedules the operations on threads, processes or a cluster. It fits teams whose code is already written in pandas and who want to scale it without learning a new API.

Scale changes the number of machines, the size of the partitions and the cost of moving data between machines, called shuffle, which happens in every deduplication and every join by key. It does not change the contract of Silver, the rules of the transformation, the accounting of rows or the idempotency of the load. For this reason the specification of the first round of the lab is written without naming the engine, and the same requirements would be valid if the extraction were rewritten in Spark.

Pandas is not on this list for a reason worth stating. A loop in pandas over the rows of a dataframe, or a dataframe loaded entirely in memory from all the files of the lake, works with the fourteen days of the lab and fails with the history of the partner. The prompts of the lab ask for rules written in SQL over the whole table precisely so that the code of the group grows with the data.

Part IIITransformation

9. Transformation techniques

The description of the session names four techniques: cleaning, formatting, type conversion and enrichment. In the case, each technique answers a defect that the generator planted, and each defect has a count that a test can check. Writing the rules in this way, tied to a defect and to a number, is what turns a transformation into something that can be verified.

Cleaning

Cleaning removes duplicates, separates invalid values and decides what to do with missing values. Duplicates are removed by the key of the grain, with an explicit rule for which copy wins. For sale lines, the copy with the latest ingestion_date and, within it, the latest source file wins, which keeps one row for each of the 209 lines posted twice and keeps the resend of JUN-04 instead of the incomplete night batch. For stock positions, the latest extract of each key wins, which lets the 60 audit corrections replace the older counts. Invalid values, such as a product that does not exist, a quantity of zero or a negative stock, go to the quarantine. A missing value is handled according to what it means. The 130 stock positions of JUN-04 without on_hand mean that the store did not count, and imputing zero would create 130 stock-outs that did not happen, so they are kept as NULL and counted by a check.

Formatting

Formatting gives each concept one representation. Store codes are written in upper case without spaces, timestamps are converted to one type in local time, and prices use a decimal point. Formatting comes before any comparison and any join, because the key and the rules compare formatted values. A lookup of the store that ran before upper(trim(store_code)) would fail for 2,070 valid lines and send them to the quarantine as unknown stores.

Type conversion

Type conversion turns the text of the extraction into the declared types of Silver. In DuckDB, try_cast and try_strptime return NULL when the conversion fails, while CAST and strptime raise an error that aborts the query. The first pair turns a bad value into a reason for the quarantine, and the second turns it into a failed run in the middle of the night. The two date formats of the case are combined with coalesce: the ISO timestamp with its offset is read as a TIMESTAMPTZ and converted to the local time of America/Sao_Paulo, and the format of BAU-05 is read as a local timestamp, so that both arrive as the same type and the same clock.

Enrichment

Enrichment adds to each row what every consumer would otherwise compute. The store_id is found from the formatted store code in the master table, line_amount is the quantity times the unit price, sold_date is the date of the sale, and is_stockout marks the stock positions equal to zero. The lineage columns are also an enrichment: source_file and ingestion_date come from the extraction, and run_id and loaded_at come from the load. The field customer_cpf is removed in this step and never selected again.

DuckDB SQL · sale lines from staging to the conformed table
CREATE OR REPLACE TEMP TABLE t_sale AS
WITH typed AS (
  SELECT r.sale_id, s.store_id, r.terminal_id,
         try_cast(r.product_id AS INTEGER)                          AS product_id,
         try_cast(r.quantity AS INTEGER)                            AS quantity,
         try_cast(replace(r.unit_price, ',', '.') AS DECIMAL(10,2)) AS unit_price,
         coalesce(
           try_strptime(r.sold_at, '%Y-%m-%dT%H:%M:%S%z')::TIMESTAMPTZ AT TIME ZONE 'America/Sao_Paulo',
           try_strptime(r.sold_at, '%d/%m/%Y %H:%M:%S'))            AS sold_at,
         r.source_file, r.ingestion_date::DATE                      AS ingestion_date,
         row_number() OVER (PARTITION BY r.sale_id
                            ORDER BY r.ingestion_date DESC, r.source_file DESC) AS rn
  FROM raw_sale r
  LEFT JOIN silver.store s ON s.store_code = upper(trim(r.store_code))
)
SELECT * EXCLUDE (rn),
       quantity * unit_price AS line_amount,
       CAST(sold_at AS DATE) AS sold_date,
       CASE
         WHEN store_id IS NULL THEN 'unknown_store'
         WHEN product_id IS NULL
              OR product_id NOT IN (SELECT product_id FROM silver.product) THEN 'orphan_product'
         WHEN quantity IS NULL OR quantity <= 0 THEN 'invalid_quantity'
         WHEN unit_price IS NULL THEN 'invalid_price'
         WHEN sold_at IS NULL THEN 'invalid_timestamp'
       END AS reason
FROM typed
WHERE rn = 1;   -- customer_cpf is never selected

The query runs over the whole staging table, with no loop in Python. On the 1.1 million lines of the benchmark, the transformation of the three entities took about one second. The order of the rules in the CASE is a decision that must be documented, because a row that breaks two rules receives only the first reason, and a change of order changes the counts by reason without changing the total.

10. Quarantine and the accounting of rows

The quarantine is the table that receives the rows that break a rule of Silver, with the reason, the source file, the ingestion date and the run that rejected them. It exists so that a rejected row remains visible and countable instead of disappearing, and so that the team can decide later whether to correct the source, change the rule or accept the loss. Because each conformed table carries a column reason, the split between Silver and quarantine is a filter: rows with reason IS NULL are loaded, and the others are copied to the quarantine with their entity, a key that identifies the record and a JSON copy of the conformed row.

The quarantine also obeys the rules of privacy. A quarantined sale line keeps the columns of the conformed table, and the conformed table no longer has customer_cpf, so the CPF does not reach the quarantine either. A design that stored the raw row from staging in the quarantine would bring the CPF into the warehouse through the back door.

EntityRead from BronzeAfter deduplicationSilverQuarantineReasons
sale_line21,35321,00020,89110968 orphan_product, 41 invalid_quantity
stock_position3,4203,3603,3461414 negative_on_hand
delivery2712712581313 missing_quantity

The table above is the result of the reference pipeline for the fourteen days of the lab, and it is the result that the tests of the group should reproduce. Of the 353 POS copies removed, 209 are lines posted twice and 144 are lines of JUN-04 sent on the night of 17/10 and then resent the next morning. The 241 lines of JUN-04 for that day are in Silver once each, all with ingestion_date = 2026-10-18. The 3,580 prices of SOR-03 and the 3,447 timestamps of BAU-05 were converted, and none of them reached the quarantine.

Late master data

A quarantine reason may depend on the moment of the check. The 68 lines with products 41 and 42 are orphans because those products are not in the master file. If the ERP adds the two products next week, the sales become valid, and the quarantine records a decision that is no longer true. The pipeline must then choose between three behaviours: leaving the quarantine as a record of the past, reprocessing the affected days with a full load, or retrying the quarantined rows at each run. The third is convenient and dangerous, because a row that is retried forever hides a source that never corrects itself. Whatever the choice, it belongs in the specification, with the requirement that states it.

Part IVLoad

11. Data Warehouse and Data Lake

The pipeline reads from a lake and writes to a warehouse, and the two systems are complementary. A Data Lake keeps files in Object Storage, with the schema decided by whoever reads them, which is called schema on read. It accepts any format, grows cheaply and keeps the history. A Data Warehouse keeps tables with declared types and constraints, with the schema checked when the data is written, which is called schema on write. It supports transactions, updates by key and many concurrent queries from analysts and BI tools. The lakehouse, discussed in Lesson 3, brings transactions and tables to the files of the lake through table formats such as Delta Lake and Apache Iceberg, which the module does not use but which follow the same contracts.

AspectData Lake (MinIO, S3)Data Warehouse (DuckDB here; ClickHouse, Redshift)
Schemaon read: the reader decides the typeson write: the load rejects what does not fit
Unit of storagefiles and objectstables, columns, constraints
Updatesreplace whole objectsINSERT, UPDATE, MERGE in transactions
Who readspipelines, data scientists, enginesanalysts, BI tools and applications, through SQL
Cost driverbytes stored and requestscomputation of queries and loads

ClickHouse

ClickHouse is an open-source columnar database designed for analytical queries over large tables. Its main family of table engines, MergeTree, writes each insert as an immutable part sorted by the ORDER BY key of the table and merges the parts in the background. The key orders the data and builds a sparse index over it, but it does not enforce uniqueness: two rows with the same key can coexist until a merge, and even after it. Deduplication is therefore done in the ETL, or delegated to the engine ReplacingMergeTree, which keeps the latest version of each key when it merges parts, without guaranteeing when that happens. ClickHouse reads S3 directly with the table function s3(), which allows an ELT variant of this pipeline. A load into ClickHouse usually inserts in large batches, because each insert creates a part and many small inserts overload the merges.

Amazon Redshift

Redshift is a managed columnar warehouse of AWS that distributes the rows of each table among the slices of a cluster by a distribution key and orders them on disk by sort keys. Loads from S3 use the command COPY, which reads many files in parallel and is much faster than inserts row by row. Primary keys and foreign keys can be declared but are informational: the planner uses them, and the database does not enforce them. Redshift supports MERGE, which performs the upsert of an incremental load from a staging table. Redshift Spectrum queries the files of S3 as external tables without loading them.

What the two have in common

Neither ClickHouse nor Redshift enforces the uniqueness of the grain. In both, the pipeline owns the deduplication and must check it after each load, which is exactly what the reference pipeline does with its integrity queries in section 13. DuckDB enforces primary keys, which makes it a strict test warehouse, and section 12 shows the cost of that enforcement.

12. Full and incremental loads

A full load rebuilds Silver from all the partitions of Bronze. An incremental load reads only the partitions after the watermark and merges their rows into the existing tables. The two must arrive at the same Silver, and comparing them is the most effective test of the pipeline: when the counts of a full load differ from those of the incremental loads that preceded it, one of the two modes has a bug.

StrategyWhat it doesFits whenRisk
Full rebuildcreates the tables again from all of Bronzefirst load, small volumes, a rule that changedcost grows with the history; readers must never see an empty table
Appendinserts the new rowsimmutable events that never arrive twicea resend duplicates rows: the 241 lines of JUN-04 would appear twice
Incremental merge (upsert)MERGE by key on the new partitionssources that resend and correct, as in the casedepends on a correct key and on a watermark that sees late files
Partition overwritereplaces the Silver rows of each reprocessed daydata partitioned by the same date it arrivescorrections of other days, such as the audits of day minus two, are lost

Three properties make a load safe to operate. Idempotency means that running the same input twice produces the same Silver, which allows a failed job to be restarted without thinking. MERGE by the key of the grain provides it, and append does not. Atomicity means that the run either changes all the tables or none of them, which in DuckDB comes from executing the whole load in one transaction. Traceability means that each run leaves a record of what it read, what it loaded and what it rejected, which in the lab is the table load_log, with run_id, entity, mode, the dates covered, the counts and the start and end times.

DuckDB SQL · incremental merge of the stock positions
BEGIN TRANSACTION;

MERGE INTO silver.stock_position AS t
USING (SELECT * EXCLUDE (reason) FROM t_stock WHERE reason IS NULL) AS s
   ON t.store_id = s.store_id AND t.product_id = s.product_id AND t.date = s.date
WHEN MATCHED THEN UPDATE SET
     on_hand = s.on_hand, is_stockout = s.is_stockout,
     source_file = s.source_file, ingestion_date = s.ingestion_date,
     run_id = s.run_id, loaded_at = s.loaded_at      -- audit correction
WHEN NOT MATCHED THEN INSERT BY NAME;                -- new day

DELETE FROM silver.quarantine
 WHERE entity = 'stock_position' AND ingestion_date IN (SELECT DISTINCT ingestion_date FROM t_stock);
INSERT INTO silver.quarantine
SELECT 'stock_position', concat_ws('|', store_id, product_id, date), reason,
       source_file, ingestion_date, run_id, record
  FROM t_stock WHERE reason IS NOT NULL;      -- record: the conformed row as JSON, without CPF

INSERT INTO silver.load_log VALUES (?, 'stock_position', 'incremental', ?, ?, ?, ?, ?, ?, now());
COMMIT;

What each mode cost

The reference pipeline was run over the benchmark bucket, with 73,500 sales per day, to measure the cost of each mode on the same machine.

RunPOS rows readExtractTransformLoad
Full, 14 days, empty warehouse1,046,5141.11 s1.02 s3.23 s
Incremental, day 26/1074,2350.19 s0.16 s0.32 s
Full, 15 days, drop and rebuild1,120,7491.2 s1.0 s3.4 s
Full, 15 days, DELETE then MERGE into the existing tables1,120,7491.2 s1.0 s32.37 s

The incremental run costs the size of one day, and the full run the size of the history, which is the expected behaviour and the reason why the incremental mode exists. The last line is less obvious. Deleting every row and merging them again took ten times longer than dropping the tables and rebuilding them, because every deletion and every merge into a table with a primary key updates the index of that key. The same index explains why silver.sale_line occupied 142 MiB with its primary key and 23 MiB without it, and why the copy without the key took 0.32 seconds. Columnar warehouses such as ClickHouse and Redshift do not enforce keys for this reason, and leave uniqueness to the ETL. The prompt of the fourth round therefore asks for the full mode as a rebuild, and the ADR of the group should record whether the primary keys stay in the test warehouse, with the measurements of the group.

Reprocessing

A watermark protects the pipeline from reading the same data twice, and for the same reason it prevents the correction of data already loaded. If the rule for BAU-05 had read dd/mm/yyyy as mm/dd/yyyy for ten days, the next incremental run would not touch those days, because they are behind the watermark. The team can run a full load, move the watermark back or add a backfill mode that reprocesses a window without moving the watermark. Because MERGE updates the rows of the keys it finds, an incremental run over the corrected days rewrites sold_at of the existing sale lines, while the load log records the backfill as a run of its own. Whatever the mechanism, the indicators of Gold computed from those days must be recomputed and the consumers told.

13. Designing Silver and checking integrity

The design of the Silver tables in this lesson follows the grain of the sources and avoids redundancy where redundancy would be expensive to keep. sale_line keeps store_id and product_id and leaves the names, cities and categories in store and product, so that a change in the name of a store is one update instead of thousands. At the same time it keeps line_amount and sold_date, a small denormalisation of derived values that every query of Gold would otherwise repeat. Normalisation avoids anomalies when data changes, and denormalisation avoids repeated computation and joins when data is read. Lesson 5 discusses the choice systematically with Third Normal Form and Data Vault, and Lesson 6 denormalises deliberately into the dimensions of a cube.

TableGrain and primary keyMain columns
silver.storestore_idstore_code, city, region
silver.productproduct_idname, continuous_use, list_price
silver.sale_linesale_idstore_id, terminal_id, product_id, quantity, unit_price, line_amount, sold_at, sold_date
silver.stock_position(store_id, product_id, date)on_hand, is_stockout
silver.deliverydelivery_idsupplier, store_id, product_id, quantity, unit_cost, delivered_on
silver.quarantinenone; one row per rejectionentity, record_key, reason, source_file, ingestion_date, run_id, record as JSON
silver.load_logone row per run and entitymode, from_date, to_date, rows_read, rows_loaded, rows_quarantined, started_at, finished_at

Every Silver table also carries the four lineage columns. The supplier file has Portuguese headers, and the conformed table translates them, so that id_entrega becomes delivery_id and data_entrega becomes delivered_on. The translation is a formatting rule and belongs in the plan, because a consumer who reads the CSV and the table side by side needs to know it.

Integrity checks

Integrity is checked after each run with queries that must return no rows. The checks below are the minimum, and in a warehouse that does not enforce keys they are the only protection of the grain.

DuckDB SQL · checks that must return zero rows
-- grain of stock_position
SELECT store_id, product_id, date, count(*) FROM silver.stock_position
GROUP BY ALL HAVING count(*) > 1;

-- referential integrity of sale_line
SELECT l.sale_id FROM silver.sale_line l ANTI JOIN silver.product p USING (product_id);

-- standardised store codes
SELECT store_code FROM silver.store WHERE store_code <> upper(trim(store_code));

-- no personal data anywhere in the warehouse
SELECT table_name, column_name FROM information_schema.columns
 WHERE column_name ILIKE '%cpf%';

-- accounting of the last run
SELECT entity FROM silver.load_log
 WHERE run_id = ? AND rows_loaded + rows_quarantined > rows_read;
-- the exact check, rows after deduplication = loaded + quarantined, is a test of the transformation

Consistency for the reader is the last concern. An analyst who queries the warehouse during a run must never see the sale lines of that run without its stock positions. Loading all the tables in one transaction gives that guarantee in DuckDB. In a warehouse without transactions across tables, the same guarantee comes from loading into staging tables and exchanging them for the live tables in one operation, such as EXCHANGE TABLES in ClickHouse or ALTER TABLE ... APPEND in Redshift.

Part VLab

14. Preparing the environment

The support files are in the folder lab/lesson-4/ of the module, linked at the top of this page: docker-compose.yml with the MinIO, .env.example, requirements.txt, AGENTS.md with the rules for the agent, and generate_bronze.py. The code of the pipeline is not there. It is written during the session, through the prompts of section 15, in the folder lesson_04_etl/ of the group repository, which Lessons 5 and 6 will extend.

Terminal · at the root of the group repository
mkdir -p lesson_04_etl/{specs,src,tests/fixtures,docs/adr,warehouse}
# copy the five support files and .env.example into lesson_04_etl/
cd lesson_04_etl
printf '.env\n.venv/\n__pycache__/\nwarehouse/\n' >> .gitignore
cp .env.example .env
git check-ignore .env            # must print: .env
openssl rand -base64 24          # use it as MINIO_ROOT_PASSWORD and S3_SECRET_KEY in .env

docker compose up -d --wait
docker compose ps                # STATUS must show (healthy)
python3 -m venv .venv && source .venv/bin/activate     # Windows: .venv\Scripts\activate
pip install -r requirements.txt
python generate_bronze.py        # 14 days, 2026-10-12 to 2026-10-25, 45 objects, 4.4 MiB

echo "@AGENTS.md" > CLAUDE.md     # Claude Code imports the rules; other agents read AGENTS.md
claude

The generator prints the number of defects it planted, and that output is the expected result of the pipeline. The group should keep it in the folder, for example in docs/bronze-defects.txt, because the tests and the ADR will refer to it.

Counter printed by the generatorValueMeaning
sale_lines_sent21,112lines in the 14 files batch_2300.json
double_posted209lines posted twice in the same file
resent_lines241lines of JUN-04 resent on 2026-10-18
orphan_product68product_id 41 or 42
invalid_quantity41quantity 0 or -1
br_date_format3,447sold_at as dd/mm/yyyy HH:MM:SS (BAU-05)
comma_decimal3,580unit_price as text with comma (SOR-03)
dirty_store_code2,070store code in lower case, title case or with spaces
stock_rows3,420rows in the 14 files extract.parquet
null_on_hand130JUN-04 without a count
negative_on_hand14invariant violations
audit_correction60corrections of the stock two days earlier
deliveries271rows in the 14 files acme_0930.csv
missing_delivery_qty13empty quantidade

The console of the MinIO is at http://localhost:9001, and in a Codespace it is reached through the forwarded port. Any coding agent can be used. The AGENTS.md is the same for all of them, and the review boxes of each prompt are what keeps the result under the control of the group.

15. The four prompts

The prompts follow the CREATE structure used in the module: character, request, example, adjustments, type of output and extras. Each one is sent alone, the agent shows its plan before editing and stops at the end, and the group answers the questions of the review box before sending the next prompt. The prompts bring facts measured in the Bronze of the lab, so that the requirements and the tests are written against data that exists, and they ask the agent to confirm those facts before using them. When the group adapts the prompts to the partner data, the facts must be measured again.

PromptFilesWhile the agent works, the session explains
1specs/spec.md, specs/plan.md, specs/tasks.mdETL and ELT, the Bronze to Silver contract (sections 3 and 4)
2src/config.py, src/extract.py, tests/test_extract.pyObject Storage, formats, partitions, volume (sections 5 to 8)
3src/transform.py, tests/test_transform.pytechniques and quarantine (sections 9 and 10)
4src/load.py, src/pipeline.py, tests/test_load.py, docs/adr/ADR-001-full-and-incremental-load.mdwarehouse, loads, design (sections 11 to 13)

Prompt 1 · Specification, plan and tasks

Prompt 1 · CREATE
[C] Character
You are a senior data engineer in charge of the specification of an ETL
pipeline. You work in the folder lesson_04_etl/ of the group repository,
which follows Spec-Driven Development. In this step you write documents
only; you do not write code.

[R] Request
Write three files:
1. specs/spec.md with functional requirements (RF-01...) and non-functional
   requirements (RNF-01...) of an ETL that reads the Bronze layer of the
   pharmacy chain from the local MinIO (bucket pharmacy-lake, prefix
   bronze/) and loads the Silver layer into a test Data Warehouse, a DuckDB
   file at WAREHOUSE_PATH. Each requirement has a description, an origin and
   at least one acceptance criterion written as Given / When / Then.
2. specs/plan.md with the components (extract, transform, load, pipeline),
   the Silver tables with their grain and primary key, the order of the
   steps, the two load modes and the technical choices, each pointing to a
   requirement.
3. specs/tasks.md with small tasks (T-01...), each with files, the test
   that proves it and the verification command.
The specification must cover, at least:
- extraction of three sources and three formats: POS sale lines in
  newline-delimited JSON, ERP stock positions in Parquet, supplier
  deliveries in CSV separated by ';' and encoded in Latin-1, plus the store
  and product master files in CSV;
- Bronze read as text, except Parquet, with the source file and the
  ingestion_date partition of each row;
- standardisation of store codes, dates in two formats, prices with a
  decimal comma, and the Portuguese column names of the supplier file;
- deduplication of POS lines posted twice and of the whole day that the
  terminal of JUN-04 resends the next morning;
- stock corrections of two days earlier, which arrive in a later extract
  and must replace the older value;
- quarantine with a reason for orphan products, invalid quantities,
  negative stock and deliveries without quantity;
- removal of customer_cpf before the warehouse;
- lineage columns in every Silver table;
- full load and incremental load by watermark, with a load log;
- rerun without new data producing no change, and a full load and an
  incremental load arriving at the same Silver.

Facts measured on 26/10/2026 with generate_bronze.py (confirm before use):
- Layout: bronze/source=<source>/entity=<entity>/ingestion_date=YYYY-MM-DD/
  <file>; pos/sale_line/batch_2300.json, erp/stock_position/extract.parquet,
  supplier/delivery/acme_0930.csv, erp/store/store.csv and
  erp/product/product.csv (masters only in the first partition).
- 14 days (2026-10-12 to 2026-10-25): 21,353 POS lines read, of which
  21,000 are unique sale_id values; 209 lines posted twice; 241 lines resent
  on 2026-10-18 in batch_0815_resend.json; 68 orphan products (ids 41 and
  42); 41 quantities equal to 0 or -1.
- Store BAU-05 sends sold_at as 'dd/mm/yyyy HH:MM:SS' in local time; the
  others send ISO 8601 with offset -03:00. Store SOR-03 sends unit_price as
  text with a decimal comma.
- Stock: 240 keys per day, 3,420 rows read, 3,360 unique keys
  (store_id, product_id, date); 60 audit corrections; 14 negative values;
  130 null on_hand values, all in JUN-04.
- Deliveries: 271 rows, 13 without quantity; header id_entrega;
  fornecedor; loja; produto; quantidade; custo_unitario; data_entrega.

[E] Example
### RF-04 · Deduplicate resent POS lines
Origin: Bronze contract of Lesson 3 (one Silver row per sale line).
Description: when the same sale_id arrives more than once, Silver keeps
the delivery with the latest ingestion_date and, within it, the latest
source file.
Acceptance criterion:
- Given that the terminal of JUN-04 sent part of 2026-10-17 in
  batch_2300.json and resent the whole day on 2026-10-18,
  when the full load processes both partitions,
  then silver.sale_line has one row per sale_id of JUN-04 on that day,
  all with ingestion_date = 2026-10-18.

[A] Adjustments
- Requirements must be verifiable: no "fast", "reliable" or "robust"
  without a measure. Values without a source are marked "hypothesis —
  validation pending".
- Do not hard-code the measured counts in the requirements: the criterion
  compares the pipeline with what the generator printed.
- Every row read must end in a Silver table or in the quarantine; write a
  requirement that states this accounting.
- Silver of this lesson is conformed, not modelled: no star schema, no
  Data Vault (Lessons 5 and 6).
- Do not write code.

[T] Type of output
Three Markdown files: spec.md (context in five lines, RF list, RNF list,
traceability table requirement | origin, section "Facts, gaps and
assumptions"), plan.md (up to 80 lines, with a Mermaid flowchart of the
pipeline) and tasks.md (one task per extract, transform rule group, load
mode and pipeline entry point).

[E] Extras
Read AGENTS.md and the docstring of generate_bronze.py before starting.
Show the index of the requirements before writing the files. Ask if the
documents conflict. Stop at the end.
Review before moving on

Does every RF have a Given / When / Then criterion that can become a test? Is there a requirement for the 241 resent lines and another for the audit corrections? Is the accounting requirement there (read = Silver + quarantine)? Does any requirement keep customer_cpf in the warehouse? Did the plan choose a primary key for each Silver table and say how the incremental load knows where it stopped?

Prompt 2 · Extraction from Object Storage

Prompt 2 · CREATE
[C] Character
You are the data engineer who implements the extraction. You follow
specs/spec.md, specs/plan.md and specs/tasks.md, and you only touch the
files of the extraction tasks.

[R] Request
Implement src/config.py and src/extract.py with tests in
tests/test_extract.py:
- config.py loads .env and opens a DuckDB connection with the httpfs
  extension and an S3 secret pointing to the MinIO (endpoint, path-style
  URLs, SSL from S3_USE_SSL);
- extract.py exposes list_partitions(con, entity_path, after=None), which
  lists the files of the partitions with glob and keeps only those whose
  ingestion_date is greater than after, and extract(con, after=None),
  which creates three staging tables raw_sale, raw_stock and raw_delivery
  plus the masters, each with source_file and ingestion_date;
- POS JSON read with format='newline_delimited' and explicit columns, all
  VARCHAR; Parquet read with its own types; CSV read with delim=';',
  encoding='latin-1' and all_varchar=true.

[E] Example
raw_sale for the 14 days has 21,353 rows and 15 distinct source files
(14 batch_2300.json and one batch_0815_resend.json); after=2026-10-25
returns only the files of 2026-10-26.

[A] Adjustments
- Bronze is read-only.
- The incremental extraction reads the list of files returned by
  list_partitions; it does not read the glob of all days with a WHERE on
  ingestion_date (measured on 26/10/2026: with JSON, the WHERE still read
  18 files and 5.35 MiB to return one day; the explicit list read 0.63 MiB).
- No type conversion in this step, except what Parquet already carries.
- Unit tests use fixtures in tests/fixtures/ and a local path instead of
  the MinIO; one integration test reads the MinIO.

[T] Type of output
The two modules, the tests, the fixtures and the task marked as done in
specs/tasks.md with the command used to verify it.

[E] Extras
Read AGENTS.md and the three spec files. Show the plan before editing.
Run pytest and show the counts of each staging table. Stop at the end.
Review before moving on

Do the counts of raw_sale, raw_stock and raw_delivery match the generator output? Does every staging row have source_file and ingestion_date? Did the agent read the CSV with the right encoding (look for "Distribuição")? Does the incremental path use the list of files?

Prompt 3 · Transformation from Bronze to Silver

Prompt 3 · CREATE
[C] Character
You are the data engineer who implements the Silver rules. You write SQL
in DuckDB, executed from Python, and you keep every rule traceable to a
requirement.

[R] Request
Implement src/transform.py with tests in tests/test_transform.py. The
module creates three conformed tables, t_sale, t_stock and t_delivery,
each with a column reason that is NULL for valid rows and holds the
quarantine reason otherwise. Rules:
- cleaning: deduplicate sale_id keeping the latest ingestion_date and
  source_file; deduplicate (store_id, product_id, date) keeping the latest
  ingestion_date and extracted_at; send orphan products, quantity <= 0,
  negative on_hand and deliveries without quantity to quarantine; keep a
  null on_hand as NULL (a missing count is not imputed);
- formatting: upper(trim()) of store codes; sold_at from ISO with offset
  or from 'dd/mm/yyyy HH:MM:SS', both as local time of America/Sao_Paulo;
  unit_price and unit_cost with the decimal comma replaced;
- type conversion with try_cast and try_strptime;
- enrichment: store_id by lookup of the store code, line_amount =
  quantity * unit_price, sold_date, is_stockout = (on_hand = 0), and the
  lineage columns;
- customer_cpf dropped.

[E] Example
For the 14 days: t_sale has 21,000 rows, 20,891 with reason NULL, 68
orphan_product and 41 invalid_quantity; t_stock has 3,360 rows and 14
negative_on_hand; t_delivery has 271 rows and 13 missing_quantity.

[A] Adjustments
- No row disappears: for each entity, rows after deduplication = valid +
  quarantined. Write this as a test.
- The first failing rule gives the reason (one reason per row).
- No Python loop over rows: the rules are SQL over the whole table.
- No cast that aborts the run.

[T] Type of output
The module, the tests, and a short table in specs/plan.md mapping each
rule to its requirement.

[E] Extras
Read AGENTS.md, the spec files and src/extract.py. Show the plan before
editing. Run pytest and print the counts by entity and reason. Stop at
the end.
Review before moving on

Do the counts match the generator? Does any valid row still have a store code with spaces or lower case? Is sold_at of BAU-05 at the same local time as the text it came from? Is there any column with CPF in t_sale? Is the rule order documented?

Prompt 4 · Load into the Data Warehouse

Prompt 4 · CREATE
[C] Character
You are the data engineer who loads the warehouse. You care about
idempotency, integrity and the cost of each load mode.

[R] Request
Implement src/load.py and src/pipeline.py with tests in tests/test_load.py:
- load.py creates the schema silver and the tables store, product,
  sale_line, stock_position, delivery, quarantine and load_log, with a
  primary key on the grain of each Silver table;
- full mode rebuilds the Silver tables from all partitions (drop and
  create, then insert);
- incremental mode reads the watermark max(to_date) from silver.load_log,
  extracts only newer partitions and applies MERGE INTO by key, so that a
  resend or an audit correction updates the existing row;
- the whole load of a run is one transaction, and the load log records
  run_id, entity, mode, from_date, to_date, rows_read, rows_loaded,
  rows_quarantined, started_at and finished_at;
- pipeline.py runs: python -m src.pipeline full | incremental.

[E] Example
Measured on 26/10/2026: full load of 14 days gives sale_line 20,891,
stock_position 3,346, delivery 258 and quarantine 136; after
generate_bronze.py --day 2026-10-26, the incremental load reads 1,515 POS
lines and leaves sale_line with 22,380 rows, the same number that a new
full load produces; a second incremental run finds nothing after the
watermark and changes nothing.

[A] Adjustments
- Full mode does not delete row by row from tables with a primary key
  (measured: DELETE plus MERGE over 1.1 million rows took 32 s, against
  3.4 s to rebuild).
- Quarantine of a reprocessed ingestion_date is replaced, not appended.
- A failed run leaves the warehouse as it was before the run.
- Tests use a temporary warehouse file.

[T] Type of output
The modules, the tests, the commands of the verification in a section of
specs/tasks.md and an ADR in docs/adr/ADR-001-full-and-incremental-load.md
comparing the two modes with the measurements of the group.

[E] Extras
Read AGENTS.md, the spec files and the previous modules. Show the plan
before editing. Run full, generate one more day, run incremental twice,
run full again and show the counts after each run. Stop at the end.
Review before moving on

Do full and incremental arrive at the same counts? Does the second incremental run change nothing? Does the grain query return no rows? Does the load log explain each run? Does the ADR use the numbers of the group instead of the ones in this prompt?

16. Verification

The verification proves three things: that the pipeline closes the accounting of rows, that it is idempotent, and that it keeps privacy and lineage. The sequence below runs the full load, generates one more day, runs the incremental load twice and the full load again, and then inspects the warehouse.

Terminal · lesson_04_etl/
pytest -q
python -m src.pipeline full
python generate_bronze.py --day 2026-10-26
python -m src.pipeline incremental
python -m src.pipeline incremental          # must find nothing after the watermark
python -m src.pipeline full                 # must arrive at the same counts
python - <<'EOF'
import duckdb
con = duckdb.connect("warehouse/pharmacy.duckdb", read_only=True)
for t in ["sale_line", "stock_position", "delivery", "quarantine"]:
    print(t, con.sql(f"SELECT count(*) FROM silver.{t}").fetchone()[0])
print(con.sql("SELECT entity, reason, count(*) FROM silver.quarantine GROUP BY ALL ORDER BY ALL"))
print(con.sql("""SELECT store_id, product_id, date, count(*) FROM silver.stock_position
                 GROUP BY ALL HAVING count(*) > 1"""))       # must return no rows
print(con.sql("SELECT * FROM silver.load_log ORDER BY started_at"))
EOF
TableAfter the full load of 14 daysAfter the incremental load of 2026-10-26
silver.sale_line20,89122,380
silver.stock_position3,3463,585
silver.delivery258281
silver.quarantine136150

The day 26/10 generated by the option --day carries 1,515 POS lines, 15 of them posted twice, 9 orphan products and 2 invalid quantities, 245 stock rows with 5 audit corrections of 24/10, and 25 deliveries, 2 of them without quantity. The incremental run read the 1,515 lines, loaded 1,489 and quarantined 11, and read 245 stock rows, of which 244 were loaded and 1 quarantined. The totals of the warehouse after it are identical to those of a new full load of the fifteen days, and a second incremental run reports that there is nothing after the watermark.

17. Recurring mistakes of agents

The reference pipeline was built with the same prompts, and the mistakes below appeared in that work or are typical of agents in pipelines of this kind. Each one passes a superficial test and is caught by a count.

The most frequent mistake is to let the reader infer types. An agent writes read_json_auto or read_csv without options, the inference works on the sample of the first files, and the run fails on the first price of SOR-03 or, worse, reads the date of BAU-05 as month first without any error. Reading as text and converting with try_cast removes both failures.

The second mistake concerns the supplier file. Read with the default encoding, the name of the supplier appears as Distribuição, and nothing fails. The review of prompt 2 asks the group to look for the cedilla precisely because the error is silent.

The third mistake is to filter the incremental extraction with a WHERE on the partition column and to assume that only the new files are read. Section 7 shows that, with JSON, the engine still opened every file. The test that catches it reads the HTTP log of DuckDB or simply counts the files passed to the reader.

The fourth mistake is to deduplicate after the validation, or to deduplicate by the whole row instead of by the key. Deduplicating by the whole row keeps the incomplete night batch of JUN-04 and the resend as different rows whenever any field differs, and deduplicating after the validation can send to the quarantine a copy whose newer version was valid.

The fifth mistake is to impute missing values. Agents tend to fill on_hand with zero or with the previous count, which makes the tests pass and changes the indicator of stock-outs that Gold will compute.

The sixth mistake is to keep the CPF in the quarantine by storing the staging row there, and the seventh is to implement the full mode as a deletion followed by a merge, which works but costs ten times more on the benchmark, as section 12 measured. The eighth, finally, is to write the measured counts of the prompts into the assertions of the tests. A test with the number 20,891 written in it passes on the lab data and has no meaning for the partner data. The tests should compare the pipeline with the counts that the generator prints or with invariants such as the accounting of rows.

18. Quality scenarios and deliverable

The quality of the pipeline is expressed, as in the ATAM of Lesson 3, through scenarios with a stimulus and a measurable response. The group records them in docs/ with the evidence produced by its own run.

StimulusExpected responseEvidence
a terminal resends a whole dayone row per sale_id, latest delivery kept241 rows of JUN-04 on 17/10, all ingested on 18/10
an audit corrects the stock of day minus twothe older count is replaced and no row is addedthe grain query returns no rows
a price arrives as text with a commaconverted, never an aborted run3,580 lines of SOR-03 in Silver
the incremental load runs twicethe second run changes nothingload log with nothing after the watermark
the run fails in the third tablethe warehouse stays as before the runa test that raises inside the transaction
a new day of 74,000 lines arrivesloaded in a time proportional to one dayincremental time against full time, measured by the group

By the end of the session, each group should have the MinIO running with the Bronze of fourteen days, the reviewed specification in specs/, the extraction and the transformation with tests passing, and a first full load with the counts of section 16. During the week, before Lesson 5 on 05/11, the group completes the incremental mode and the comparison between the two modes, writes the ADR with its own measurements, records the six scenarios and points the same pipeline at a sample of the partner data.

The deliverable is the folder lesson_04_etl/ in the group repository, with AGENTS.md, specs/ (spec, plan and tasks), src/ (config, extract, transform, load and pipeline), tests/ passing and docs/adr/ADR-001-full-and-incremental-load.md. The warehouse file and .env are not committed, and anyone can rebuild the warehouse with the generator and a full load.

19. Glossary

Accounting of rows
The invariant that every row read, after the removal of copies, ends in Silver or in the quarantine.
Backfill
A run that reprocesses a window of past partitions, usually after a rule was corrected, without moving the watermark.
ELT
Extract, load and transform: raw data is loaded into the warehouse and transformed there.
ETL
Extract, transform and load: data is transformed in an engine outside the warehouse, which receives only conformed data.
Grain
What one row of a table represents, identified by the key of the table.
Hive partitioning
The convention of writing name=value segments in the keys of objects, read by engines as columns.
Idempotency
The property of a run that produces the same result when it is executed twice with the same input.
Lineage
The record of where each row came from: source file, partition, run and time of load.
MERGE
SQL statement that updates the rows whose key already exists and inserts the others, also called upsert.
Partition pruning
Skipping files or row groups that cannot contain rows of a filter, using the keys or the statistics.
Quarantine
The table that keeps the rows that broke a rule of Silver, with the reason and the lineage.
Row group
A horizontal division of a Parquet file, with one chunk per column and the minimum and maximum of each chunk in the footer.
Schema on read
Types decided by whoever reads the files, as in a lake.
Schema on write
Types checked when the data is written, as in a warehouse.
Staging table
A temporary table that holds the rows of the extraction before the transformation.
Watermark
The highest ingestion date already loaded, from which the next incremental run starts.

20. Checklist

  • .env and warehouse/ are ignored by Git, checked with git status --short.
  • The output of the generator is kept in the folder and referenced by the tests.
  • The spec has a requirement for the accounting of rows, one for the resend of JUN-04 and one for the audit corrections.
  • Every staging row has source_file and ingestion_date.
  • The supplier name reads Distribuição, with the cedilla.
  • The incremental extraction reads an explicit list of files.
  • For each entity, rows after deduplication equal rows in Silver plus rows in quarantine.
  • No store code with spaces or lower case in Silver.
  • sold_at of BAU-05 is at the same local time as the text it came from.
  • No column with CPF in any table of the warehouse, quarantine included.
  • The second incremental run changes nothing, and the full and incremental loads arrive at the same counts.
  • The ADR compares the two modes with the measurements of the group.

21. References

  • APACHE SOFTWARE FOUNDATION. Apache Parquet: File Format. Available at: parquet.apache.org/docs/file-format.
  • APACHE SOFTWARE FOUNDATION. RDD Programming Guide. Apache Spark documentation. Available at: spark.apache.org/docs/latest/rdd-programming-guide.html.
  • AMAZON WEB SERVICES. Amazon Redshift Database Developer Guide: COPY, MERGE and defining table constraints. Available at: docs.aws.amazon.com/redshift.
  • AMAZON WEB SERVICES. Amazon S3 User Guide: organizing objects using prefixes. Available at: docs.aws.amazon.com/AmazonS3.
  • ARMBRUST, M.; GHODSI, A.; XIN, R.; ZAHARIA, M. Lakehouse: a new generation of open platforms that unify data warehousing and advanced analytics. In: Conference on Innovative Data Systems Research (CIDR), 2021.
  • CLICKHOUSE. MergeTree table engine and ReplacingMergeTree. ClickHouse documentation. Available at: clickhouse.com/docs.
  • DUCKDB FOUNDATION. DuckDB documentation: S3 API support, reading multiple files, Hive partitioning, MERGE statement. Available at: duckdb.org/docs.
  • INMON, W. H. Building the Data Warehouse. 4th ed. Indianapolis: Wiley, 2005.
  • KIMBALL, R.; CASERTA, J. The Data Warehouse ETL Toolkit. Indianapolis: Wiley, 2004.
  • KLEPPMANN, M. Designing Data-Intensive Applications. Sebastopol: O'Reilly, 2017.
  • MICROSOFT. Extract, transform, load (ETL). Azure Architecture Center. Available at: learn.microsoft.com/en-us/azure/architecture/data-guide/relational-data/etl.
  • MINIO. MinIO Object Storage documentation. Available at: min.io/docs.
  • RAASVELDT, M.; MÜHLEISEN, H. DuckDB: an embeddable analytical database. In: ACM SIGMOD International Conference on Management of Data, 2019.
  • REIS, J.; HOUSLEY, M. Fundamentals of Data Engineering. Sebastopol: O'Reilly, 2022.
  • ROCKLIN, M. Dask: parallel computation with blocked algorithms and task scheduling. In: Python in Science Conference (SciPy), 2015.
  • ZAHARIA, M. et al. Resilient distributed datasets: a fault-tolerant abstraction for in-memory cluster computing. In: USENIX Symposium on Networked Systems Design and Implementation (NSDI), 2012.