Instruction session ยท Thursday, November 5, 2026 ยท 14:00 to 16:00
The orders of Olist, a Brazilian marketplace, enter the platform as raw CSV files and become a Silver layer in two copies: a long-lived lake in RustFS, read with DuckDB, and ClickHouse for tactical queries. The session ends with a star schema built over that Silver layer with views and materialized views, which answers how many sales the North made each month compared with the Southeast. The professor builds it live with a coding agent in four steps.
Project ritual
Each group reports the progress of its deliverables, the work planned for this session and the blockers that require a decision.
The professor sends each prompt to the coding agent. While the agent writes, the slides explain the concept that the step implements, and the step ends with a review against the counts measured in the rehearsal.
src/load_hybrid.pySlides: normalising, aggregating and deriving; the lake firstsrc/reconcile.pySlides: Redshift and ClickHouse, TTL and the clock of the retentionThe Olist dataset, the hybrid architecture, the raw CSV files and the local RustFS and ClickHouse.
The checks that close the lab and how they map to the Data Ingestion Structure artifact of the week.
What each group takes to its own data before Lesson 6, and the self-study.
Olist connects small shops to the large marketplaces of Brazil. Its public dataset has 99,441 orders placed between September 2016 and October 2018, with the customers, sellers, products and items of each order, extracted from the transactional system without any treatment.
How many sales did each region make this month, and how does the North compare with the Southeast? The answer must come in under a second, for a dashboard.
Is the growth of the North seasonal or structural, and which categories drive it? The answer needs every year that the platform has kept, and it may run for hours.
Where did this number come from, and can you rebuild it? The answer needs the source file of each record and proof that no copy was altered.
Every load writes the lake first and then loads ClickHouse from the files it has just written. ClickHouse therefore never holds a row that the lake does not hold, and the star schema of the Gold database is computed from it.
The two copies answer different kinds of question, and each kind needs a different period of history and a different cost per query.
| ClickHouse | Lake in RustFS, read with DuckDB | |
|---|---|---|
| Questions | tactical: sales of the month by region, late deliveries of the week | strategic: seasonality, trends over years, models |
| Users | commercial area, operations, dashboards | analysts, data scientists, auditors |
| Period kept | up to one year, removed by TTL | years and decades, every version |
| Cost profile | server always on, data on fast disk | object storage, compute only when a job runs |
| Typical run | sub-second queries, many per minute | jobs of minutes, hours or days |
| If lost | rebuilt from the lake | the record of the platform; must be protected |
The archive below holds the files of the case without any change. The lab copies it into the Bronze layer, so every defect of the source is still there for the Silver layer to treat.
| File | Bronze entity | Rows | MB |
|---|---|---|---|
olist_orders_dataset.csv | orders | 99,441 | 17.7 |
olist_order_items_dataset.csv | order_items | 112,650 | 15.0 |
olist_customers_dataset.csv | customers | 99,441 | 8.6 |
olist_sellers_dataset.csv | sellers | 3,095 | 0.2 |
olist_products_dataset.csv | products | 32,951 | 2.4 |
product_category_name_translation.csv | product_category_translation | 71 | 0.0 |
olist_order_payments_dataset.csv | payments | 103,886 | 5.6 |
olist_order_reviews_dataset.csv | reviews | 99,224 | 14.5 |
The eight files, the licence and a note on the source. Payments and reviews stay in the Bronze for the groups to explore; the Silver layer of the lab uses the other six.
Source: github.com/olist/work-at-olist-data, MIT licence. The same data is published on Kaggle as Brazilian E-Commerce Public Dataset by Olist. The 61 MB geolocation file is left out because the lab does not use it.
The support files are in lab/lesson-5/ of the module, with the archive of raw data in data/. The folder lesson_05_dw/ starts as a copy of it, and load_bronze.py uploads the eight files to RustFS byte for byte.
git clone --depth 1 https://github.com/afonsolelis/aulas.git cp -r aulas/pages/module-8-sistemas-informacao/lab/lesson-5 ~/lesson_05_dw cd ~/lesson_05_dw cp .env.example .env # passwords changed off screen docker compose up -d --wait # rustfs and clickhouse healthy python3 -m venv .venv && source .venv/bin/activate pip install -r requirements.txt python load_bronze.py # 8 objects in bronze/ echo "@AGENTS.md" > CLAUDE.md && claude
data_ingestao, data_linha, data_tag.data_linha is JSON in ClickHouse, never String.RustFS speaks the S3 API, accepts only path-style addresses and has its console at localhost:9001/rustfs/console/. ClickHouse answers on localhost:8123 and reaches RustFS inside the compose network at rustfs:9000. The archive is already inside the folder; the download button is for studying the files at home.
load_bronze.py counts them at the end of the upload. None of them is planted: they are what a transactional extract without treatment looks like, and each one becomes a rule of the contract in Step 01.
| Defect in the Bronze | Count | Rule of the Silver layer |
|---|---|---|
orders delivered without order_delivered_customer_date | 8 | quarantine, with the 8 items of those orders |
orders delivered without order_approved_at | 14 | kept, with approved_at null |
| zip prefixes with 4 digits, the leading zero lost at the source | 23,995 ยท 1,027 | customers ยท sellers: text padded to 5 characters |
| products without category ยท category without English name | 610 ยท 13 | unknown ยท the Portuguese name as fallback |
headers product_name_lenght, product_description_lenght | 2 | renamed in the contract |
| translation file starting with a UTF-8 byte order mark | 1 | read with the mark removed, or the join finds no column |
| timestamps without offset, local time of a country that had daylight saving time until 2019 | all | ISO 8601 with -03:00 or -02:00 of that date |
Step 01 ยท 14:25 ยท Contract and decision
Before any code, the agent writes what the Silver layer promises: three columns, one tag per kind of record, the layout of the lake and the decision of the two copies, plus the DDL of ClickHouse.
specs/silver_contract.md, docs/adr/ADR-002-hybrid-silver.md and sql/clickhouse_enriched.sql, applied in ClickHouse.
data_ingestao, data_linha and data_tag?zip_prefix a string of 5 characters?SHOW CREATE TABLE show the JSON type and the TTL?[C] Character
You are a senior data architect. You work in the folder lesson_05_dw/,
which holds the Bronze layer of the Olist case (a Brazilian marketplace,
orders from 2016-09 to 2018-10) in a local RustFS, an S3-compatible
object storage, and an empty ClickHouse. In this step you write the
contract of the Silver layer, the decision record and one DDL file; you
do not write Python.
[R] Request
Write three files:
1. specs/silver_contract.md: the enriched table of the Silver layer, with
exactly three columns:
- data_ingestao: date and time at which the record entered the
platform, in America/Sao_Paulo: the ingestion_date partition of the
Bronze object at 00:00. It is not the date of the order.
- data_linha: JSON with the normalised and derived fields of one
record, always including source_file.
- data_tag: 'olist.<entity>.v<N>', or 'quarantine.v1' for rejected
records, whose data_linha holds entity, key, reason and source_file.
Five tags enter the Silver layer: olist.customer.v1, olist.seller.v1,
olist.product.v1, olist.order.v1 and olist.order_item.v1. Payments and
reviews stay in the Bronze. The fields of data_linha, besides
source_file, are:
- customer: customer_id, customer_unique_id, zip_prefix, city, state,
region;
- seller: seller_id, zip_prefix, city, state, region;
- product: product_id, category_pt, category_en, name_length,
description_length, photos_qty, weight_g, length_cm, height_cm,
width_cm;
- order: as in the example below;
- order_item: order_id, order_item_id, product_id, seller_id,
shipping_limit_at, price, freight_value, item_total.
Include a catalogue with one entry per tag (fields, key used for
deduplication, rules) and the layout of the lake:
silver/enriched/data_tag=<tag>/ingestion_date=<D>/data.parquet (Parquet
zstd, the same key is overwritten on a rerun) and
silver/_manifests/run_<run_id>.json (per file: key, data_tag, rows,
bytes, sha256; plus rows per tag, times and status).
2. docs/adr/ADR-002-hybrid-silver.md: every load writes the lake first and
then loads ClickHouse from the files it has just written. The lake is
the source of truth and keeps every version for years, for strategic
analysis and data science read with DuckDB. ClickHouse keeps a short
window for tactical queries and deletes older rows by TTL. Compare
with two alternatives: ClickHouse only, and lake only.
3. sql/clickhouse_enriched.sql: database silver and table silver.enriched
(data_ingestao DateTime64(3, 'America/Sao_Paulo'), data_tag
LowCardinality(String), data_linha JSON), MergeTree, partition by month
of data_ingestao, order by (data_tag, data_ingestao), TTL of 1 year on
data_ingestao. Apply it and show SHOW CREATE TABLE.
Facts measured on 05/11/2026 (confirm before use):
- Bronze: 8 CSV objects under
bronze/source=olist/entity=<e>/ingestion_date=2026-11-05/, written
unchanged by load_bronze.py, which prints the defects of the source.
- Rows in the Bronze: orders 99,441, order_items 112,650, customers
99,441, sellers 3,095, products 32,951, category translation 71.
- Defects: 8 orders 'delivered' without order_delivered_customer_date;
14 orders 'delivered' without order_approved_at (kept, approved_at
null); 23,995 customer and 1,027 seller zip prefixes with 4 digits (the
leading zero was lost at the source); 610 products without category
and 13 whose category has no English translation; headers
product_name_lenght and product_description_lenght misspelt; the
translation file starts with a UTF-8 byte order mark; timestamps
without offset, in local time of Brazil, which had daylight saving
time until 2019.
[E] Example
### olist.order.v1
Source: bronze/source=olist/entity=orders/*/olist_orders_dataset.csv
Key: order_id; keep the latest ingestion_date, then the latest file.
data_linha: order_id, customer_id, order_status, purchased_at,
approved_at, delivered_carrier_at, delivered_customer_at (ISO 8601 with
the offset of America/Sao_Paulo on that date, -03:00 or -02:00),
estimated_delivery_on, customer_state, customer_region, delivery_days,
delivered_late, source_file.
Rules: customer_state and customer_region joined from the customers;
region from the state (North, Northeast, Central-West, Southeast,
South); delivery_days and delivered_late derived.
Quarantine: orphan customer; status 'delivered' without delivery date.
[A] Adjustments
- Keep the three column names exactly as written: data_ingestao,
data_linha, data_tag.
- Read every CSV column as text and convert it explicitly; zip_prefix is
a string of 5 characters, never a number.
- An order item whose order went to quarantine also goes to quarantine,
with the reason 'order in quarantine'. A superseded duplicate of a key
goes to quarantine with the reason 'duplicate key, superseded', so
that every Bronze record ends in exactly one tag.
- data_linha is of type JSON in ClickHouse, never String.
- The retention of 1 year is a business parameter: mark it "hypothesis,
to validate with the partner", and say who decides it.
- No Python in this step.
[T] Type of output
Three files. The contract has the column table, the tag catalogue, the
lake layout and a section "Facts, gaps and assumptions". The ADR has
Context, Decision, Alternatives (table), Consequences and a Mermaid
flowchart Bronze -> enrich -> lake -> ClickHouse.
[E] Extras
Read AGENTS.md first. Show the tag catalogue before writing the files.
Record this prompt in docs/prompts.md. Stop at the end.
Step 01 ยท While the agent works
The agent showed its plan, received the go-ahead and is writing. The next slides explain the concept that the prompt asked for, and the review of the files comes after them.
data_ingestao, data_linha, data_tagRead the tag catalogue against the counts of the Bronze and check that the ADR names who decides the retention.
- data_tag: 'olist.<entity>.v<N>', or 'quarantine.v1' for rejected
records, whose data_linha holds entity, key, reason and source_file.
In the medallion architecture, Silver combines and cleans what arrived in Bronze and offers one corporate view of the core business entities. Inmon defined a Data Warehouse by four properties, and the Silver layer of the lab has each of them.
Organised around orders, items, customers, sellers and products, and not around the tables of the transactional system that produced them.
One format for dates, one for zip prefixes and one name per category for all files. The 23,995 short zip prefixes arrive padded.
Every record carries data_ingestao, so the warehouse can answer what was known at any moment, not only the current state.
Loads add or replace whole files; nobody edits a row by hand. A rerun with the same Bronze gives the same Silver.
Analysts query Silver directly, because the cleaning and the integration were done once, upstream, with rules that are written down.
The star schema of Step 04 is computed from Silver, so an error fixed in Silver is fixed in every fact and every dimension.
The enriched table stores every kind of record in the same three columns. The fixed part is what the platform needs to manage the data, and the variable part travels in JSON.
| Column | Type in ClickHouse | Meaning |
|---|---|---|
data_ingestao | DateTime64(3, 'America/Sao_Paulo') | when the record entered the platform: the partition date of the Bronze object |
data_linha | JSON | the normalised and derived fields of one record, always with source_file |
data_tag | LowCardinality(String) | olist.<entity>.v<N> or quarantine.v1 |
data_ingestao 2026-11-05 00:00:00.000
data_tag olist.order.v1
data_linha {"order_id":"a985d695โฆ",
"order_status":"delivered",
"purchased_at":
"2018-03-14T10:11:04-03:00",
"customer_state":"MG",
"customer_region":"Southeast",
"delivery_days":8,
"delivered_late":false,
"source_file":"s3://โฆ/orders/โฆcsv"}data_ingestao says when the platform received the record, and purchased_at says when the customer bought. The orders are from 2018, but they entered the platform on 05/11/2026; the TTL and the analysis use different dates, and Step 03 measures what that means.JSON lets records of different shapes share one table, and the tag says which shape each record has. Together they absorb new sources and new versions without a change of DDL.
delivery_days Int64, price Float64, purchased_at String.ALTER TABLE.olist.order.v1 names source, entity and version of the contract.olist.order_item.v2.quarantine.v1 keeps rejected records visible, with a reason.| data_tag | Rows expected after Step 02 | Key of deduplication |
|---|---|---|
olist.order.v1 ยท olist.order_item.v1 | 99,433 ยท 112,642 | order_id ยท order_id, order_item_id |
olist.customer.v1 ยท olist.seller.v1 | 99,441 ยท 3,095 | customer_id ยท seller_id |
olist.product.v1 | 32,951 | product_id |
quarantine.v1 | 16 | entity and key |
| total | 347,578 |
Step 02 ยท 14:40 ยท Enrichment and hybrid load
The agent applies the rules of the contract in DuckDB, produces the three columns for every tag, writes one Parquet file per tag and day with its SHA-256, and loads ClickHouse from those files.
src/config.py, src/enrich.py, src/lake.py, src/clickhouse.py, src/load_hybrid.py and tests/test_enrich.py.
purchased_at keep its offset and stay String in ClickHouse?[C] Character
You are the data engineer who implements the hybrid load. You follow
specs/silver_contract.md and docs/adr/ADR-002-hybrid-silver.md, and you
only touch src/ and tests/.
[R] Request
Write:
1. src/config.py: reads .env (names only, never the values).
2. src/enrich.py: DuckDB SQL that reads the Bronze over httpfs and builds
one relation (data_ingestao, data_tag, data_linha) with every tag of
the contract: normalise (text columns, 5-digit zip prefixes, fixed
headers, ISO 8601 timestamps with offset, categories in English with
the Portuguese name as fallback and 'unknown' when empty), aggregate
sources (state and region of the customer into each order), derive
(region, delivery_days, delivered_late, item_total), deduplicate by
the keys of the contract and send rejected records to quarantine.v1
with a reason.
3. src/lake.py: writes one Parquet file per (data_tag, day of
data_ingestao) under silver/enriched/, computes the SHA-256 of the
bytes it uploads and writes the manifest of the run.
4. src/clickhouse.py: truncates silver.enriched and loads it with the
s3() table function of ClickHouse reading the Parquet files of the
lake, never the Bronze.
5. src/load_hybrid.py, run as python -m src.load_hybrid: enrich, write the
lake, load ClickHouse from the lake, write the manifest with status ok.
If ClickHouse fails, write the manifest with status error_clickhouse
and exit with a non-zero code.
6. tests/test_enrich.py with small fixtures in tests/fixtures/, one
example of each defect, without network.
Then run the load and print the rows per data_tag in the lake and in
ClickHouse.
Facts measured on 05/11/2026 (confirm before use):
- Expected Silver: olist.customer.v1 99,441, olist.seller.v1 3,095,
olist.product.v1 32,951, olist.order.v1 99,433, olist.order_item.v1
112,642, quarantine.v1 16 (8 orders and their 8 items). Total 347,578
rows in 6 Parquet files.
- Whole run about 2.5 s on the preparation machine (0.8 s to enrich,
0.8 s to write the lake, 0.9 s to load ClickHouse).
- In ClickHouse the JSON paths keep their types: purchased_at and
zip_prefix stay String, delivery_days Int64, price Float64,
delivered_late Bool.
[E] Example
data_tag: olist.order.v1
data_ingestao: 2026-11-05 00:00:00.000 -03:00
data_linha: {"order_id":"a985d695ba083a66246dd48086ad4cab",
"customer_id":"db9fca3fe54ebcbdb9ccf151ab539a1c",
"order_status":"delivered","purchased_at":"2018-03-14T10:11:04-03:00",
"delivered_customer_at":"2018-03-22T15:28:56-03:00",
"estimated_delivery_on":"2018-04-06","customer_state":"MG",
"customer_region":"Southeast","delivery_days":8,
"delivered_late":false,"source_file":"s3://olist-lake/bronze/
source=olist/entity=orders/ingestion_date=2026-11-05/
olist_orders_dataset.csv", ...}
[A] Adjustments
- Order of the run: lake, then ClickHouse, then the manifest. ClickHouse
never holds a row that the lake does not hold.
- A rerun gives the same result: the lake keys are overwritten and
ClickHouse is rebuilt from the lake.
- Every INSERT uses input_format_try_infer_dates = 0,
input_format_try_infer_datetimes = 0 and async_insert = 0, so that the
timestamps keep their text and offset.
- DuckDB reaches RustFS with URL_STYLE 'path' and USE_SSL false; it
needs the pytz package to hand TIMESTAMPTZ values to Python. In DuckDB
2.0 a relation has no fetchone(): use con.execute(...).fetchone().
- ClickHouse reaches RustFS at S3_ENDPOINT_FROM_CLICKHOUSE, the address
inside the compose network, not at localhost.
- Read the Bronze with hive_partitioning = false and take
ingestion_date as text from the path, so that no column is typed by
the reader.
- pytest runs from the root of the folder: add tests/conftest.py that
puts the root on sys.path, so that the tests can import src.
- Pass the credentials of s3() from .env at run time, never written in
a file, and record in the ADR that they appear in system.query_log of
ClickHouse (a named collection would avoid it).
- Do not use CREATE PERSISTENT SECRET.
[T] Type of output
The six files, the output of pytest -q and of the load, and a table
data_tag | rows in the lake | rows in ClickHouse.
[E] Extras
Show the plan before editing. Record this prompt in docs/prompts.md.
Stop at the end.
Step 02 ยท While the agent works
The agent showed its plan, received the go-ahead and is writing. The next slides explain the concept that the prompt asked for, and the review of the files comes after them.
Compare the table lake against ClickHouse with the expected counts, then open one Parquet file in the console of RustFS.
- Order of the run: lake, then ClickHouse, then the manifest. ClickHouse
never holds a row that the lake does not hold.
Enrichment adds to a record what it needs to be used without returning to its source. In the lab it has three operations, each measured in the Bronze of Olist.
23,995 customer and 1,027 seller zip prefixes padded to 5 characters; every timestamp written in ISO 8601 with its offset; two misspelt headers renamed; 610 empty categories as unknown.
Each order receives customer_state and customer_region from the customers file, and each product receives its category in English from the translation file.
region from the state, delivery_days and delivered_late for every delivered order, and item_total = price + freight for every item.
dim_customer.The order of the run decides what a failure leaves behind. Writing the lake first means that any failure afterwards leaves ClickHouse behind the lake, never ahead of it.
silver/enriched/, with the SHA-256 of its bytes.s3() function reading those files, never the Bronze.ok; if ClickHouse fails, with error_clickhouse.{"run_id": "20261105T135218Z_7f349d",
"status": "ok",
"rows_lake": 347578, "rows_sent_ch": 347578,
"seconds": {"enrich": 0.75, "lake": 0.8,
"clickhouse": 0.85},
"files": [{"key": "silver/enriched/
data_tag=olist.order.v1/
ingestion_date=2026-11-05/data.parquet",
"rows": 99433, "sha256": "โฆ"}, โฆ]}Rehearsal on 05/11/2026 with RustFS 1.0.4, DuckDB 2.0.0 and ClickHouse 26.8.15.10. The counts are the expected result of the step; the times change with the machine.
Every data_linha carries source_file, so any number of a dashboard can be traced to the Bronze object it came from.
The SHA-256 in the manifest is computed on the bytes uploaded. Recomputing it later shows whether a file of the lake was altered.
A second run overwrites the same keys and rebuilds ClickHouse from the lake, arriving at the same 347,578 rows.
Open http://10.8.8.10:8123/play, the copy of the class on the server shrek2, with the user aluno and the password aluno, which can only read. Play runs one statement at a time, so each slide holds one.
SELECT data_tag, count() AS rows FROM silver.enriched GROUP BY data_tag ORDER BY data_tag;
| data_tag | rows |
|---|---|
| olist.customer.v1 | 99,441 |
| olist.order.v1 | 99,433 |
| olist.order_item.v1 | 112,642 |
| olist.product.v1 | 32,951 |
| olist.seller.v1 | 3,095 |
| quarantine.v1 | 16 |
The total is 347,578 rows, the same count that the manifest of the run records for the lake. Opening the address of ClickHouse without a query returns Empty query, which is not an error of the login.
The three columns of the contract appear as they are stored: the ingestion date, the tag and the record in JSON.
SELECT data_ingestao, data_tag, data_linha FROM silver.enriched WHERE data_tag = 'olist.customer.v1' LIMIT 3;
2026-11-05 00:00:00.000 ยท olist.customer.v1 ยท {"city":"osasco", "customer_id":"00012a2cโฆ", "region":"Southeast", "state":"SP", "zip_prefix":"06273", "source_file":"s3://olist-lake/bronze/โฆ"}
The zip_prefix keeps five characters, with the leading zero that the CSV had lost, and source_file points to the Bronze object that produced the record.
A path of the JSON is read with a dot. Its type is Dynamic, which ClickHouse refuses in GROUP BY until it is cast to a concrete type.
SELECT data_linha.customer_region::String AS region,
count() AS orders
FROM silver.enriched
WHERE data_tag = 'olist.order.v1'
GROUP BY region
ORDER BY orders DESC;| region | orders |
|---|---|
| Southeast | 68,259 |
| South | 14,147 |
| Northeast | 9,394 |
| Central-West | 5,782 |
| North | 1,851 |
These are all orders, in any status. The question of Step 04 counts only delivered orders, which is why the North drops to 1,796 there.
Rejected records stay in the table with the tag quarantine.v1, the entity, the key and the reason, so that no line of the source disappears without a trace.
SELECT data_linha.entity::String AS entity,
data_linha.reason::String AS reason,
count() AS records
FROM silver.enriched
WHERE data_tag = 'quarantine.v1'
GROUP BY entity, reason;| entity | reason | records |
|---|---|---|
| orders | delivered without delivery date | 8 |
| order_items | order in quarantine | 8 |
The wording of the reason is the one written by the agent in Step 02 and may differ slightly; the counts, 8 orders and their 8 items, may not.
Step 03 ยท 15:00 ยท Audit and lifecycle
The agent writes the reconciliation of the two copies, shows that a rerun and a rebuild reach the same counts, and measures what the retention would keep if it counted from the date of the order.
src/reconcile.py and the section "Measured consequences" of the ADR.
[C] Character
You are the data engineer responsible for the audit of the Silver layer.
The partner asks two questions before trusting it: can every number be
proved against the lake, and how long will ClickHouse keep the orders?
[R] Request
1. Write src/reconcile.py, run as python -m src.reconcile, which prints
for each data_tag: rows in the lake, rows in the lake inside the
retention window of ClickHouse, rows in ClickHouse and OK or DIFF
(a comparison of counts per tag, not row by row); and
which checks the SHA-256 of every file listed in the last manifest. It
exits with a non-zero code on any DIFF or mismatch.
2. Run python -m src.load_hybrid twice and python -m src.reconcile after
each run, to show that a rerun arrives at the same counts.
3. Drop silver.enriched, recreate it from sql/clickhouse_enriched.sql,
reload it from the lake only with the function of src/clickhouse.py
and time the rebuild.
4. Without changing the table, measure how many orders would remain in
ClickHouse if the TTL counted from purchased_at instead of
data_ingestao.
5. Append to docs/adr/ADR-002-hybrid-silver.md a section "Measured
consequences" with the numbers of this run and the question of which
clock the retention follows, addressed to the owner of the decision.
Facts measured on 05/11/2026 (confirm before use):
- Reconciliation: 6 tags OK, 6 files, 0 SHA-256 mismatches, 0.4 s.
- Rebuild of ClickHouse from the lake: 347,578 rows in about 1 s.
- TTL on data_ingestao keeps every row, because everything was ingested
on 2026-11-05. A TTL on purchased_at would keep 0 of the 99,433
orders, because the newest one is from 2018-10-17.
- SHOW CREATE TABLE writes the TTL as toIntervalYear(1), not as
INTERVAL 1 YEAR.
[E] Example
window of ClickHouse read from the TTL: 1 Year
data_tag lake window clickhouse
olist.order.v1 99433 99433 99433 OK
quarantine.v1 16 16 16 OK
files=6 sha256_mismatches=0
[A] Adjustments
- The window comes from the TTL of the table (read it from ClickHouse),
not from a constant copied into the script.
- A tag with more rows in ClickHouse than in the lake is a DIFF,
whatever the window.
- Bronze stays read-only; load_bronze.py is its only writer.
- Ask before the DROP of step 3.
- Do not change tests to make them pass.
[T] Type of output
The new src/reconcile.py, the output of the two loads, of the
reconciliations and of the rebuild, the count of step 4 and the new
section of the ADR.
[E] Extras
Show the plan before editing. Record this prompt in docs/prompts.md.
Stop at the end.
Step 03 ยท While the agent works
The agent showed its plan, received the go-ahead and is writing. The next slides explain the concept that the prompt asked for, and the review of the files comes after them.
Read the reconciliation table and the count of step 4 of the prompt: the same rows, two possible windows.
- The window comes from the TTL of the table (read it from ClickHouse),
not from a constant copied into the script.
Both store each column separately and compressed, so an analytical query reads only the columns it uses. They differ in how they are operated and paid for.
| Amazon Redshift | ClickHouse | |
|---|---|---|
| Model | managed service of AWS, cluster or serverless | open source server; also offered as a managed cloud |
| Storage | columnar, compressed, distributed across nodes (MPP) | columnar, compressed parts of a MergeTree table |
| Data layout | distribution key and sort key per table | partition key and ordering key per table |
| Lake access | Redshift Spectrum queries Parquet in S3 | s3() table function queries Parquet in S3 |
| Semi-structured | SUPER type with PartiQL | JSON type with typed subcolumns |
| Materialized views | refreshed manually, on a schedule or automatically | incremental (on insert) or refreshable (on a schedule) |
| Retention | jobs that delete or unload old data | TTL clause applied by the server during merges |
The architecture does not depend on the product: the lake stays the source of truth, and the columnar engine is the fast copy that can be replaced or rebuilt. In this lab ClickHouse plays the role that Redshift would play in an AWS stack.
Each insert writes an immutable part on disk. Background merges join parts of the same partition, and the TTL clause tells the server which rows to drop while it merges.
CREATE TABLE silver.enriched
(
data_ingestao DateTime64(3, 'America/Sao_Paulo'),
data_tag LowCardinality(String),
data_linha JSON
)
ENGINE = MergeTree
PARTITION BY toYYYYMM(data_ingestao) -- one month per partition
ORDER BY (data_tag, data_ingestao) -- filter by tag first
TTL toDateTime(data_ingestao) + INTERVAL 1 YEAR;PARTITION BY month: a whole month expires as one unit, which makes deletion cheap.ORDER BY tag and time: a query of one tag reads a contiguous range.LowCardinality: six tag values stored as a dictionary.TTL: the server stores it as toIntervalYear(1), so a script that searches for the text INTERVAL 1 YEAR finds nothing.The TTL is one line of SQL, but the number in it carries obligations. Engineering informs the decision with cost and speed; the business makes it, and the ADR records it.
Tax records set periods that sales must be kept, and the LGPD limits how long personal data may be kept. customer_unique_id, the city and the zip prefix identify a customer indirectly, so they are personal data.
The commercial area compares months; a plan for a new region compares years. A window of one year serves the first and leaves the second to the lake.
ClickHouse keeps its data on servers that are always on; the lake keeps Parquet in object storage and pays for compute only when a job runs.
The same table, with the same rows, keeps everything or nothing depending on the date that the TTL counts from. The choice belongs to the owner of the decision, and the ADR must state it.
Every record entered the platform on 05/11/2026, so a window of one year keeps the whole history of 2016 to 2018 until November 2027. The window measures how recent the delivery is, not how recent the sale is.
The newest order is from 17/10/2018. A window of one year counted from the purchase would leave ClickHouse empty, and every question of the case would have to go to the lake.
The window is read from the TTL of the table, and every tag is compared inside it. Two loads in a row and a rebuild from the lake reach the same counts.
| data_tag | Lake | Lake in window | ClickHouse | Status |
|---|---|---|---|---|
olist.customer.v1 | 99,441 | 99,441 | 99,441 | OK |
olist.order.v1 | 99,433 | 99,433 | 99,433 | OK |
olist.order_item.v1 | 112,642 | 112,642 | 112,642 | OK |
olist.product.v1 | 32,951 | 32,951 | 32,951 | OK |
olist.seller.v1 | 3,095 | 3,095 | 3,095 | OK |
quarantine.v1 | 16 | 16 | 16 | OK |
| total | 347,578 | 347,578 | 347,578 | 6 files ยท 0 SHA-256 mismatches |
Step 04 ยท 15:15 ยท Star schema
The enriched table records what arrived. The commercial area needs a model of the business: the agent designs a star schema, builds it in ClickHouse from the Silver layer with views and materialized views, and checks the answer against the lake.
docs/star_model.md, sql/star_clickhouse.sql, sql/star_duckdb.sql and sql/question.sql.
uniqExact(order_id)?[C] Character
You are a dimensional modeller. The enriched table records what arrived;
the commercial area of Olist needs a model that answers its questions.
You design a star schema, build it in ClickHouse from silver.enriched
with views and materialized views, and build the same star in DuckDB
over the lake to check the answer.
[R] Request
1. docs/star_model.md: the business question "How many sales were made
each month in the North, compared with the Southeast?", the
definition of a sale (a delivered order, counted once, in the month of
purchased_at, in the region of the customer), the grain of the fact
(one order item), the dimensions and a Mermaid ER diagram of the star.
2. sql/star_clickhouse.sql, database gold:
- views dim_customer, dim_seller and dim_product over
silver.enriched, one per tag, with typed columns;
- view dim_date (date_key yyyymmdd, date, month 'YYYY-MM', quarter,
year, weekday) generated with numbers(), from 2016-01-01 for 1,096
days;
- refreshable materialized view fact_order_item (REFRESH EVERY
1 HOUR, MergeTree): one row per order item, with order_id,
order_item_id, date_key, customer_id, seller_id, product_id,
order_status, price and freight_value, joining the tags
olist.order_item.v1 and olist.order.v1;
- refreshable materialized view agg_sales_month_region (DEPENDS ON
gold.fact_order_item): month, region, orders (distinct order_id),
items and revenue (sum of price, without freight) of the delivered
orders.
3. sql/star_duckdb.sql: views enriched (read_parquet of the lake),
dim_customer, dim_date and fact_order_item in WAREHOUSE_PATH.
4. sql/question.sql: the question answered from agg_sales_month_region,
one row per month with north, southeast and north as a percentage of
southeast. Run it, run the same question from fact_order_item and
from DuckDB over the lake, and compare the three answers and times.
Facts measured on 05/11/2026 (confirm before use):
- dim_customer 99,441, dim_seller 3,095, dim_product 32,951, dim_date
1,096; fact_order_item 112,642; agg_sales_month_region 107 rows.
- 96,470 delivered orders; North 1,796, Southeast 66,193. Example
months: 2017-11 North 124, Southeast 5,000; 2018-01 North 135,
Southeast 4,816; 2018-08 North 73, Southeast 4,690.
- Times: 0.002 s from the aggregate, 0.06 s from the fact with the
joins, 0.5 s in DuckDB over the lake; the three answers are equal.
- SYSTEM REFRESH VIEW gold.fact_order_item does not refresh the
aggregate: DEPENDS ON orders only the scheduled refreshes.
[E] Example
CREATE OR REPLACE VIEW gold.dim_customer AS
SELECT data_linha.customer_id::String AS customer_id,
data_linha.city::String AS city,
data_linha.state::String AS state,
data_linha.region::String AS region
FROM silver.enriched
WHERE data_tag = 'olist.customer.v1';
[A] Adjustments
- Dimensions are views; only the fact and the aggregate are stored.
- Parse purchased_at with its offset (parseDateTime64BestEffort with
'America/Sao_Paulo'), so that the month is the month in Brazil.
- A sale is counted with uniqExact(order_id), never with count() of
items.
- The percentage returns NULL when the Southeast has no sales in the
month, never inf or nan.
- The duckdb command line is not installed: run sql/star_duckdb.sql and
the DuckDB question from Python, with the secret of RustFS created in
the session.
- After each load, refresh fact_order_item, wait for it, then refresh
agg_sales_month_region (SYSTEM REFRESH VIEW and SYSTEM WAIT VIEW).
- Mermaid without semicolons in labels.
[T] Type of output
The four files, the rows of every object of gold, the result of the
question and a table source | north | southeast | seconds for the three
ways of answering it.
[E] Extras
Show the plan before editing. Record this prompt in docs/prompts.md.
Stop at the end.
Step 04 ยท While the agent works
The agent showed its plan, received the go-ahead and is writing. The next slides explain the concept that the prompt asked for, and the review of the files comes after them.
Check the rows of every object of gold, then read the answer month by month.
- A sale is counted with uniqExact(order_id), never with count() of
items.
Kimball designs a model from a business process and a question, not from the tables of the source. Each decision constrains the next, and the grain is the one that is hardest to change later.
The process measured is the sale of the marketplace: an order placed by a customer, with one or more items from one or more sellers.
Each row of the fact is one item of one order. A finer grain answers more questions; this one still lets an order be counted once with a distinct count.
Customer, seller, product and date describe the context of each item. Region and state live in the dimension, once per customer.
price and freight_value add across any dimension. A count of orders does not: it must be distinct, because one order has several items.
One fact in the centre and four dimensions around it, all in the database gold of ClickHouse. The numbers are the rows measured in the rehearsal.
Each dimension reads one tag of silver.enriched and turns JSON paths into typed columns. The fact joins two tags, items and orders, and takes the date of the purchase in the time zone of Brazil.
CREATE OR REPLACE VIEW gold.dim_customer AS
SELECT data_linha.customer_id::String AS customer_id,
data_linha.city::String AS city,
data_linha.state::String AS state,
data_linha.region::String AS region
FROM silver.enriched
WHERE data_tag = 'olist.customer.v1';SELECT i.order_id, i.order_item_id,
toUInt32(toYYYYMMDD(o.purchased_at)) AS date_key,
o.customer_id, i.seller_id, i.product_id,
o.order_status, i.price, i.freight_value
FROM (โฆ WHERE data_tag = 'olist.order_item.v1') AS i
JOIN (SELECT โฆ, parseDateTime64BestEffort(
data_linha.purchased_at::String, 0,
'America/Sao_Paulo') AS purchased_at
โฆ WHERE data_tag = 'olist.order.v1') AS o
ON i.order_id = o.order_idThe filter by tag goes inside each subquery. Parsing purchased_at over the whole table fails on the rows of other tags, where the path is empty, which the rehearsal met as a CANNOT_PARSE_DATETIME error.
A view stores a query; a materialized view stores a result. ClickHouse offers two kinds of materialized view, and only one of them fits a fact that joins two tags of a table that every load truncates.
| View | Incremental materialized view | Refreshable materialized view | |
|---|---|---|---|
| Stores | only the query | a table, fed on every insert | a table, recomputed on a schedule |
| When it runs | at each query | on each block inserted into one source table | REFRESH EVERY 1 HOUR, or SYSTEM REFRESH VIEW |
| Joins | any | only inserts into the left table fire it | any; the whole query runs again |
| Truncate and reload | no effect | does not remove what was computed | next refresh replaces the result atomically |
| In the star | the four dimensions | not used | fact_order_item and agg_sales_month_region |
agg_sales_month_region is declared with DEPENDS ON gold.fact_order_item, but a manual SYSTEM REFRESH VIEW of the fact does not refresh the aggregate: the dependency orders only the scheduled refreshes. After a load, refresh the fact, wait for it, then refresh the aggregate.The aggregate keeps one row per month and region of the customer, 107 rows in all. It answers the dashboard without touching the 112,642 rows of the fact, and it is valid because each order belongs to one month and one region.
CREATE MATERIALIZED VIEW gold.agg_sales_month_region
REFRESH EVERY 1 HOUR DEPENDS ON gold.fact_order_item
ENGINE = MergeTree ORDER BY (month, region)
AS
SELECT d.month, c.region,
uniqExact(f.order_id) AS orders,
count() AS items,
sum(f.price) AS revenue
FROM gold.fact_order_item AS f
JOIN gold.dim_customer AS c USING (customer_id)
JOIN gold.dim_date AS d USING (date_key)
WHERE f.order_status = 'delivered'
GROUP BY d.month, c.region;-- How many sales were made each month in the -- North, compared with the Southeast? SELECT month, sumIf(orders, region = 'North') AS north, sumIf(orders, region = 'Southeast') AS southeast, if(southeast = 0, NULL, round(100 * north / southeast, 2)) AS north_pct_of_southeast FROM gold.agg_sales_month_region WHERE region IN ('North', 'Southeast') GROUP BY month ORDER BY month;
Summing orders across months or regions is correct, because no order is in two cells. Summing it across products would count an order with items of two categories twice; for that question the distinct count must run on the fact.
Delivered orders by month of purchase and region of the customer. The North made 1,796 sales and the Southeast 66,193, so the North is 2.71 % of the Southeast over the whole period.
| Month | North | Southeast | North / SE % |
|---|---|---|---|
| 2016-09 | 0 | 1 | 0.00 |
| 2016-10 | 5 | 172 | 2.91 |
| 2017-01 | 17 | 485 | 3.51 |
| 2017-02 | 55 | 1,103 | 4.99 |
| 2017-03 | 70 | 1,726 | 4.06 |
| 2017-04 | 76 | 1,509 | 5.04 |
| 2017-05 | 82 | 2,331 | 3.52 |
| 2017-06 | 64 | 2,118 | 3.02 |
| 2017-07 | 59 | 2,606 | 2.26 |
| 2017-08 | 98 | 2,755 | 3.56 |
| 2017-09 | 90 | 2,753 | 3.27 |
| Month | North | Southeast | North / SE % |
|---|---|---|---|
| 2017-10 | 92 | 3,019 | 3.05 |
| 2017-11 | 124 | 5,000 | 2.48 |
| 2017-12 | 98 | 3,818 | 2.57 |
| 2018-01 | 135 | 4,816 | 2.80 |
| 2018-02 | 106 | 4,450 | 2.38 |
| 2018-03 | 120 | 4,824 | 2.49 |
| 2018-04 | 113 | 4,727 | 2.39 |
| 2018-05 | 91 | 4,837 | 1.88 |
| 2018-06 | 100 | 4,279 | 2.34 |
| 2018-07 | 128 | 4,174 | 3.07 |
| 2018-08 | 73 | 4,690 | 1.56 |
November and December of 2016 have no delivered orders in these two regions. The share of the North is highest in February and April of 2017, near 5 %, and falls below 2 % in May and August of 2018, while the Southeast grows faster.
The agent answered the question from the aggregate, from the fact with its joins, and from DuckDB over the lake. The three answers are identical, which checks the star against the source of truth.
| Source of the answer | North | Southeast | Seconds | Who uses it |
|---|---|---|---|---|
gold.agg_sales_month_region ยท ClickHouse | 1,796 | 66,193 | 0.002 | the dashboard of the commercial area |
gold.fact_order_item with the dimensions ยท ClickHouse | 1,796 | 66,193 | 0.06 | an analyst who needs another cut |
| star views in DuckDB over the Parquet of the lake | 1,796 | 66,193 | 0.47 | data science and the audit |
delivered orders in the star: the 96,478 of the source minus the 8 in quarantine.
Southeast 66,193, South 13,813, Northeast 9,044, Central-West 5,624 and North 1,796.
The aggregate is as recent as its last refresh; a load is complete only after the star is refreshed.
Every object of the star lives in a database of its own, so that Silver and Gold can be read, granted and dropped separately. On shrek2 the professor creates the objects, and the user aluno runs the queries of the charts.
CREATE DATABASE IF NOT EXISTS gold;
Ok. and no rows, because a CREATE returns nothing.
Run it once; the next slides create the dimensions, the fact, the aggregate and the report tables inside it.
From here on the statements build the star of Step 04 by hand, in the order of the dependencies: dimensions, fact, aggregate and reports.
A view stores only its query, so the dimension is computed from silver.enriched at each use and never falls out of date.
CREATE OR REPLACE VIEW gold.dim_customer AS
SELECT data_linha.customer_id::String AS customer_id,
data_linha.customer_unique_id::String AS customer_unique_id,
data_linha.zip_prefix::String AS zip_prefix,
data_linha.city::String AS city,
data_linha.state::String AS state,
data_linha.region::String AS region
FROM silver.enriched
WHERE data_tag = 'olist.customer.v1';Ok. and no rows, because a CREATE returns nothing.
Check with SELECT count() FROM gold.dim_customer: 99,441 rows.
The region is kept here once per customer; the fact refers to it through customer_id.
The seller has its own region, which the report of the flow between regions compares with the region of the customer.
CREATE OR REPLACE VIEW gold.dim_seller AS
SELECT data_linha.seller_id::String AS seller_id,
data_linha.zip_prefix::String AS zip_prefix,
data_linha.city::String AS city,
data_linha.state::String AS state,
data_linha.region::String AS region
FROM silver.enriched
WHERE data_tag = 'olist.seller.v1';Ok. and no rows, because a CREATE returns nothing.
Check with SELECT count() FROM gold.dim_seller: 3,095 rows.
Two dimensions read the same five regions from different tags, which is why the region was derived once, in the Silver layer.
The category comes in English from the Silver layer; the 610 products without category arrive as unknown.
CREATE OR REPLACE VIEW gold.dim_product AS
SELECT data_linha.product_id::String AS product_id,
data_linha.category_en::String AS category,
data_linha.weight_g::Nullable(Int64) AS weight_g
FROM silver.enriched
WHERE data_tag = 'olist.product.v1';Ok. and no rows, because a CREATE returns nothing.
Check with SELECT count() FROM gold.dim_product: 32,951 rows.
The weight is Nullable because a few products of the source have no measures.
The calendar does not come from the source: it is generated, one row per day, so that a month without sales still exists as a row.
CREATE OR REPLACE VIEW gold.dim_date AS
SELECT toUInt32(toYYYYMMDD(d)) AS date_key,
d AS date,
formatDateTime(d, '%Y-%m') AS month,
toQuarter(d) AS quarter,
toYear(d) AS year,
toDayOfWeek(d) AS weekday
FROM (SELECT toDate('2016-01-01') + number AS d
FROM numbers(1096));Ok. and no rows, because a CREATE returns nothing.
Check with SELECT count() FROM gold.dim_date: 1,096 days, from 2016-01-01 to 2018-12-31.
The key date_key is the date written as a number, such as 20180115, which the fact computes from purchased_at.
The fact is a refreshable materialized view: a table that ClickHouse fills as soon as it is created and recomputes every hour.
CREATE MATERIALIZED VIEW IF NOT EXISTS gold.fact_order_item
REFRESH EVERY 1 HOUR
ENGINE = MergeTree ORDER BY (date_key, order_id, order_item_id)
AS
SELECT i.order_id, i.order_item_id,
toUInt32(toYYYYMMDD(o.purchased_at)) AS date_key,
o.customer_id, i.seller_id, i.product_id,
o.order_status, i.price, i.freight_value
FROM (SELECT data_linha.order_id::String AS order_id,
data_linha.order_item_id::UInt16 AS order_item_id,
data_linha.seller_id::String AS seller_id,
data_linha.product_id::String AS product_id,
toDecimal64(data_linha.price::Float64, 2) AS price,
toDecimal64(data_linha.freight_value::Float64, 2) AS freight_value
FROM silver.enriched WHERE data_tag = 'olist.order_item.v1') AS i
INNER JOIN
(SELECT data_linha.order_id::String AS order_id,
data_linha.customer_id::String AS customer_id,
data_linha.order_status::String AS order_status,
parseDateTime64BestEffort(data_linha.purchased_at::String,
0, 'America/Sao_Paulo') AS purchased_at
FROM silver.enriched WHERE data_tag = 'olist.order.v1') AS o
ON i.order_id = o.order_id;Ok. and no rows, because a CREATE returns nothing.
Check with SELECT count() FROM gold.fact_order_item: 112,642 items.
Each subquery filters its tag before parsing, because the paths of an order do not exist in the rows of the other tags.
The aggregate answers the question of the business with 107 rows. It depends on the fact, so its scheduled refresh runs after the refresh of the fact.
CREATE MATERIALIZED VIEW IF NOT EXISTS gold.agg_sales_month_region
REFRESH EVERY 1 HOUR DEPENDS ON gold.fact_order_item
ENGINE = MergeTree ORDER BY (month, region)
AS
SELECT d.month AS month, c.region AS region,
uniqExact(f.order_id) AS orders,
count() AS items,
sum(f.price) AS revenue
FROM gold.fact_order_item AS f
INNER JOIN gold.dim_customer AS c ON f.customer_id = c.customer_id
INNER JOIN gold.dim_date AS d ON f.date_key = d.date_key
WHERE f.order_status = 'delivered'
GROUP BY month, region;Ok. and no rows, because a CREATE returns nothing.
Check with SELECT count() FROM gold.agg_sales_month_region: 107 rows. If it returns 0, the aggregate ran before the fact was ready: run SYSTEM REFRESH VIEW gold.agg_sales_month_region and count again.
After a new load of the Silver layer, run SYSTEM REFRESH VIEW and SYSTEM WAIT VIEW on the fact first and on the aggregate next: a manual refresh does not cascade.
This is the question of the session, answered from the aggregate in a few milliseconds.
SELECT month,
sumIf(orders, region = 'North') AS north,
sumIf(orders, region = 'Southeast') AS southeast,
if(southeast = 0, NULL,
round(100 * north / southeast, 2)) AS north_pct_of_southeast
FROM gold.agg_sales_month_region
WHERE region IN ('North', 'Southeast')
GROUP BY month
ORDER BY month;| month | north | southeast | % |
|---|---|---|---|
| 2017-11 | 124 | 5,000 | 2.48 |
| 2018-01 | 135 | 4,816 | 2.80 |
| 2018-05 | 91 | 4,837 | 1.88 |
| 2018-08 | 73 | 4,690 | 1.56 |
| total | 1,796 | 66,193 | 2.71 |
The query returns 22 months. The guard against a division by zero matters in 2016-09, when the Southeast had a single delivered order and the North none.
Each report is one more materialized view over the star, with one row per point of a chart, so the dashboard reads tens of rows instead of the 112,642 of the fact.
CREATE MATERIALIZED VIEW IF NOT EXISTS gold.rpt_kpi_month
REFRESH EVERY 1 HOUR DEPENDS ON gold.fact_order_item
ENGINE = MergeTree ORDER BY month
AS
SELECT d.month AS month,
uniqExact(f.order_id) AS orders,
uniqExact(f.customer_id) AS customers,
uniqExact(f.seller_id) AS sellers,
sum(f.price) AS revenue,
round(sum(f.price) / uniqExact(f.order_id), 2) AS avg_ticket
FROM gold.fact_order_item AS f
INNER JOIN gold.dim_date AS d ON f.date_key = d.date_key
WHERE f.order_status = 'delivered'
GROUP BY month;Ok. and no rows, because a CREATE returns nothing.
Check with SELECT count() FROM gold.rpt_kpi_month: 23 months.
The average ticket divides the revenue by the distinct orders, not by the items, because an order with three items is one purchase.
The data of a line chart: one row per month, read in milliseconds.
SELECT month, orders, revenue, avg_ticket FROM gold.rpt_kpi_month ORDER BY month;
| month | orders | revenue | ticket |
|---|---|---|---|
| 2017-01 | 750 | 111,797.92 | 149.06 |
| 2017-11 | 7,288 | 987,643.58 | 135.51 |
| 2018-05 | 6,749 | 977,539.82 | 144.84 |
| total | 96,470 | 13,220,181.73 |
The best month is 2017-11, with 7,288 delivered orders. The first months of 2016 have one or two orders and show how the marketplace started.
The category comes from dim_product, so the report joins the fact to two dimensions.
CREATE MATERIALIZED VIEW IF NOT EXISTS gold.rpt_revenue_month_category
REFRESH EVERY 1 HOUR DEPENDS ON gold.fact_order_item
ENGINE = MergeTree ORDER BY (month, category)
AS
SELECT d.month AS month, p.category AS category,
uniqExact(f.order_id) AS orders,
count() AS items,
sum(f.price) AS revenue,
sum(f.freight_value) AS freight
FROM gold.fact_order_item AS f
INNER JOIN gold.dim_product AS p ON f.product_id = p.product_id
INNER JOIN gold.dim_date AS d ON f.date_key = d.date_key
WHERE f.order_status = 'delivered'
GROUP BY month, category;Ok. and no rows, because a CREATE returns nothing.
Check with SELECT count() FROM gold.rpt_revenue_month_category: 1,273 rows.
Summing revenue across months is correct. Summing orders across categories is not, because an order with items of two categories appears in both.
The data of a bar chart, summed over the months of the report table.
SELECT category,
sum(revenue) AS revenue,
sum(orders) AS orders
FROM gold.rpt_revenue_month_category
GROUP BY category
ORDER BY revenue DESC
LIMIT 10;| category | revenue | orders |
|---|---|---|
| health_beauty | 1,233,124.14 | 8,647 |
| watches_gifts | 1,165,897.51 | 5,493 |
| bed_bath_table | 1,023,428.73 | 9,272 |
| sports_leisure | 954,669.33 | 7,529 |
| computers_accessories | 888,609.43 | 6,529 |
The table shows the first five of the ten. Watches sell fewer orders than bed and bath but more revenue, because the ticket is higher.
The report crosses the region of the seller with the region of the customer, which needs both dimensions at once.
CREATE MATERIALIZED VIEW IF NOT EXISTS gold.rpt_region_flow
REFRESH EVERY 1 HOUR DEPENDS ON gold.fact_order_item
ENGINE = MergeTree ORDER BY (seller_region, customer_region)
AS
SELECT s.region AS seller_region,
c.region AS customer_region,
uniqExact(f.order_id) AS orders,
sum(f.price) AS revenue,
round(avg(f.freight_value), 2) AS avg_freight
FROM gold.fact_order_item AS f
INNER JOIN gold.dim_seller AS s ON f.seller_id = s.seller_id
INNER JOIN gold.dim_customer AS c ON f.customer_id = c.customer_id
WHERE f.order_status = 'delivered'
GROUP BY seller_region, customer_region;Ok. and no rows, because a CREATE returns nothing.
Check with SELECT count() FROM gold.rpt_region_flow: 23 pairs of regions.
This is the question that the star answers and the enriched table does not: the order of the Silver layer carries the region of the customer, not of the seller.
The data of a matrix or a stacked bar: where the orders of the North came from and what the freight cost.
SELECT seller_region, orders, avg_freight FROM gold.rpt_region_flow WHERE customer_region = 'North' ORDER BY orders DESC;
| seller_region | orders | avg_freight |
|---|---|---|
| Southeast | 1,509 | 35.49 |
| South | 203 | 46.86 |
| Northeast | 45 | 44.74 |
| Central-West | 43 | 27.29 |
Of the orders of the North, 83.8 % came from sellers of the Southeast. The rows add up to 1,800, not 1,796, because an order with sellers of two regions appears in both rows.
Open http://10.8.8.10:8123/play and fill in the user aluno and the password aluno at the top right. The user reads silver and gold and creates objects only in the database lab.
SELECT count() AS rows FROM silver.enriched;
| rows |
|---|
| 347,578 |
Every object of the group is named with its number, as in lab.g01_โฆ: replace g01 with the number of your group in every statement that follows, because all groups share the same database.
JSONExtractString(data_linha, 'state') reads one key of the JSON and returns it as text. There are versions for each type: JSONExtractUInt, JSONExtractFloat, JSONExtractBool.
CREATE OR REPLACE VIEW lab.g01_dim_customer AS
SELECT JSONExtractString(data_linha, 'customer_id') AS customer_id,
JSONExtractString(data_linha, 'city') AS city,
JSONExtractString(data_linha, 'state') AS state,
JSONExtractString(data_linha, 'region') AS region
FROM silver.enriched
WHERE data_tag = 'olist.customer.v1';Ok. and no rows, because a CREATE returns nothing.
Check with SELECT count() FROM lab.g01_dim_customer: 99,441 customers.
A normal view stores only the query. Each time someone reads it, ClickHouse runs the query again over silver.enriched, so the view is always current and costs the full computation at every use.
The fact joins the items to their orders, one row per order item. As a refreshable materialized view, ClickHouse computes it once, stores the result and recomputes it every hour.
CREATE MATERIALIZED VIEW IF NOT EXISTS lab.g01_fact_order_item
REFRESH EVERY 1 HOUR
ENGINE = MergeTree ORDER BY (order_id, order_item_id)
AS
SELECT i.order_id, i.order_item_id, o.customer_id, i.seller_id,
i.product_id, o.order_status, o.purchased_at,
i.price, i.freight_value
FROM (SELECT JSONExtractString(data_linha, 'order_id') AS order_id,
JSONExtractUInt(data_linha, 'order_item_id') AS order_item_id,
JSONExtractString(data_linha, 'seller_id') AS seller_id,
JSONExtractString(data_linha, 'product_id') AS product_id,
JSONExtractFloat(data_linha, 'price') AS price,
JSONExtractFloat(data_linha, 'freight_value') AS freight_value
FROM silver.enriched WHERE data_tag = 'olist.order_item.v1') AS i
INNER JOIN
(SELECT JSONExtractString(data_linha, 'order_id') AS order_id,
JSONExtractString(data_linha, 'customer_id') AS customer_id,
JSONExtractString(data_linha, 'order_status') AS order_status,
parseDateTimeBestEffort(JSONExtractString(data_linha, 'purchased_at'),
'America/Sao_Paulo') AS purchased_at
FROM silver.enriched WHERE data_tag = 'olist.order.v1') AS o
ON i.order_id = o.order_id;Ok. and no rows, because a CREATE returns nothing.
Check with SELECT count() FROM lab.g01_fact_order_item: 112,642 items.
Each subquery filters its tag before extracting the keys, because a key of an order does not exist in the rows of a customer or a product.
The report answers how many delivered orders and how much revenue each state of the customer had. First as a normal view, which stores only the query.
CREATE OR REPLACE VIEW lab.g01_v_sales_state AS
SELECT c.state AS state,
uniqExact(f.order_id) AS orders,
round(sum(f.price), 2) AS revenue
FROM lab.g01_fact_order_item AS f
INNER JOIN lab.g01_dim_customer AS c ON f.customer_id = c.customer_id
WHERE f.order_status = 'delivered'
GROUP BY state;Ok. and no rows, because a CREATE returns nothing.
Nothing is computed yet: the view runs only when it is read.
The same query will now be created a second time, as a materialized view, so that the two can be compared.
The query is identical. The difference is in the first two lines: REFRESH EVERY 1 HOUR and an engine to store the result.
CREATE MATERIALIZED VIEW IF NOT EXISTS lab.g01_mv_sales_state
REFRESH EVERY 1 HOUR
ENGINE = MergeTree ORDER BY state
AS
SELECT c.state AS state,
uniqExact(f.order_id) AS orders,
round(sum(f.price), 2) AS revenue
FROM lab.g01_fact_order_item AS f
INNER JOIN lab.g01_dim_customer AS c ON f.customer_id = c.customer_id
WHERE f.order_status = 'delivered'
GROUP BY state;Ok. and no rows, because a CREATE returns nothing.
ClickHouse computes the 27 states as soon as the view is created and keeps them in a table of its own.
A materialized view of ClickHouse can also be incremental, fed on each insert into one source table; with joins and a table that is reloaded, the refreshable kind is the safe choice.
Run the report from the normal view and look at the line under the result in Play, which shows the time and the rows read.
SELECT state, orders, revenue FROM lab.g01_v_sales_state ORDER BY revenue DESC LIMIT 10;
| state | orders | revenue |
|---|---|---|
| SP | 40,494 | 5,066,562.98 |
| RJ | 12,350 | 1,759,651.13 |
| MG | 11,354 | 1,552,481.83 |
| โฆ | ||
| time | โ 0.18 s | 219,138 rows read |
To answer, ClickHouse read the fact and the customers again and grouped them, the whole computation for ten rows of result.
Run the same report from the materialized view and compare the line under the result with the previous one.
SELECT state, orders, revenue FROM lab.g01_mv_sales_state ORDER BY revenue DESC LIMIT 10;
| state | orders | revenue |
|---|---|---|
| SP | 40,494 | 5,066,562.98 |
| RJ | 12,350 | 1,759,651.13 |
| MG | 11,354 | 1,552,481.83 |
| โฆ | ||
| time | โ 0.005 s | 54 rows read |
The rows are the same, read about 35 times faster, because the result was already stored. The price is freshness: after a new load of the Silver layer, the materialized view shows the old numbers until SYSTEM REFRESH VIEW lab.g01_mv_sales_state, while the normal view is current at once.
The catalogue of ClickHouse shows what each object keeps: a view has no rows of its own, a materialized view has a table behind it.
SELECT name, engine, total_rows, total_bytes FROM system.tables WHERE database = 'lab' AND name LIKE 'g01_%' ORDER BY name;
| name | engine | total_rows |
|---|---|---|
| g01_dim_customer | View | NULL |
| g01_fact_order_item | MaterializedView | 112,642 |
| g01_mv_sales_state | MaterializedView | 27 |
| g01_v_sales_state | View | NULL |
Use a normal view when the result must always be current or is read rarely, as in the dimensions; use a materialized view when the result is read often and can wait for the next refresh, as in the fact and the tables of a dashboard.
Each group chooses one question of the business, builds its own dimension, fact and report in lab with the prefix of the group, once as a view and once as a materialized view, and writes the query of the chart.
Which region of the customer has the highest share of late orders? The order carries delivered_late (Bool) and delivery_days (Int) in olist.order.v1.
In which categories does the freight weigh most against the price? The item carries freight_value, and the product carries category_en in olist.product.v1.
Do sellers of one region sell more to their own region? The seller carries region in olist.seller.v1, and the customer carries it in olist.customer.v1.
Deliver the statements in the order they were run, the result of the chart query and one sentence on why the report was kept as a view or as a materialized view. Objects of other groups must not be dropped; DROP works only inside lab.
Each check has a command and an expected result. The professor runs them on the projector; the groups will run the same checks on their own data.
| Check | Command | Expected |
|---|---|---|
| every record ends in one tag | python -m src.load_hybrid | 347,578 rows; 16 in quarantine |
| lake and ClickHouse agree | python -m src.reconcile | OK for every tag inside the window |
| no file of the lake was altered | same command | 0 SHA-256 mismatches |
| ClickHouse is rebuildable | drop and reload from the lake | same counts, about 1 s |
| the star is complete | SELECT count() FROM gold.fact_order_item | 112,642 items; 107 rows in the aggregate |
| the star is fresh | system.view_refreshes | last success after the last load |
| the answer is consistent | sql/question.sql and DuckDB | North 1,796 ยท Southeast 66,193 in both |
The artifact asks each group for an ETL from Object Storage into an OLAP database, documented in Data_Ingestion.md, with a UML component diagram from data collection to the DataAPP. The lab gives a pattern for each criterion.
| Criterion on Adalove | What the lab showed | What the group adapts |
|---|---|---|
| efficient and appropriate extraction | DuckDB reads the Bronze over httpfs, every column as text | the formats and partitions of the partner data |
| transformations ensuring quality | normalise, aggregate, derive, quarantine with reason | the defects measured in the partner data |
| correct loading into the OLAP database | lake first, ClickHouse from the lake, reconciliation, star refreshed | the OLAP engine and the window agreed with the partner |
| clear UML component diagram | Bronze, enrich, lake, ClickHouse, star | add the DataAPP and the sources of the partner |
| detailed documentation | contract, ADR-002, star model and prompt log | the same documents, with the group's numbers |
Weight 6 on Adalove. Follow the Sprint Increment Delivery Checklist of the module.
The lab used the orders of Olist. The groups repeat the same structure with the partner data during the week, and can practise first with the payments and reviews that the lab left in the Bronze.
lab/lesson-5/ of the module.Readings and a video assigned on Adalove for week 4. They extend the modelling part of the session: warehouse and mart, fact and dimension tables, and granularity.
Video on data marts and data warehouses, their roles and differences in an analytical environment.
Schema design, fact and dimension tables, granularity and the difference between warehouse and mart.
Open-access article on strategic concepts, development approaches and business impact of data warehousing.
The theory of each step in depth, the four prompts in full, the reference numbers and the mistakes that agents usually make in this lab.
Data Warehouses: the hybrid Silver layer ยท 05/11/2026 ยท Prof. Afonso
By the end of the session, students should be able to design the Silver layer of a Data Warehouse for the Olist orders as an enriched table with the data_ingestao, data_linha and data_tag columns, loaded first into a long-lived lake read with DuckDB and then into ClickHouse with a one-year retention, to reconcile both copies, and to build over it a star schema with views and materialized views that answers how many sales the North made each month compared with the Southeast, justifying the grain, the dimensions and the retention.
Practice and theory interleaved. The professor builds the Silver layer and the star schema live with a coding agent in four steps (contract and decision, hybrid load, audit and lifecycle, and star schema), pasting each CREATE prompt over the raw CSV files of Olist, and while the agent works the slides explain the concept that the step implements. Each step ends with a review against counts measured in the rehearsal, and the session closes with the connection to the Data Ingestion Structure artifact.