Module 8 · Information Systems · Lesson 4 · Week 3

Instruction session · Thursday, October 29, 2026 · 11:00 to 13:00

ETL: Object Storage to Data Warehouse

The Bronze layer of the pharmacy chain sits in a local MinIO, in JSON, Parquet and CSV. In four rounds, a coding agent builds the pipeline that extracts it, conforms it and loads it into a DuckDB warehouse as the Silver layer, and while the agent works the slides explain what each step does and what it costs.

ETL and ELTMinIO · S3 APIDuckDBCSV · JSON · ParquetBronze to SilverFull and incremental loads

Project ritual

Daily · 15 minutes

Each group reports the progress of its deliverables, the work planned for this session and the blockers that require a decision.

15:00
What I didWhat I will doBlockersProgress
Agenda · 11:15 to 13:00
Four rounds of prompt, build and explanation

Each round starts with a prompt to the coding agent. While the agent writes the files, the slides explain the mechanism that those files implement, and the round ends with a review of what the agent produced.

11:25 · round 1SpecificationAgent: spec, plan and tasksSlides: ETL and ELT, the Bronze to Silver contract
11:40 · round 2ExtractionAgent: src/extract.pySlides: how a query reads Object Storage, formats and partitions
11:57 · round 3TransformationAgent: src/transform.pySlides: cleaning, formatting, type conversion, enrichment, quarantine
12:15 · round 4LoadAgent: src/load.pySlides: warehouse and lake, full and incremental loads
11:15

Case and setup

The Bronze layer of the case, the target architecture and the local MinIO with the generated data.

12:35

Verification

Counts against the generator, rerun without new data, and a full load that must match the incremental one.

12:47

Closing

Quality attribute scenarios of the pipeline, what remains for the week and the self-study.

Running case · Problem
Three sources, three formats, one Silver layer

The pharmacy chain of the module has six stores and forty products. Lesson 3 defined the contracts of each layer, and this session builds the step that turns what arrived in Bronze into the conformed entities that Silver promises.

POS · JSON

Sale lines, every night

One file per day with about 1,500 lines. BAU-05 sends dates as dd/mm/yyyy, SOR-03 sends prices as text with a comma, and JUN-04 lost its connection on 17/10 and resent the whole day the next morning.

ERP · Parquet

Stock positions, every night

240 keys per day, already typed. Audits correct the count of two days earlier, and the correction arrives in a later extract. JUN-04 often closes the day without a count.

Supplier · CSV

Deliveries, every morning

Separator ;, Latin-1 encoding, Portuguese headers, decimal comma and dates as dd/mm/yyyy. Some rows arrive without a quantity.

Result of the sessionA DuckDB warehouse with the schema silver: store, product, sale_line, stock_position and delivery, each with a declared grain and its lineage, plus quarantine and load_log. Every row read from Bronze ends in one of these tables, and none of them stores the customer CPF.
Target architecture · one run
From the bucket to the warehouse in one run
POSbatch_2300.json ERPextract.parquet Supplieracme_0930.csv MinIObronze/read-only ExtractDuckDB · httpfs TransformSQL rules LoadMERGE by key Warehousepharmacy.duckdbsilver.* quarantinerow + reason load_logwatermark Last request   Rows read 0 In Silver 0 Quarantined 0 Watermark none

 

  1. 1 · sources deliver
  2. 2 · list partitions
  3. 3 · read files
  4. 4 · conform
  5. 5 · quarantine
  6. 6 · merge
  7. 7 · watermark
11:18 · Environment
Local MinIO with the Bronze of 14 days

The support files are in lab/lesson-4/ of the module. The group folder is lesson_04_etl/, the same one that Lessons 5 and 6 will extend.

Terminal · group repository
mkdir -p lesson_04_etl/{specs,src,tests/fixtures,docs/adr,warehouse}
cp lab/lesson-4/* lab/lesson-4/.env.example lesson_04_etl/
cd lesson_04_etl
printf '.env\n.venv/\n__pycache__/\nwarehouse/\n' >> .gitignore
cp .env.example .env && git check-ignore .env
docker compose up -d --wait
python3 -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt
python generate_bronze.py        # 45 objects, 4.4 MiB
echo "@AGENTS.md" > CLAUDE.md && claude
AGENTS.md · rules that matter today
  • Bronze is read-only.
  • Bronze is read as text, except Parquet; types come in the transformation, with try_cast.
  • Every row ends in Silver or in quarantine, with a reason.
  • The incremental extraction reads only the files of new partitions.
  • customer_cpf never reaches the warehouse.
  • Every Silver row carries source_file, ingestion_date, run_id and loaded_at.

The console of the MinIO is at localhost:9001. In a Codespace, open the forwarded port. Any coding agent works; the rules are the same file.

Numerical example 1 · Bronze measured on 26/10/2026
What the generator planted in the Bronze

generate_bronze.py is deterministic and prints how many defects it planted. Those numbers are the expected result of the pipeline, which is how the group knows whether the agent got the rules right.

POS · sale linesRowsExpected in Silver
lines read (14 batches + 1 resend)21,35321,000 unique sale_id
posted twice in the same file209removed by deduplication
JUN-04 resend of 17/10241one row each, ingested 18/10
orphan product (41, 42)68quarantine
quantity 0 or -141quarantine
dd/mm/yyyy dates (BAU-05)3,447parsed, local time
price with comma (SOR-03)3,580converted to decimal
store code dirty2,070standardised
ERP and supplierRowsExpected in Silver
stock rows read3,4203,360 keys of the grain
audit corrections (day − 2)60replace the older count
negative on_hand14quarantine
null on_hand (JUN-04)130kept as NULL, not imputed
deliveries read271one row per id_entrega
delivery without quantity13quarantine
Accounting that the pipeline must closePOS 21,000 = 20,891 in Silver + 109 in quarantine. Stock 3,360 = 3,346 + 14. Deliveries 271 = 258 + 13. A pipeline that loads 20,891 sale lines but cannot say where the other 462 rows went has lost data, even if every query works.
Round 1 · 11:25 · Prompt 1
Specification before code

The agent writes specs/spec.md, specs/plan.md and specs/tasks.md. The prompt brings the facts measured in the Bronze, so that the requirements are written against data that exists.

Excerpt of the example in the prompt · full text in the material, section 6
### RF-04 · Deduplicate resent POS lines
Origin: Bronze contract of Lesson 3.
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.
- 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.
The spec must cover
  • three formats and the master files
  • standardisation, deduplication and corrections
  • quarantine with a reason
  • CPF removed, lineage kept
  • full and incremental loads, with a load log
Review before moving on

Is there a requirement that every row read ends in Silver or in quarantine? Did the plan choose a key for each table and say how the incremental load knows where it stopped?

Block 1 · while the agent writes the spec
ETL transforms before loading, ELT after
ETL ELT Bronzeobject storage Transform enginePython · Spark · DuckDB Warehousesilver.*conformed rows only Bronzeobject storage Warehouse · raw.*text, CPF included Warehouse · silver.*CREATE TABLE AS SELECTSQL inside the warehouse CPF stored 0 CPF stored 0  

 

  1. 1 · ETL extracts
  2. 2 · transforms outside
  3. 3 · loads Silver
  4. 4 · ELT loads raw
  5. 5 · transforms inside
  6. 6 · what stayed
Block 1 · ETL and ELT
Where the transformation runs decides five things

Both approaches extract, transform and load. They differ in the place where the transformation runs, and that place determines who pays for the computation, what the warehouse stores and how an error is corrected.

AspectETL · transform, then loadELT · load, then transform
Computationan engine outside the warehouse (Python, Spark, Dask, DuckDB)the warehouse itself, in SQL (Redshift, ClickHouse, BigQuery, Snowflake)
What the warehouse storesonly conformed dataraw data and conformed data, with the sensitive fields of the raw
Correcting a rulererun the engine from Bronze, which must still existrerun the SQL over the raw tables, without a new extraction
Fits whenthe warehouse is expensive per byte or per query, data must be masked before landing, or the logic needs code beyond SQLthe warehouse scales cheaply, analysts own the SQL (dbt), and the raw data may be kept under the same governance
Main riskthe engine becomes a second platform to operatethe warehouse becomes a lake of raw tables nobody conforms
In this sessionThe medallion architecture already keeps the raw data, in Bronze, in Object Storage. The pipeline transforms with DuckDB before the warehouse, which is ETL from the point of view of the warehouse and ELT from the point of view of the lake. The second view explains why Lesson 3 called the medallion a form of ELT.
Block 1 · Medallion architecture
What Silver guarantees that Bronze does not

A layer is defined by the guarantee it gives to the next one. The transition from Bronze to Silver is the point where data stops being what the source sent and becomes an entity the organisation can trust.

PropertyBronze · rawSilver · workingGold · curated (Lessons 5 and 6)
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
Lineagepath 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 is the reason why Bronze is read-only. If the pipeline altered Bronze, a wrong rule in Silver could no longer be corrected by recomputing it.

Block 1 · Numerical example 2 · 1.1 million sale lines
ELT kept the CPF of every customer in the warehouse

The same generator, with 73,500 sales per day, produced 1,120,749 POS lines in 15 days. Both paths were run on the professor's machine on 26/10/2026, with DuckDB 2.0.0 and the MinIO local.

MeasureETL (this pipeline)ELT (raw first)
Rows written to the warehouse in the first step1,096,943 conformed1,120,749 raw
Rows of the warehouse that contain a CPF01,120,749
Time of the first step6.0 s (extract, transform, load)2.9 s (load only)
Size of the POS data in the warehouse23 MiB without index · 142 MiB with key33 MiB raw, before Silver
What the measurement showsELT lands faster because it does nothing to the data, and the transformation time moves to the next step. The cost that does not move is governance: from the first second, the warehouse holds the CPF of every customer, and the LGPD treatment that Silver promised now depends on the access rules of a second system.
Block 1 · Pause for reflection
The partner wants to count returning customers

The purchasing team asks for a weekly indicator of customers who bought a continuous-use medicine twice in thirty days. The only identifier of the customer in the POS file is customer_cpf, and the AGENTS.md says it never reaches the warehouse. What should the Silver layer do?

Option A

Keep the CPF in Silver

The indicator becomes a simple query, and the warehouse holds the identifier of every customer.

Option B

A keyed hash of the CPF

A column customer_key computed with a secret key outside the warehouse. Who keeps the key, and what happens if it leaks?

Option C

Compute the indicator in the ETL

Silver receives only the count per week and product. Can the team answer a new question about the same customers later?

And before choosing

Who decides?

Which data viewpoint of Lesson 3 records this decision, and which requirement of the spec changes?

Block 1 · Synthesis
Key points of block 1
  1. ETL and ELT differ in where the transformation runs, and that place decides who computes, what the warehouse stores and how a rule is corrected.
  2. Silver guarantees grain, declared types, quarantine with a reason, removal of sensitive fields and lineage. Bronze guarantees only that what arrived was kept.
  3. Bronze is read-only, because it is the only layer from which Silver can be rebuilt.
  4. The pipeline closes an accounting: every row read ends in Silver or in quarantine.
Back to the agentReview the spec with the questions of the prompt slide before sending prompt 2. A missing requirement now becomes a missing test later.
Round 2 · 11:40 · Prompt 2
Extraction from the bucket into staging tables

The agent writes src/config.py and src/extract.py. The extraction does not convert types: it reads the three formats into staging tables with the file and the partition of each row.

What the extraction must look like · DuckDB from Python
con.execute("INSTALL httpfs; LOAD httpfs;")
con.execute("""CREATE SECRET lake (TYPE s3, KEY_ID ?, SECRET ?,
  ENDPOINT 'localhost:9000', URL_STYLE 'path', USE_SSL false)""")
files = list_partitions(con, "source=pos/entity=sale_line",
                        after=watermark)        # one LIST
con.execute(f"""CREATE TEMP TABLE raw_sale AS
  SELECT * FROM read_json({files}, format='newline_delimited',
    hive_partitioning=true, filename='source_file',
    columns={{sale_id:'VARCHAR', unit_price:'VARCHAR', ...}})""")
Expected counts

raw_sale 21,353 rows from 15 files, raw_stock 3,420, raw_delivery 271. With after=2026-10-25, only the files of 26/10.

Review before moving on

Does every staging row have source_file and ingestion_date? Does the supplier name read "Distribuição", with the cedilla? Does the incremental path read a list of files?

Block 2 · while the agent writes the extraction
Object Storage as the foundation of the lake

Lesson 2 of the module wrote the Parquet sample to the raw zone. The extraction now reads that kind of storage at scale, and three properties of object storage shape how it should be read.

Flat namespace

Keys, not folders

bronze/source=pos/entity=sale_line/ingestion_date=2026-10-17/batch_2300.json is one key. The slashes and the name=value segments are a convention that engines read as Hive partitions, so the layout of the keys is the index of the lake.

Whole objects

Write once, read by range

An object is replaced, never edited. Reads can ask for a byte range with the Range header, which is what lets an engine read the footer and a few columns of a Parquet file without downloading it.

Cost per request

LIST, HEAD and GET are billed

On Amazon S3 each request has a price and a latency of tens of milliseconds. Thousands of small files cost more to list and open than a few large ones with the same bytes.

Why it is the foundation of a lakeStorage is separated from computation, so DuckDB on a laptop, Spark on a cluster and Redshift Spectrum read the same objects. Capacity grows without a schema, which is why Bronze can keep every delivery. Durability is a property of the service, and the price per GB is lower than that of a database disk, which makes it cheap to keep history.
Block 2 · How the engine reads the bucket
The same question, read from a CSV and from a Parquet file
Query SELECT sum(quantity) FROM sale_line WHERE store_code = 'CMP-01' CSV · 90 MiB Parquet · 25 MiB · 9 row groups × 8 columns + footer CSV read 0 MiB Parquet read 0 MiB GET requests 0

 

  1. 1 · CSV: read all
  2. 2 · parse all rows
  3. 3 · Parquet: footer
  4. 4 · skip row groups
  5. 5 · read 2 columns
  6. 6 · compare
Block 2 · File formats
CSV, JSON and Parquet, read by DuckDB

Each format of the case needs different options in the reader. The options that matter are the ones that tell the engine what the file does not say about itself.

FormatWhat the file carriesWhat the reader must be toldReader in the case
CSVtext by rows; no types, no encoding, no schema beyond the headerseparator, header, encoding, decimal and date formats; read as text to avoid wrong inferenceread_csv(files, delim=';', encoding='latin-1', all_varchar=true)
JSON Linesone object per line; field names and a few types (number, string)that it is newline-delimited, and the columns, because inference from a sample fails when one terminal sends a price as textread_json(files, format='newline_delimited', columns={...})
Parquetschema, types, row groups, column chunks, min and max of each chunk, compressionnothing about the content; only the files and the partitioningread_parquet(files, hive_partitioning=true)
Lineage

filename='source_file' adds the key of the object to each row. Without it, a wrong row in Silver cannot be traced to its delivery.

Partitions

hive_partitioning=true turns ingestion_date=2026-10-17 in the key into a column of the row.

Text first

Reading as text moves every conversion to the transformation, where a failure becomes a quarantine reason instead of an aborted run.

Block 2 · Numerical example 3 · 1,046,514 sale lines
The same rows in three formats, read from the MinIO

The typed POS lines of 14 days at 73,500 sales per day were written as CSV, JSON Lines and Parquet in the bucket. DuckDB 2.0.0 ran each query with the HTTP cache off, and the HTTP log gave the requests and the bytes.

FormatSizecount(*)sum of one storeGETsTime
CSV90 MiB118 MiB read120 MiB read630.22 s
JSON Lines200 MiB232 MiB read232 MiB read1170.36 s
Parquet25 MiB0.03 MiB read0.12 MiB read70.011 s
What the measurement showsThe count in Parquet reads only the footer, which already stores the number of rows. The sum of one store reads the footer, uses the minimum and maximum of store_code in each row group to skip the groups of other stores, and downloads two columns of the rest. CSV and JSON have no footer and no statistics, so both questions download the whole file, and a little more than its size because the reader fetches overlapping blocks. On a laptop the difference is a fraction of a second; on S3, with latency and price per request, it is the cost of the pipeline.
Block 2 · Numerical example 4 · incremental extraction
Reading one new day out of fifteen

The incremental extraction must read only the partition of 26/10. Three ways of asking for it were measured on the POS JSON of the lab bucket, with the HTTP cache off.

How the extraction asks for the dayLISTHEADGETRead
glob of all days, no filter (full load)1164814.15 MiB
glob of all days with WHERE ingestion_date = '2026-10-26'116185.35 MiB
list of the files of the new partition, from glob()1120.63 MiB
Parquet of the ERP, glob with the same WHERE1020.01 MiB
What the measurement showsWith Parquet, the filter on the partition column is pushed to the list of files and the other days are not opened. With JSON, in DuckDB 2.0.0, the same filter still opened every file and read part of 17 of them. The rule of the AGENTS.md comes from this measurement: the incremental extraction computes the list of new files and reads only that list, which works the same way in any engine and any format.
Block 2 · Large volumes
When one machine stops being enough

The Adalove description of the session mentions Spark and Dask. Each answers the same question, what to do when the data does not fit in the memory of one process, in a different way.

DuckDB

One process, out of core

Executes in vectors of rows, in parallel threads, and spills to disk when an operator exceeds the memory limit. Fits the lab and most Silver loads up to hundreds of GB on one machine.

Apache Spark

A cluster of executors

Splits the files into partitions processed by executors on several machines. The self-study on RDDs explains the model: immutable partitions, lazy transformations and recomputation from lineage after a failure.

Dask

Pandas in partitions

Splits a dataframe into many pandas dataframes and schedules them on threads, processes or a cluster. Fits teams whose code is already pandas.

What changes with scaleWhat does not change
the number of machines, the size of the partitions, the cost of moving data between them (shuffle) in deduplications and joinsthe contract of Silver, the rules of the transformation, the accounting of rows and the idempotency of the load; the specification written in round 1 is valid for any of the three engines
Block 2 · Pause for reflection
The supplier now sends 300 small files a day

ACME changes its integration: instead of one acme_0930.csv per morning, it writes one CSV per delivery, about 300 files a day of 400 bytes each. In a year, the partition folder of deliveries has 109,500 objects. What happens to the extraction, and what should the pipeline do?

Option A

Nothing changes

The glob and the list of files still work. How many LIST pages and GET requests does a full load make, and what does that cost on S3?

Option B

Compact in Bronze

A job concatenates the day into one file. Does that break the rule that Bronze is read-only, and where would the compacted file go?

Option C

Compact at the boundary

The extraction of each day writes one Parquet staging file per partition, and later runs read the staging. Which layer is that file in?

And the watermark

Late files

If a file of 25/10 arrives on 27/10, in the folder of 25/10, does the incremental load see it?

Block 2 · Synthesis
Key points of block 2
  1. The layout of the keys is the index of the lake: name=value segments become partition columns, and the extraction chooses files by them.
  2. Parquet carries schema, types and statistics, so the engine reads the footer and a few column chunks; CSV and JSON are read whole.
  3. The incremental extraction reads an explicit list of new files, which is cheaper than a filter and does not depend on the format.
  4. Each row of staging carries its source file and its partition, the first link of the lineage of Silver.
Back to the agentCompare the counts of the staging tables with the generator output and check the cedilla in the supplier name before sending prompt 3.
Round 3 · 11:57 · Prompt 3
Silver rules in SQL, one reason per rejected row

The agent writes src/transform.py. Each conformed table has a column reason, NULL for valid rows and the first broken rule otherwise, so the split between Silver and quarantine is one query.

TechniqueRule in the case
Cleaningdedup sale_id by latest ingestion; dedup stock key by latest extract; quarantine orphans, quantity ≤ 0, negative stock, delivery without quantity; NULL on_hand kept
Formattingupper(trim(store_code)); sold_at from ISO or dd/mm/yyyy in local time; comma to point in prices
Type conversiontry_cast and try_strptime; a failure becomes a reason
Enrichmentstore_id by lookup, line_amount, sold_date, is_stockout, lineage; CPF dropped
Expected counts

t_sale 21,000 rows: 20,891 valid, 68 orphan_product, 41 invalid_quantity. t_stock 3,360 with 14 negative_on_hand. t_delivery 271 with 13 missing_quantity.

Review before moving on

Is sold_at of BAU-05 at the same local time as its text? Is there any column with CPF? Is rows after dedup = valid + quarantined a test?

Block 3 · while the agent writes the rules
The resent day of JUN-04, from Bronze to Silver
batch_2300.json · ingested 17/10 batch_0815_resend.json · ingested 18/10 row_number() OVER(PARTITION BY sale_idORDER BY ingestion_date DESC) reason, first rule brokenunknown_storeorphan_productinvalid_quantityinvalid_price, invalid_timestamp silver.sale_lineJUN-04 · 17/100 silver.quarantineall stores · 14 days0 Rows of JUN-04 · 17/10 read 0 After the window 0  

 

  1. 1 · night batch
  2. 2 · morning resend
  3. 3 · window by sale_id
  4. 4 · rules
  5. 5 · split
  6. 6 · whole case
Block 3 · Transformation techniques
Four techniques, each tied to a defect of the case

The Adalove description lists 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 the test can check.

Cleaning

Nulls, invalid values, duplicates

Duplicates are removed by key with a rule for which copy wins. Invalid values go to quarantine. A null is kept when it means "not measured": imputing zero to the 130 missing counts of JUN-04 would invent 130 stock-outs.

Formatting

Dates, numbers, strings

One representation per concept: store codes in upper case without spaces, one timestamp type in local time, prices with a decimal point. Formatting comes before any join or comparison.

Type conversion

Text to declared types

try_cast returns NULL instead of an error, which turns a bad value into a quarantine reason. A plain CAST would abort the run on the first price written as text.

Enrichment

Metadata and derived fields

Lineage columns, the store_id found from the code, line_amount, sold_date and is_stockout. Derived fields that every consumer would compute are computed once.

Order of the rulesFormatting and conversion run before deduplication and validation, because the key and the rules compare formatted values. A rule on the store code that ran before upper(trim()) would send 2,070 valid lines to quarantine.
Block 3 · The rules in SQL
One query that types, deduplicates and classifies
DuckDB · src/transform.py · sale lines
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',               -- ISO with offset
                  try_strptime(r.sold_at, '%d/%m/%Y %H:%M:%S'))     AS sold_at,  -- BAU-05
         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), CASE
         WHEN store_id IS NULL                       THEN 'unknown_store'
         WHEN product_id NOT IN (SELECT product_id FROM silver.product)
              OR product_id IS NULL                  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 never loops over rows in Python. On the 1.1 million lines of the benchmark, the transformation of the three entities took 1.0 s.

Block 3 · Numerical example 5 · reference pipeline, 14 days
Every row read has a destination

The reference pipeline, run on 26/10/2026 over the lab bucket, closes the accounting of each entity. These are the numbers the group's tests should reproduce.

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
353POS copies removed: 209 posted twice and 144 lines of JUN-04 sent before the resend
60stock counts replaced by audit corrections that arrived two days later
130stock positions in Silver with NULL on_hand, counted by a check, not imputed
0rows of the warehouse with a CPF, quarantine included
Block 3 · Pause for reflection
68 sale lines point to products that do not exist

The 68 lines with product_id 41 or 42 are in quarantine. On Monday, the ERP adds products 41 and 42 to the master file, with a new product.csv in the partition of that day. The sales were real. What should happen to the quarantined lines?

Option A

Nothing

The quarantine is a record of the past. The weekly indicator of those days stays without 68 lines. Who is told?

Option B

Reprocess the days

A full load rebuilds Silver with the new master and the lines become valid. Is the full load cheap enough to be the answer?

Option C

Retry the quarantine

Each run tries the quarantined rows again before the new ones. What makes this safe, and what makes it dangerous?

The general question

Late master data

Is orphan_product a property of the row or of the moment in which the row was checked?

Block 3 · Synthesis
Key points of block 3
  1. Cleaning, formatting, conversion and enrichment are rules over the whole table, written in SQL and tied to a defect with a known count.
  2. Formatting and conversion come before deduplication and validation, because keys and rules compare formatted values.
  3. try_cast turns a bad value into a quarantine reason; one reason per row, the first rule broken.
  4. A null that means "not measured" is kept and counted. Imputing it changes the indicator that Gold will compute.
Back to the agentPrint the counts by entity and reason and compare them with the table of the numerical example before sending prompt 4.
Round 4 · 12:15 · Prompt 4
Full and incremental loads into the warehouse

The agent writes src/load.py and src/pipeline.py. The full mode rebuilds Silver from all partitions. The incremental mode reads the watermark of the load log and merges only the new partitions by key.

Incremental merge · DuckDB
BEGIN;
MERGE INTO silver.stock_position t
USING (SELECT * FROM t_stock WHERE reason IS NULL) s
   ON t.store_id = s.store_id AND t.product_id = s.product_id
  AND t.date = s.date
WHEN MATCHED THEN UPDATE           -- audit correction
WHEN NOT MATCHED THEN INSERT;      -- new day
INSERT INTO silver.load_log VALUES (run_id, 'stock_position',
  'incremental', '2026-10-26', '2026-10-26', 245, 244, 1, ...);
COMMIT;
Expected counts

Full of 14 days: sale_line 20,891. After --day 2026-10-26 and an incremental run: 22,380, the same as a new full load. A second incremental run changes nothing.

Review before moving on

Is the full mode a rebuild, not a delete row by row? Is the whole run one transaction? Does the ADR use the group's own measurements?

Block 4 · while the agent writes the load
Data Warehouse and Data Lake in the same pipeline

The pipeline reads from a lake and writes to a warehouse. The two are complementary: the lake keeps everything that arrived, cheaply and in any format, and the warehouse serves typed tables to many concurrent queries.

AspectData Lake (MinIO, S3)Data Warehouse (DuckDB here; ClickHouse, Redshift)
Schemaon read: the reader decides the typeson write: the load fails or quarantines 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, applications, through SQL
ClickHouse

Columnar and open source. Tables of the MergeTree family are sorted by an ORDER BY key and merged in the background. The key orders and indexes the data but does not enforce uniqueness, so deduplication is done in the ETL or with ReplacingMergeTree. Reads S3 directly with the s3() table function.

Amazon Redshift

Columnar, managed, massively parallel. Loads from S3 with COPY, distributes rows by a distribution key and orders them by sort keys. Primary keys are informational and not enforced, and MERGE performs the upsert of the incremental load.

Block 4 · Load strategies
Full load, incremental load and the watermark
Bronze partitions · ingestion_date silver.sale_line · silver.stock_position sale_line0 inserted0 updated0 silver.load_log   Mode  

 

  1. 1 · full load
  2. 2 · watermark
  3. 3 · new day
  4. 4 · incremental merge
  5. 5 · second run
  6. 6 · same result
Block 4 · Choosing a load strategy
Four ways of writing Silver, each with its risk
StrategyWhat it doesFits whenRisk
Full rebuildcreates the tables again from all of Bronzesmall volumes, a rule changed, or the first loadcost grows with history; must swap atomically so readers 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, like the audits of day − 2, are lost
Watermark

The highest ingestion_date already loaded, kept in load_log. The next run reads only what is after it.

Idempotency

Running the same input twice gives the same Silver. MERGE by key provides it; append does not.

Atomicity

One transaction per run. A failure in the third table leaves the first two as they were.

Block 4 · Numerical example 6 · 1.1 million sale lines
What each load mode cost on the benchmark

Reference pipeline over the benchmark bucket, on the professor's machine, 26/10/2026, DuckDB 2.0.0 and local MinIO. Times are of one run; on S3 the extraction share grows with the latency of each request.

RunPOS rows readExtractTransformLoadTotal
Full, 14 days, empty warehouse1,046,5141.1 s1.0 s3.2 s5.4 s
Incremental, day 26/1074,2350.2 s0.2 s0.3 s0.7 s
Full, 15 days, drop and rebuild1,120,7491.2 s1.0 s3.4 s5.6 s
Full, 15 days, DELETE then MERGE into the full tables1,120,7491.2 s1.0 s32.4 s34.6 s
What the measurement showsThe incremental run costs the size of one day, and the full run the size of the history. Deleting row by row from tables with a primary key costs ten times more than rebuilding them, because each deletion and each merge updates the index of the key. The same index is why sale_line takes 142 MiB with its key and 23 MiB without it, and why columnar warehouses such as ClickHouse and Redshift do not enforce primary keys and leave uniqueness to the ETL.
Block 4 · Designing Silver
Tables of the Silver layer and the checks that protect them

Silver of this session is conformed, close to the shape of the sources, with each table keyed by its grain. Lesson 5 models it in Third Normal Form or Data Vault, and Lesson 6 builds the cubes of Gold on top of it.

Normalisation and denormalisation

sale_line keeps store_id and product_id and leaves names and cities in store and product, which avoids rewriting thousands of rows when a store changes name. It also keeps the derived line_amount and sold_date, a small denormalisation that every query of Gold would otherwise repeat.

Integrity checks · each must return zero rows
-- grain of stock_position
SELECT store_id, product_id, date FROM silver.stock_position
GROUP BY ALL HAVING count(*) > 1;
-- referential integrity of sale_line
SELECT sale_id FROM silver.sale_line l
ANTI JOIN silver.product p USING (product_id);
-- accounting of the last run
SELECT entity FROM silver.load_log WHERE run_id = ?
  AND rows_loaded + rows_quarantined > rows_read;
Consistency for the readerA reader of the warehouse must never see the sale lines of a run without its stock positions. Loading the three tables in one transaction gives that guarantee in DuckDB. In warehouses without multi-table transactions, the same guarantee comes from loading into staging tables and swapping them in one operation.
Block 4 · Pause for reflection
A rule was wrong for ten days

On 05/11 the team discovers that the rule of BAU-05 read dd/mm/yyyy as mm/dd/yyyy since 26/10, so sales of 05/11 were loaded as 11/05. The rule is fixed. The watermark is 05/11, so the next incremental run will not touch the ten wrong days. What should the team run?

Option A

A full load

Rebuild Silver from all of Bronze. How long does it take when the history has two years?

Option B

Move the watermark back

Set it to 25/10 and run the incremental load. Does MERGE by sale_id correct sold_at of rows that already exist?

Option C

A backfill mode

A parameter --from 2026-10-26 that reprocesses a window without moving the watermark. What does the load log record?

And Gold

Downstream

The weekly indicator of those weeks was already published. Who is told, and how does the indicator show that it changed?

Block 4 · Synthesis
Key points of block 4
  1. The lake keeps everything that arrived; the warehouse serves typed tables with constraints and transactions.
  2. The full load rebuilds, the incremental load merges the partitions after the watermark, and both must arrive at the same Silver.
  3. MERGE by the key of the grain makes the load idempotent and absorbs resends and late corrections.
  4. Constraints cost space and load time; columnar warehouses do not enforce keys, so the ETL owns uniqueness and checks it after each run.
Back to the agentRun full, generate 26/10, run incremental twice and full again, and compare the counts with the verification slide.
12:35 · Verification
Prove that the pipeline closes the accounting
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      # nothing after the watermark
python -m src.pipeline full             # same counts as the incremental
python -c "import duckdb; c = duckdb.connect('warehouse/pharmacy.duckdb', read_only=True); \
  print(c.sql('SELECT entity, reason, count(*) FROM silver.quarantine GROUP BY ALL'))"
Table14 days+ 26/10
sale_line20,89122,380
stock_position3,3463,585
delivery258281
quarantine136150
Accountingafter dedup = Silver + quarantine, for each entity and each run.
Idempotencysecond incremental run changes nothing; full and incremental agree.
Privacy and lineageno CPF in any table; every row with its source file and run.
12:42 · Quality attribute scenarios
Six scenarios the pipeline must answer

Each scenario has a stimulus and a measurable response. The group records them in docs/ with the evidence of its own run, as in the ATAM of Lesson 3.

StimulusExpected responseEvidence
a terminal resends a whole dayone row per sale_id, latest delivery kept241 rows of JUN-04 on 17/10, ingested 18/10
an audit corrects the stock of day − 2the older count is replaced, no new rowgrain query returns zero 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 watermark"
the run fails in the third tablethe warehouse stays as before the runtest that raises inside the transaction
a new day of 74,000 lines arrivesloaded in time proportional to one dayincremental time against full time, measured by the group
12:50 · Closing
What must exist at 13:00 and by Lesson 5

The four prompts fit the session if each review is short. What does not fit continues during the week, with the material and the lab script.

In class, by 13:00
  • MinIO local with the Bronze of 14 days
  • specs/ with spec, plan and tasks reviewed
  • src/extract.py and src/transform.py with tests passing
  • first full load with the counts of the verification slide
During the week, by Lesson 5 (05/11)
  • incremental mode, rerun and full again with the same counts
  • ADR-001 comparing full and incremental with the group's numbers
  • the six quality scenarios with evidence
  • the same pipeline pointed at a sample of the partner data
Deliverable in the group repositoryFolder lesson_04_etl/ with AGENTS.md, specs/, src/, tests/ passing and docs/adr/ADR-001-full-and-incremental-load.md. The warehouse file is not committed: anyone rebuilds it with the generator and the full load.
Self-study
Self-study for this session

Five readings and videos assigned on Adalove. They extend the four blocks of the session and prepare the modelling of Silver in Lesson 5.

Self-study 5

RDD Programming Guide

Official Spark guide to resilient distributed datasets. Extends the slide on large volumes.

spark.apache.org· 30 min
Reading material

Lesson 4 material

The four blocks in depth, the four prompts in full, the lab script and the mistakes that agents usually make in this pipeline.

this module

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