Module 8 · Information Systems · Lesson 5 · Week 4

Data Warehouses: the hybrid Silver layer

Reference material for the session in which the professor builds, live and with a coding agent, a Data Warehouse over the real orders of Olist, a Brazilian marketplace. One enriched table with the columns data_ingestao, data_linha and data_tag is written first to a long-lived lake in RustFS, an S3-compatible object storage read with DuckDB, and then loaded into ClickHouse, which keeps a one-year window for tactical queries. Over that table, a star schema built with views and refreshable materialized views answers how many sales were made each month in the North, compared with the Southeast. The material explains the Silver layer as a warehouse, enrichment, auditability, columnar warehouses, the lifecycle of the data and dimensional modelling, and it brings the measurements of the rehearsal and the four prompts in full.

About this session

Data Warehouses: the hybrid Silver layer · 05/11/2026 · Prof. Afonso

Learning objective

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.

Session strategy

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.

Session structure

  1. Daily — 15 min
  2. Running case, hybrid architecture, raw data and local environment — 10 min
  3. Step 01: contract of the enriched table and ADR; the Silver layer as a Data Warehouse and the data_ingestao, data_linha and data_tag columns — 15 min
  4. Step 02: enrichment and hybrid load; normalising, aggregating and deriving, and auditability with the lake first — 20 min
  5. Step 03: audit and lifecycle; Redshift and ClickHouse, TTL and the clock of the retention — 15 min
  6. Step 04: star schema over the Silver layer; dimensional modelling, views and materialized views, and the North against the Southeast — 27 min
  7. Verification and the Data Ingestion Structure artifact — 10 min
  8. Closing and self-study — 8 min
Part IFoundations

1. How to read this material

This material accompanies Lesson 5, in which the professor runs the lab alone, on the classroom computer, while the class follows on the projector. Each step starts with a CREATE prompt that the professor assembles and pastes into a coding agent, and while the agent writes the files the slides explain the concept that those files implement. Each step ends with a review in which the result is compared with the counts measured in the rehearsal. The groups then apply the same reasoning to the partner data in the artifact Data Ingestion Structure.

The case of the lesson is the public dataset of Olist, a Brazilian marketplace, with real orders placed between September 2016 and October 2018. Parts I to IV follow the theory blocks of the session. Part I places the Silver layer of the medallion architecture in the tradition of the Data Warehouse and describes the enriched table with its three columns. Part II covers the techniques of enrichment named in the description of the session and the reason why every load writes the lake before the warehouse. Part III compares two columnar warehouses, Amazon Redshift and ClickHouse, and discusses the lifecycle of the data, including the choice of the clock that the retention follows. Part IV introduces dimensional modelling in the sense of Kimball and builds, over the enriched table, a star schema in ClickHouse that answers one business question: how many sales were made each month in the North, compared with the Southeast. Part V is the lab, with the preparation of the classroom computer, the four prompts in full with their review questions, the verification and the mistakes that agents usually make in this kind of pipeline.

Every number in this material was measured on 05/11/2026 on the preparation machine, with RustFS 1.0.4, DuckDB 2.0.0, ClickHouse 26.8.15.10 and clickhouse-connect 1.12.0. The counts of rows are deterministic, because the input is a fixed archive of CSV files, and they should be reproduced exactly on the classroom computer. The times describe one machine with local containers and serve to compare the steps among themselves, so they will differ on another computer.

2. The Olist case and the hybrid architecture

Olist connects small Brazilian shops to large online marketplaces, and it published an anonymised sample of its operation as an open dataset. The sample contains about one hundred thousand orders placed between 2016-09-04 and 2018-10-17, with their items, customers, sellers, products, payments and reviews, and it is distributed under the MIT licence in the repository github.com/olist/work-at-olist-data. The same data is published on Kaggle as the "Brazilian E-Commerce Public Dataset by Olist". The lab uses eight of its CSV files, packed in one archive of 28 MB, which also carries the licence and a file SOURCE.txt with the origin of the data. The file of geolocation, with 61 MB, was left out, because no step of the lesson needs it.

Source: github.com/olist/work-at-olist-data, MIT licence; the same data as the Kaggle "Brazilian E-Commerce Public Dataset by Olist". The archive is also inside the lab folder, at data/olist_raw_csv.zip, so that load_bronze.py works without downloading anything else.

The data is real, and for this reason its defects were not planted by a generator but left by the systems that produced it. Some zip prefixes arrive with four digits, the leading zero already lost at the source; two headers of the products file are misspelt; one file starts with a byte order mark; and the timestamps were written in the local time of Brazil, which had daylight saving time until 2019, without any offset. Section 5 describes how the enrichment treats each defect, and section 14 lists the counts that load_bronze.py prints for them.

The architecture was decided by the professor before the session and is recorded by the agent in an ADR during Step 01. The script load_bronze.py uploads the eight CSV files, unchanged, to the Bronze layer of a local RustFS under bronze/source=olist/entity=<entity>/ingestion_date=2026-11-05/. Each load of the Silver layer reads the Bronze, enriches it with DuckDB and writes first a standardised lake in RustFS, one Parquet file per tag and per day under silver/enriched/data_tag=<tag>/ingestion_date=<D>/data.parquet, together with a manifest of the run under silver/_manifests/run_<id>.json that records the SHA-256 of every file. Only then does the load fill ClickHouse, and it does so by reading the files it has just written to the lake, never the Bronze. This order is what makes the warehouse auditable, since ClickHouse never holds a row that the lake does not hold and can be rebuilt from the lake at any moment. Over the enriched table of ClickHouse, Step 04 builds a star schema in a database gold, with dimensions as views and a fact and an aggregate as refreshable materialized views.

Source8 CSV files of Olist, 2016-09 to 2018-10
BronzeRustFS, files unchanged, read-only, partitioned by ingestion date
EnrichDuckDB with httpfs: normalise, aggregate, derive, quarantine
Silver lakeParquet by tag and day, manifest with SHA-256, kept for years
ClickHousesilver.enriched loaded from the lake, TTL of one year; star in gold

The two copies serve two kinds of question. ClickHouse keeps a short window, up to one year, removed automatically by a TTL, and answers the tactical questions of the operation, such as the number of delivered orders of the month by region. The lake keeps every version for years and is read with DuckDB for the strategic questions, for data science and for heavy manipulations such as training runs that last hours or days, which should not compete with the tactical queries for the resources of the warehouse. Section 8 explains why the length of the ClickHouse window belongs to the business and why, in this case, the clock that the window follows matters as much as its length.

The environment runs in two containers declared in docker-compose.yml. The object storage is RustFS, image rustfs/rustfs:1.0.4, which publishes the S3 API on port 9000 and the web console on port 9001, under the path /rustfs/console/. It replaces the MinIO of Lesson 4 because the official MinIO image is no longer published, and since it speaks the same S3 API, DuckDB and boto3 work against it unchanged. RustFS accepts only path-style addresses, which is why DuckDB is configured with URL_STYLE 'path'. ClickHouse uses the image clickhouse/clickhouse-server:26.8.15.10 and publishes only its HTTP interface, on port 8123, which is the one used by clickhouse-connect. The native port of ClickHouse is also 9000, and since RustFS already occupies that port on the host, the native port is not published. Inside the network of the compose file, ClickHouse reaches RustFS by the name of its service, at http://rustfs:9000, which is the value of S3_ENDPOINT_FROM_CLICKHOUSE in .env.

3. The Silver layer as a Data Warehouse

The term Data Warehouse was defined by William Inmon as a subject-oriented, integrated, time-variant and non-volatile collection of data in support of the decisions of management. Each of the four properties describes a guarantee that operational systems do not give, and together they explain why the Silver layer of the medallion architecture plays the role of the warehouse in this module.

Subject-oriented

The data is organised around the entities of the business, such as customer, seller, product, order and order item, whatever application produced them. In the enriched table, the entity is the middle segment of each tag, as in olist.order.v1.

Integrated

Codes, formats and units are made consistent. After the enrichment, every zip prefix of customers and sellers has five characters, every timestamp carries its offset and every category has a name in English, with the Portuguese name as fallback.

Time-variant

Every record is associated with a moment, and the history is kept. Here the moment is data_ingestao, and a second delivery of the same files, loaded with load_bronze.py --ingestion-date 2026-11-06, would be kept as another partition of the lake.

Non-volatile

Data is loaded and read, but not edited in place. A correction arrives as a new record or as a reload derived from the Bronze, which is why a rerun of the load must produce the same result.

The Silver layer combines and cleans the Bronze into a corporate view of the core entities of the business. Corporate view means that the definition of an order, of an order item or of a delivery is the same for every team that reads it, so that the commercial team and the finance team do not compute two different revenues from two different extractions. This shared definition is what makes self-service analytics possible, in which analysts query the Silver layer directly, without asking the engineering team to reconcile the sources for each question. Self-service depends on three conditions that the lab makes explicit: a written contract with the meaning of every field, stable names, and a way of filtering the data by kind and version, which is the role of data_tag.

The Silver layer is also the foundation of the Gold layer. This division corresponds to the two classic schools of the field. Inmon proposed an integrated enterprise warehouse, normalised, from which departmental data marts are derived. Ralph Kimball proposed building the warehouse as a set of dimensional marts that share conformed dimensions. In the medallion architecture, the Silver layer takes the integrating role of the Inmon warehouse and the Gold layer takes the dimensional role of the Kimball marts, so that the two approaches become successive layers. Step 04 of this lesson builds the first piece of the Gold layer, a star schema for one question, and Lesson 6 continues with cubes and data marts over the same Silver layer, so that every mart inherits the same cleaning and the same keys.

LayerGuarantee to the next layerIn this lesson
Bronzewhat arrived was kept as it arrived, with the moment of ingestion8 CSV objects of one delivery, written unchanged by load_bronze.py, read-only
Silverone record per declared key, integrated codes and formats, rejected records with a reason, lineage to the source fileenriched table in the lake (strategic) and in ClickHouse (tactical), 347,578 rows
Goldfacts and dimensions of an indicator, ready for consumptionthe star schema of Step 04 in the database gold; cubes and marts in Lesson 6

4. The enriched table

The description of the session asks for a table with three columns, and the lab keeps their names exactly as written, in Portuguese, because the contract of the Silver layer and the queries of every later lesson depend on them. The table stores one record per row, whatever the entity, and the entity and its version are declared by the tag.

ColumnType in ClickHouseContentRule
data_ingestaoDateTime64(3, 'America/Sao_Paulo')date and time at which the record entered the platformthe ingestion_date partition of the Bronze object at 00:00 in America/Sao_Paulo; it is not the date of the order
data_linhaJSONthe normalised and derived fields of one recordalways includes source_file
data_tagLowCardinality(String)kind and version of the recordolist.<entity>.v<N>, or quarantine.v1 for rejected records

The date and time of ingestion

The value of data_ingestao is derived from the Bronze, without reference to the clock of the load. Every object of the delivery lives under the partition ingestion_date=2026-11-05, so every record of the run receives 2026-11-05 00:00 in America/Sao_Paulo, written by ClickHouse as 2026-11-05 00:00:00.000 with the offset -03:00. The reason for this rule is reproducibility. If the load wrote the current time, two runs over the same Bronze would produce different values in every row, the files of the lake would differ from one run to the next and a reconciliation between runs would find differences that do not correspond to any change in the data. Deriving the moment from the Bronze makes reruns deterministic.

The moment of ingestion must not be confused with the moment of the business event. An order bought on 2018-03-14 entered the platform on 2026-11-05, and the date of the purchase lives inside data_linha, in the field purchased_at. The two clocks answer different questions, since data_ingestao says when the platform learned of a record and purchased_at says when the sale happened, and section 8 shows that the choice between them decides what the retention of ClickHouse keeps.

The record in JSON

The column data_linha holds the record as a JSON object. JSON accommodates structured data, such as an order with fixed fields, and semi-structured data, such as a record whose fields vary from one version of a source to another, in the same column. This flexibility would be a problem in a warehouse that stored the JSON as text, because every query would have to parse the text of every row. ClickHouse avoids it with the type JSON, which stores each path of the object as a separate subcolumn with its own type, so that a query on data_linha.customer_region reads only that subcolumn, as it would read an ordinary column. The format therefore remains compatible with the columnar storage of the warehouse, and a new field in a new version of the source becomes a new path without any change to the table.

In the rehearsal, ClickHouse kept the types written by the enrichment: purchased_at and zip_prefix stayed String, delivery_days and order_item_id became Int64, price and freight_value Float64, and delivered_late Bool. The path purchased_at stayed as text because every insert disabled the inference of dates, as section 17 explains, which preserves the offset written by the enrichment. The path zip_prefix stayed as text because the enrichment wrote it as a string of five characters, and a numeric type would remove the leading zero that the enrichment has just restored.

One record of olist.order.v1 (rehearsal of 05/11/2026)
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",
  "approved_at":"2018-03-14T10:48:41-03:00",
  "delivered_carrier_at":"2018-03-14T20:22:36-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"}

The flexibility of JSON has a cost that the design must pay elsewhere. The table does not enforce which fields each record has, so the schema of each kind of record moves from the DDL to the contract of the Silver layer, specs/silver_contract.md, where each tag lists its fields, its key of deduplication and its rules. The enrichment code and its tests are what enforce that contract.

The tags

The column data_tag classifies each record by source, entity and version. It serves three purposes. It versions the records, because a change in the format of a source produces a new tag, such as olist.order.v2, while the records of the previous version remain valid and the DDL of ClickHouse does not change. It categorises them, because the entity is part of the tag. And it filters them, because the table is ordered by (data_tag, data_ingestao), so that a query restricted to one tag reads a contiguous range of the table. The type LowCardinality(String) stores the few distinct values of the tag in a dictionary, which reduces both the size and the cost of comparing them. Five tags enter the Silver layer, plus quarantine. Payments and reviews stay in the Bronze, as material for the groups to treat on their own.

data_tagSource in the BronzeKey of deduplicationRows after Step 02
olist.customer.v1entity=customerscustomer_id99,441
olist.seller.v1entity=sellersseller_id3,095
olist.product.v1entity=products, with entity=product_category_translationproduct_id32,951
olist.order.v1entity=orders, with the state of the customerorder_id, latest ingestion date, then latest file99,433
olist.order_item.v1entity=order_items(order_id, order_item_id)112,642
quarantine.v1rejected records of any entityentity and key16 (8 orders and their 8 items)

A record in quarantine keeps in data_linha the entity, the key, the reason and the source file, which is enough to find the original row in the Bronze, since the Bronze keeps every file as it arrived.

SQL · sql/clickhouse_enriched.sql (reference)
CREATE DATABASE IF NOT EXISTS silver;
CREATE TABLE IF NOT EXISTS silver.enriched
(
    data_ingestao DateTime64(3, 'America/Sao_Paulo'),
    data_tag      LowCardinality(String),
    data_linha    JSON
)
ENGINE = MergeTree
PARTITION BY toYYYYMM(data_ingestao)
ORDER BY (data_tag, data_ingestao)
TTL toDateTime(data_ingestao) + INTERVAL 1 YEAR;
Part IIEnrichment and audit

5. Enrichment techniques

Enrichment is the set of transformations that turns a record of the Bronze into a record that the business can use without consulting other sources. The description of the session names three techniques, which are normalising formats and units, aggregating multiple sources and deriving new fields according to the requirements of the partner. The lab applies the three in the SQL of src/enrich.py, executed by DuckDB over the Bronze, together with the deduplication and the quarantine introduced in Lesson 4.

Normalising formats and units

Normalising means writing the same kind of value in the same way, whatever the state in which the source delivered it. The Olist files require six normalisations, and each one prevents a specific error downstream.

  • Every CSV column is read as text and converted explicitly, because automatic type detection reads a zip prefix such as 02728 as the integer 2728. In the source, 23,995 customer and 1,027 seller zip prefixes already have four digits, since the leading zero was lost before the export, and the enrichment pads them to five characters, so that the customer of the example has zip_prefix "02728".
  • The two misspelt headers of the products file, product_name_lenght and product_description_lenght, become name_length and description_length, so that the contract does not perpetuate the error of the source.
  • The translation file of the categories starts with a UTF-8 byte order mark, so its first header is read as product_category_name, with an invisible character in front, and a join on product_category_name fails to find the column. The reader must strip the mark, for instance with the encoding utf-8-sig in Python.
  • The categories receive their English name. The 610 products without a category receive 'unknown', and the 13 products whose category has no English translation, such as pc_gamer and portateis_cozinha_e_preparadores_de_alimentos, keep the Portuguese name.
  • The timestamps arrive without an offset, in the local time of Brazil, and they are written in ISO 8601 with the offset that America/Sao_Paulo had on each date. Brazil had daylight saving time until 2019, so the offset is -03:00 for most of the year and -02:00 in the summer, as in the shipping_limit_at "2017-12-08T13:30:29-02:00" of one item. A fixed offset of -03:00 would shift every summer timestamp by one hour, and an order placed in the last hour of a month would move to the next month in the answer of Step 04.
  • The CSV files mix quoted and unquoted fields, so the reader must follow the quoting rules of the format instead of splitting the lines on commas.

Aggregating multiple sources

Aggregating, in the sense of the description, means bringing into one record the attributes that live in different sources. An order of the orders file carries the identifier of the customer, but not the state where the customer lives, which comes from the customers file. The enrichment joins the customers and writes customer_state and customer_region inside the data_linha of each order. The record becomes self-contained, so that an analyst can group the orders by region without knowing where the states are defined, and the record keeps the attributes that were valid at the moment of its ingestion.

Deriving new fields

Deriving means computing a field that no source sends but that a requirement of the partner needs. The region is derived from the state, following the five regions of the IBGE, because the commercial area of Olist compares regions. The order receives delivery_days, the number of days between the purchase and the delivery to the customer, and delivered_late, which compares the delivery with the estimated date; the order of the example was bought on 2018-03-14, delivered on 2018-03-22 and estimated for 2018-04-06, so it has 8 days and was not late. The order item receives item_total, the sum of price and freight, which is 85.45 for an item of price 58.9 and freight 26.55. A derived field belongs to the Silver layer when the rule is stable and shared by several consumers, and it belongs to the Gold layer when it serves one indicator only.

RegionStates
NorthAC, AP, AM, PA, RO, RR, TO
NortheastAL, BA, CE, MA, PB, PE, PI, RN, SE
Central-WestDF, GO, MT, MS
SoutheastES, MG, RJ, SP
SouthPR, RS, SC

Deduplication, quarantine and the accounting of rows

Each tag is deduplicated by the key of the contract, which this delivery does not need, since it has no duplicates, but which the next delivery of the same files will need, because the rule keeps the latest ingestion date and then the latest file. Records that break a rule go to quarantine.v1 with a reason, and every record read from the Bronze ends in exactly one tag. In this delivery, 8 orders have the status 'delivered' without order_delivered_customer_date, and they go to quarantine because a delivered order without a delivery date cannot have delivery_days nor delivered_late. Their 8 items follow them with the reason 'order in quarantine', so that no item of the Silver layer refers to an order that the Silver layer does not hold. The 14 orders delivered without order_approved_at are kept, with approved_at null, because the missing approval does not prevent any field that the business uses.

EntityRows in the BronzeSilverQuarantine
Customers99,44199,4410
Sellers3,0953,0950
Products32,95132,9510
Orders99,44199,4338 delivered without delivery date
Order items112,650112,6428 of orders in quarantine
Total347,56216; with quarantine, 347,578 rows

6. Auditability: the lake first

A warehouse is auditable when every number it returns can be traced to the data that produced it and when that data can be shown to be the same data that was loaded. The hybrid design obtains this property through the order of the load, which always writes the lake, then loads ClickHouse from the files of the lake, and writes the manifest last.

StageWhat it doesMeasured in the rehearsal (Step 02)
EnrichDuckDB reads the Bronze over httpfs and builds one relation (data_ingestao, data_tag, data_linha)0.75 s
Write the lakeone Parquet file per tag and day, SHA-256 of the bytes uploaded6 files, 0.80 s
Load ClickHousetruncate silver.enriched and insert the Parquet files of the lake with the s3() table function0.85 s
Write the manifestkeys, tags, rows, bytes and SHA-256 per file, rows per tag, times and statusstatus ok; total about 2.5 s

ClickHouse reads the lake itself, through the table function s3(), instead of receiving the rows from Python. The address in the call is the one of RustFS inside the network of the compose file, because localhost, seen from inside the ClickHouse container, is the container itself. The column data_linha is declared as String in the structure passed to s3(), since Parquet stores it as text, and the insert converts it to the type JSON of the table.

SQL · shape of the load of ClickHouse from the lake (credentials come from .env)
INSERT INTO silver.enriched
SELECT data_ingestao, data_tag, data_linha
FROM s3('http://rustfs:9000/olist-lake/silver/enriched/data_tag=*/ingestion_date=*/data.parquet',
        key, secret, 'Parquet',
        'data_ingestao DateTime64(3, ''America/Sao_Paulo''), data_tag String, data_linha String')
SETTINGS input_format_try_infer_dates = 0,
         input_format_try_infer_datetimes = 0,
         async_insert = 0;

The order has three consequences. The first is that ClickHouse never holds a row that the lake does not hold, because the only input of ClickHouse is the set of lake files of the run. If the load of ClickHouse fails, the manifest is written with the status error_clickhouse and the process exits with a non-zero code, so that the scheduler knows that the tactical copy is out of date while the lake remains complete. The second is that ClickHouse is disposable, in the sense that it can be rebuilt from the lake at any moment. In the rehearsal, rebuilding it from the lake took about 1.0 s for 347,578 rows. The third is that the integrity of the lake can be checked later, because the manifest keeps the SHA-256 of every file. The reconciliation of Step 03 recomputes the hash of each file listed in the last manifest, and any difference means that a file was changed after the load.

Structure of silver/_manifests/run_<run_id>.json (values abbreviated)
{
  "run_id": "...",
  "status": "ok",
  "files": [
    {"key": "silver/enriched/data_tag=olist.order.v1/ingestion_date=2026-11-05/data.parquet",
     "data_tag": "olist.order.v1", "rows": 99433, "bytes": ..., "sha256": "..."},
    ...
  ],
  "rows_per_tag": {"olist.customer.v1": 99441, "olist.seller.v1": 3095,
                   "olist.product.v1": 32951, "olist.order.v1": 99433,
                   "olist.order_item.v1": 112642, "quarantine.v1": 16},
  "times_s": {"enrich": 0.75, "lake": 0.80, "clickhouse": 0.85}
}

A rerun over the same Bronze must arrive at the same result, and the design ensures it in two ways. Each lake key is determined by the tag and the day, so a rerun overwrites the same keys instead of adding files, and ClickHouse is truncated and rebuilt from the lake, so it cannot accumulate copies of a previous run. Since data_ingestao comes from the Bronze, the content of every record is also the same in both runs. In the rehearsal, the second run arrived at the same counts for every tag.

The decision and its alternatives

The ADR written in Step 01 compares the hybrid design with two simpler alternatives. Both remove one copy, and each loses a property that the business needs.

OptionAdvantagesWhat is lost
ClickHouse onlyone system to operate; fast queries over all the datathe history must stay in the warehouse forever, or be deleted; there is no independent copy against which to audit the warehouse; heavy data science competes with the tactical queries
Lake only, read with DuckDBcheapest storage; one copy; long historyno server for concurrent tactical queries by many users; every query reads files from Object Storage
Hybrid: lake first, then ClickHouselong history in the lake, fast tactical window in ClickHouse, audit by reconciliation and SHA-256, warehouse rebuildabletwo copies to keep consistent, which requires the reconciliation of Step 03 and the discipline of the order of the load
Part IIIWarehouses and lifecycle

7. Columnar warehouses: Redshift and ClickHouse

Operational databases store each row contiguously, because a transaction usually reads or writes a whole record, such as one order. Analytical queries behave differently, since they read a few columns of millions of rows, such as the price and the region of every order item of a month. A columnar warehouse stores each column contiguously, so that such a query reads only the columns it needs. Values of the same column are similar to one another, which makes compression much more effective, and the engine can process blocks of values of one column at a time, which is called vectorised execution. Amazon Redshift and ClickHouse, the two tools named in the description of the session, are columnar warehouses, and so is DuckDB, used in the lab as the engine of the lake.

ClickHouse and the MergeTree engine

ClickHouse is an open-source columnar database for analytical workloads, which can run in a container, as in the lab, on a cluster or as a managed cloud service. Its main family of table engines is MergeTree. Each insert writes an immutable part, with the rows sorted by the key of ORDER BY, and a background process merges small parts into larger ones. The table has a sparse primary index, with one entry for each granule of rows (8,192 rows by default), so that a filter on the first columns of the sorting key skips the granules that cannot contain matching rows. In the lab, the sorting key (data_tag, data_ingestao) makes a filter by tag read only the granules of that tag, which is what keeps the dimension views of Step 04 cheap even though they are recomputed at every query.

Two other clauses of the DDL organise the data in time. PARTITION BY toYYYYMM(data_ingestao) keeps the parts of each month separate, which allows the engine to drop or skip a whole month at once. TTL toDateTime(data_ingestao) + INTERVAL 1 YEAR declares that a row expires one year after its ingestion, and ClickHouse removes expired rows during merges. After Step 02 the table occupied about 32.5 MB on disk for 347,578 rows.

Amazon Redshift

Amazon Redshift is the managed warehouse of AWS, offered as provisioned clusters or as Redshift Serverless. It is a massively parallel processing (MPP) system, in which a leader node plans each query and compute nodes execute it in parallel over slices of the data, stored in columns. Two choices of the table design decide its performance. The distribution style (KEY, ALL, EVEN or AUTO) decides on which node each row lives, and a good choice puts the rows that are joined together on the same node, avoiding traffic between nodes; a small dimension such as dim_date is a typical candidate for ALL, which copies it to every node. The sort key decides the order of the rows on disk, and Redshift keeps the minimum and maximum of each block (zone maps) to skip blocks, playing a role similar to the sorting key of MergeTree. Redshift Spectrum reads files in S3 through external tables, so that a query can combine tables of the warehouse with Parquet files of a lake, and the type SUPER stores semi-structured values queried with PartiQL, which is the counterpart of the JSON type of ClickHouse.

AspectClickHouseAmazon RedshiftDuckDB (lake engine of the lab)
Deploymentopen source, self-hosted or managed cloudmanaged by AWS, provisioned or serverlessembedded library, in the Python process
Storagecolumnar parts of MergeTreecolumnar blocks distributed across nodesits own file or Parquet files in Object Storage
Physical organisationORDER BY, PARTITION BY, sparse indexdistribution style and sort key, zone mapsrow groups of Parquet with minimum and maximum per column
Semi-structured dataJSON type with typed subcolumnsSUPER type with PartiQLJSON type and operators such as ->>
Retentiondeclarative TTL on the tableno table TTL; scheduled DELETE and VACUUM, or old data kept only in S3 and read with Spectrumfiles kept or deleted in the lake
Stored results of queriesincremental and refreshable materialized viewsmaterialized views with manual or automatic refreshtables created from queries
Reading the laketable functions such as s3()Redshift Spectrumextension httpfs

The enriched table can be written for Redshift with the same structure, with data_ingestao as TIMESTAMPTZ, data_tag as VARCHAR at the start of the sort key and data_linha as SUPER. What changes is the mechanism of retention, which in Redshift is an operation scheduled by the platform, since its tables have no TTL clause.

8. Lifecycle and the clock of the TTL

Data has a lifecycle, and the questions asked about it change with its age. Recent data is read often, by many people, with short questions about the operation, and it must answer in a fraction of a second. Old data is read rarely, by few people, with long questions about trends, and it can take seconds or minutes. The hybrid design gives each phase a place, with ClickHouse keeping the tactical window and the lake, read with DuckDB, keeping the strategic history.

The question of Step 04 was answered in both places, which makes the difference measurable. ClickHouse answered it in 0.002 s from the stored aggregate and in 0.06 s from the fact with its joins, while DuckDB answered it in 0.47 s reading the Parquet files of the lake, with the same result in the three cases. The lake is small in this case, so the strategic copy is still fast. Its place is the lake for another reason, which is that the lake keeps every delivery for years, and that a training run of data science that reads all of them for hours would degrade the tactical queries if it ran on the warehouse.

The window is a business decision

The length of the ClickHouse window, one year in the lab, is a business decision. Technically, ClickHouse could keep a month or a decade, and changing the window is a single statement, ALTER TABLE silver.enriched MODIFY TTL .... What the window should be depends on questions that only the business can answer: how far back the tactical users look in their daily work, how much the partner is willing to pay to keep data in the fast copy, and which legal obligations or limits apply, such as fiscal retention periods and the principle of minimisation of the LGPD for personal data. The owner of the decision is the business area of the partner that uses the tactical queries, together with whoever answers for data governance. For this reason the contract and the ADR of the lab mark the one-year retention as a hypothesis to validate with the partner, and the engineering team implements whatever value the business decides.

Which clock the retention follows

The Olist case adds a second decision, which is the clock that the window follows. The TTL of the lab counts one year from data_ingestao, and since every record was ingested on 2026-11-05, ClickHouse keeps every row. A TTL that counted from purchased_at would keep 0 of the 99,433 orders, because the newest order of the dataset was placed on 2018-10-17T17:30:18-03:00, eight years before the lesson. Both readings are defensible. Counting from the ingestion keeps in ClickHouse whatever arrived recently, which suits a platform that reprocesses old data, while counting from the purchase keeps the recent sales, which suits an operation that only looks at the current year. Which clock the retention follows is therefore a business decision of the same kind as the length of the window, and Step 03 records it in the ADR as a question addressed to its owner.

Decision for the group

In the artifact Data Ingestion Structure, the group should state the retention of its warehouse as a hypothesis, say which date of the partner data the retention counts from, name who in the partner organisation decides it, and record the question that will validate it, for example how many months back the users of the DataApp compare their indicators.

The reconciliation inside the window

The reconciliation compares, for each tag, the rows of the lake, the rows of the lake that fall inside the window of ClickHouse and the rows of ClickHouse. The window must be read from the TTL of the table in ClickHouse, so that a change of the business decision does not require a change in the script, and a row in ClickHouse that is not in the lake is a difference whatever the window, because it would break the guarantee of section 6. In this delivery the three counts coincide for every tag, since nothing has expired.

Output of python -m src.reconcile in the rehearsal
window of ClickHouse read from the TTL: 1 Year
data_tag                  lake  window  clickhouse
olist.customer.v1        99441   99441       99441  OK
olist.order.v1           99433   99433       99433  OK
olist.order_item.v1     112642  112642      112642  OK
olist.product.v1         32951   32951       32951  OK
olist.seller.v1           3095    3095        3095  OK
quarantine.v1               16      16          16  OK
files=6 sha256_mismatches=0
Part IVDimensional modelling

9. Dimensional modelling

The enriched table records what arrived, with each record self-contained, and it is well suited to audit and to reprocessing. The commercial area of Olist, however, asks questions about sales by month, by region or by category, and answering them over the enriched table would require every analyst to know which tags to join, which paths to read and how to define a sale. Dimensional modelling, systematised by Ralph Kimball and Margy Ross in The Data Warehouse Toolkit, organises the data around the measurement of a business process, so that the questions of the business become simple queries and the definition of each measure is written once.

The four steps of the design

Kimball and Ross describe the design of a dimensional model in four steps, taken in order because each one depends on the previous. The first step selects the business process, which in this case is the sale of products through the marketplace, recorded by the orders and their items. The second step declares the grain, which is the exact meaning of one row of the fact table; here the grain is one order item, because price, freight, seller and product exist only at the level of the item, and a fact at the level of the order would have to choose one seller and one product for orders that have several. The third step identifies the dimensions, which are the contexts in which the measurements are read: who bought (customer), who sold (seller), what was sold (product) and when (date). The fourth step identifies the facts, which are the numerical measurements of the process at the declared grain, here price and freight_value of each item.

Fact table

One row per measurement event at the declared grain, with foreign keys to the dimensions and the numerical measures. It is long and narrow, since it grows with the operation; in the case, 112,642 rows.

Dimension table

One row per member of a context, with descriptive attributes used to filter and group, such as city, state and region of the customer. It is short and wide, and it changes slowly.

Conformed dimensions

A dimension is conformed when it has the same keys, the same attributes and the same meaning in every fact table that uses it. If the payments and the reviews, which this lesson leaves in the Bronze, later receive their own fact tables, they should reuse dim_customer and dim_date instead of building new ones, so that a question that crosses sales and reviews by region of the customer compares the same regions on both sides. Conformed dimensions are what allows a set of marts, built one at a time, to behave as one warehouse, which is the central argument of Kimball against the integrated warehouse built in one piece.

Additive measures and distinct counts

Kimball classifies the measures by how they can be summed. An additive measure can be summed across every dimension, as is the case of price: the revenue of a month is the sum of the revenue of its days, and the revenue of a region is the sum of the revenue of its states. A semi-additive measure can be summed across some dimensions but not across time, as a stock balance, and a non-additive measure cannot be summed at all, as a ratio. The number of sales of the question belongs to a fourth kind, the distinct count, because a sale is an order and the fact has one row per item. Counting the rows of the fact would count items, 112,642 in total for 99,433 orders, and the question asks for orders, so the measure must be uniqExact(order_id). A distinct count is not additive in general, since the same order could be counted in two groups, but in this case the sum across regions and across months is safe, because each order has exactly one customer and one date of purchase, so it belongs to exactly one region and one month.

The star and its alternatives

A star schema places the fact table at the centre and connects it to one table per dimension, with the dimensions denormalised: the region is an attribute of dim_customer, repeated for every customer of the region. This redundancy is deliberate, because it keeps every question at one join per dimension and makes the model readable by analysts. Third Normal Form, which stores each fact in one place to prevent the anomalies of updates, and Data Vault, which separates identity, relationships and history into hubs, links and satellites for environments with many changing sources, remain valid alternatives for the integrated Silver layer of other projects, and a group whose partner has many sources may prefer one of them before the Gold layer. This lesson keeps the enriched table as the Silver layer and builds the star directly over it.

10. The star of the case

The star of Step 04 has one fact and four dimensions, all in the database gold of ClickHouse, and an aggregate that stores the answer of the question at the grain of month and region. The dimensions come from three tags of the enriched table and from a calendar generated by ClickHouse, and the fact comes from the join of the orders with their items.

ObjectKind in ClickHouseSourceGrain and columnsRows
gold.dim_customerviewolist.customer.v1one customer; customer_id, city, state, region99,441
gold.dim_sellerviewolist.seller.v1one seller, with its location3,095
gold.dim_productviewolist.product.v1one product, with its category32,951
gold.dim_dateviewnumbers(), from 2016-01-01one day; date_key (yyyymmdd), date, month ('YYYY-MM'), quarter, year, weekday1,096
gold.fact_order_itemrefreshable materialized view, MergeTree, REFRESH EVERY 1 HOURolist.order_item.v1 joined with olist.order.v1one order item; order_id, order_item_id, date_key, customer_id, seller_id, product_id, order_status, price, freight_value112,642
gold.agg_sales_month_regionrefreshable materialized view, DEPENDS ON gold.fact_order_itemfact with dim_date and dim_customerone month and region; orders, items, revenue of delivered orders107

The fact carries order_status, an attribute of the order repeated in each of its items, because the definition of a sale filters the delivered orders, and keeping the status in the fact avoids a join with the orders at every query. The date of the fact is the date of purchased_at in the time of Brazil, converted to the key date_key, so that the month of a sale is the month in which the customer bought, whatever the moment of the delivery. The fact is ordered by (date_key, order_id, order_item_id), so that a filter by period reads a contiguous range, and the aggregate is ordered by (month, region).

Mermaid · ER diagram of the star (the shape asked of docs/star_model.md)
erDiagram
  dim_customer ||--o{ fact_order_item : "bought"
  dim_seller   ||--o{ fact_order_item : "sold"
  dim_product  ||--o{ fact_order_item : "was sold"
  dim_date     ||--o{ fact_order_item : "purchase day"
  fact_order_item {
    String order_id
    Int64 order_item_id
    UInt32 date_key
    String customer_id
    String seller_id
    String product_id
    String order_status
    Float64 price
    Float64 freight_value
  }
  dim_customer {
    String customer_id
    String city
    String state
    String region
  }
  dim_date {
    UInt32 date_key
    Date date
    String month
  }

The region of a sale is the region of the customer, which is the destination of the order. The region of the seller would answer a different question, about where the marketplace sources its products, and the choice must be written in docs/star_model.md together with the rest of the definition of a sale, because two analysts who chose differently would publish two different answers to the same sentence.

11. From silver.enriched to the star

The enriched table holds the five entities in one table, so each dimension is a filter by tag followed by the extraction of the paths of data_linha as typed columns. The filter by tag reads only the granules of that tag, thanks to the sorting key, and the cast of each path declares the type that the dimension exposes, so that analysts query gold.dim_customer.region as an ordinary column without knowing that it lives in a JSON object. The view of the customers is the example given in prompt 04.

SQL · dimension of customers (example of prompt 04)
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';

The calendar has no source in the Bronze. It is generated with the table function numbers(), which returns the integers from 0, so that 1,096 days from 2016-01-01 cover the years 2016 to 2018, the whole period of the orders. A calendar dimension exists because the attributes of a date, such as its month, quarter or weekday, are used to group the facts, and computing them once in a dimension avoids repeating the expressions in every query.

SQL · calendar dimension, as run in the rehearsal
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));

The fact joins two tags of the same table. Each side is a subquery that filters its tag before reading any path, and the order of the operations matters, because a function such as parseDateTime64BestEffort applied to data_linha.purchased_at over the whole table fails on the rows of the other tags, where the path is empty. The time zone passed to the parser makes the month the month in Brazil, as the adjustments of prompt 04 require.

SQL · the fact as a refreshable materialized view, as run in the rehearsal
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                                   AS order_id,
       i.order_item_id                              AS order_item_id,
       toUInt32(toYYYYMMDD(o.purchased_at))         AS date_key,
       o.customer_id                                AS customer_id,
       i.seller_id                                  AS seller_id,
       i.product_id                                 AS product_id,
       o.order_status                               AS order_status,
       i.price                                      AS price,
       i.freight_value                              AS 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;

The inner join keeps every item of the Silver layer, 112,642, because the quarantine already removed the items whose order was rejected. A difference between the rows of olist.order_item.v1 and the rows of the fact would therefore indicate an item without its order, which is a failure of the enrichment.

12. Views and materialized views in ClickHouse

The objects of the star can be computed at query time or stored, and ClickHouse offers three mechanisms with different costs. The choice depends on how much the computation costs, how often the result is read and how the source table changes, which in the lab is by truncating and reloading silver.enriched at every run.

MechanismWhat it storesWhen it is computedFits the lab when
View (CREATE VIEW)only the queryat every query that reads itthe computation is cheap, as a filter by tag with casts; used for the four dimensions
Incremental materialized view (CREATE MATERIALIZED VIEW ... TO)the result, in a target tableat each insert into its one source table, over the inserted block onlythe source only receives appends and the query reads one table; it does not fit the fact
Refreshable materialized view (REFRESH EVERY)the result, in a table of its ownon a schedule, recomputing the whole query and swapping the result atomicallythe query joins tables or the source is reloaded; used for the fact and the aggregate

Plain views for the dimensions

A plain view stores only its query, and ClickHouse substitutes it into every query that reads the view. The dimensions are plain views because their computation is a filter on the first column of the sorting key followed by casts, which reads only the granules of one tag, and because a view can never be out of date: after a reload of silver.enriched, the next query already sees the new customers.

Why the incremental materialized view does not fit

An incremental materialized view of ClickHouse is an insert trigger. When a block of rows is inserted into its source table, ClickHouse runs the query of the view over that block only and appends the result to the target table, which makes the view cheap for aggregations over a table that only grows. Two properties of the lab break this mechanism. The first is the join: the trigger is attached to one table, and in a query with a join only the inserts into the left table fire it, so an item that arrives before its order, or an order that changes, never updates the target. The second is the reload: the load of Step 02 truncates silver.enriched and inserts everything again, and a truncate of the source does not reach the target of an incremental view, so the target would keep the rows of the previous run and receive the same rows again, doubling every count at each run.

Refreshable materialized views for the fact and the aggregate

A refreshable materialized view recomputes its whole query on a schedule, writes the result into a new table and then swaps it for the previous one in one atomic operation, so that a query never sees a half-written result. The fact uses REFRESH EVERY 1 HOUR, which ClickHouse aligns to the clock hour, and the aggregate declares DEPENDS ON gold.fact_order_item, which makes its scheduled refresh wait for the refresh of the fact. The cost of the mechanism is that the stored result can be up to one interval old, which is acceptable for a commercial question asked once a day, and the benefit is that the answer is read from 107 stored rows instead of being recomputed from 347,578.

SQL · the aggregate, as run in the rehearsal
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;

Refreshing after a load

The dependency declared with DEPENDS ON orders only the scheduled refreshes. A manual SYSTEM REFRESH VIEW gold.fact_order_item refreshes the fact and leaves the aggregate with the previous result until its next scheduled refresh, so the end of each load must refresh both, in order, waiting for each one to finish.

SQL · after each load of silver.enriched
SYSTEM REFRESH VIEW gold.fact_order_item;
SYSTEM WAIT VIEW gold.fact_order_item;
SYSTEM REFRESH VIEW gold.agg_sales_month_region;
SYSTEM WAIT VIEW gold.agg_sales_month_region;

13. The question and its answer

The question of the commercial area is "How many sales were made each month in the North, compared with the Southeast?". Before any query, docs/star_model.md fixes the meaning of each word of the sentence: a sale is a delivered order, counted once; the month is the month of purchased_at in the time of Brazil; and the region is the region of the customer. With this definition, the dataset has 96,470 delivered orders, with a revenue, as the sum of the prices of their items, of 13,220,181.73.

RegionDelivered orders
Southeast66,193
South13,813
Northeast9,044
Central-West5,624
North1,796
Total96,470
SQL · sql/question.sql over the aggregate, as run in the rehearsal
-- How many sales (delivered orders) 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;

The answer has one row per month in which at least one of the two regions had a delivered order, which excludes 2016-11 and 2016-12. The first months of the dataset have few orders, so the percentage of those months says little about the regions.

MonthNorthSoutheastNorth as % of Southeast
2016-09010
2016-1051722.91
2017-01174853.51
2017-02551,1034.99
2017-03701,7264.06
2017-04761,5095.04
2017-05822,3313.52
2017-06642,1183.02
2017-07592,6062.26
2017-08982,7553.56
2017-09902,7533.27
2017-10923,0193.05
2017-111245,0002.48
2017-12983,8182.57
2018-011354,8162.80
2018-021064,4502.38
2018-031204,8242.49
2018-041134,7272.39
2018-05914,8371.88
2018-061004,2792.34
2018-071284,1743.07
2018-08734,6901.56
Total1,79666,1932.71

Over the whole period, the North made 2.71 % as many sales as the Southeast. The month with most sales in the Southeast was 2017-11, with 5,000, when the North made 124, while the highest month of the North was 2018-01, with 135. The answer does not explain the difference between the regions, which may come from population, income or delivery times, and a group that wanted to investigate it would bring delivery_days and delivered_late into the fact.

Three ways of answering

Step 04 answers the same question three times, which checks the star and measures the cost of each copy. The three answers were identical in the rehearsal, so the difference between them is only the cost of reading.

SourceNorthSoutheastSecondsWhat is read
gold.agg_sales_month_region in ClickHouse1,79666,1930.002107 stored rows
gold.fact_order_item with the joins, in ClickHouse1,79666,1930.06112,642 rows of the fact, joined with the dimensions at query time
DuckDB over the lake1,79666,1930.47the Parquet files of the lake, through the views of sql/star_duckdb.sql

The aggregate is about thirty times faster than the fact, because it has already done the joins and the distinct count, and the fact is about eight times faster than DuckDB over the lake, because it is stored in the warehouse instead of being read from Object Storage. The DuckDB answer matters for another reason, since it is computed from the lake and not from ClickHouse, and its agreement with the other two shows that the star of ClickHouse did not lose or duplicate any sale.

Part VLab

14. Step 00 · Preparing the environment

The lab runs on the classroom computer, with Linux Mint, Docker Engine and Python 3, and with Claude Code as the coding agent. The support files are in the folder lab/lesson-5/ of the module: docker-compose.yml with RustFS and ClickHouse, .env.example, requirements.txt (DuckDB, boto3, clickhouse-connect, python-dotenv, pytz and pytest), load_bronze.py, which uploads the Bronze, the archive data/olist_raw_csv.zip, AGENTS.md with the rules for the agent and README.md. The code of the Silver layer and of the star is not there. It is written live, through the prompts of section 15, in the folder lesson_05_dw/, which starts as a copy of the lab folder.

The archive comes from github.com/olist/work-at-olist-data, under the MIT licence, and holds the same data as the Kaggle "Brazilian E-Commerce Public Dataset by Olist". The copy of the lab folder below already contains it, so the button is needed only to inspect the files outside the lab.

The lab folder is obtained by cloning the repository of the course with a depth of one commit, which downloads only the current version of the files, and copying the folder of the lesson to the home directory.

Terminal · classroom computer (Linux Mint)
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
mkdir -p specs docs/adr sql src tests/fixtures warehouse
printf '.env\n.venv/\n__pycache__/\nwarehouse/\n' > .gitignore
cp .env.example .env              # change S3_SECRET_KEY and CLICKHOUSE_PASSWORD: openssl rand -base64 24

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 CSV objects, ingestion_date=2026-11-05

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

The file .env holds the passwords of RustFS and of ClickHouse and is never committed, pasted into a prompt or shown on the projector. The rules of AGENTS.md forbid the agent to read or print it, and the agent refers to the credentials only by the names of the variables. The script load_bronze.py reads the CSV files of the archive and uploads each one, byte for byte, to s3://olist-lake/bronze/source=olist/entity=<entity>/ingestion_date=2026-11-05/<file>.csv, without renaming a column, converting a value or removing a row. It then prints the rows of each entity and the defects of the source that the Silver layer must treat, and that output is the expected input of the enrichment.

Entity in the BronzeRowsEnters the Silver layer as
orders99,441olist.order.v1
order_items112,650olist.order_item.v1
customers99,441olist.customer.v1
sellers3,095olist.seller.v1
products32,951olist.product.v1
product_category_translation71joined into the products
payments103,886stays in the Bronze
reviews99,224stays in the Bronze
Defect printed by load_bronze.pyCountTreatment in the Silver layer
orders 'delivered' without order_delivered_customer_date8quarantine, with their 8 items
orders 'delivered' without order_approved_at14kept, with approved_at null
customer zip prefixes with 4 digits23,995padded to 5 characters
seller zip prefixes with 4 digits1,027padded to 5 characters
products without category610category 'unknown'
products whose category has no English translation13Portuguese name kept
misspelt headers in products2name_length, description_length
file starting with a UTF-8 byte order mark1mark removed before reading the header
timestamps without offset, in local time with daylight saving until 2019allISO 8601 with -03:00 or -02:00
mixed quoting in the CSV filesallreader that follows the CSV quoting rules

The console of RustFS is at http://localhost:9001/rustfs/console/ (the root of the port answers 403), with the pair S3_ACCESS_KEY and S3_SECRET_KEY as login, where the prefixes bronze/ and, after Step 02, silver/enriched/ and silver/_manifests/ can be shown to the class. ClickHouse answers on http://localhost:8123, and its client is opened inside the container with the command recorded in AGENTS.md, which uses the variables of the container instead of typing the password.

15. The lab in four steps

The prompts follow the CREATE structure used in the module: character, request, example, adjustments, type of output and extras. The professor sends each one alone, the agent shows its plan before editing and stops at the end, and the step closes with the questions of its review box. The prompts bring the facts measured in the rehearsal and ask the agent to confirm them before use, so that the result on the classroom computer can be compared with the reference. When a group adapts a prompt to the partner data, the facts must be measured again.

StepStartFilesWhile the agent works, the session explains
Daily14:00 (15 min)
00 · Case14:15 (10 min)environment of section 14the Olist case, the hybrid architecture and the environment (section 2)
0114:25 (15 min)specs/silver_contract.md, docs/adr/ADR-002-hybrid-silver.md, sql/clickhouse_enriched.sqlthe Silver layer as a Data Warehouse and the enriched table (sections 3 and 4)
0214:40 (20 min)src/config.py, src/enrich.py, src/lake.py, src/clickhouse.py, src/load_hybrid.py, tests/test_enrich.pyenrichment and auditability with the lake first (sections 5 and 6)
0315:00 (15 min)src/reconcile.py, section "Measured consequences" of the ADRRedshift and ClickHouse, the lifecycle and the clock of the TTL (sections 7 and 8)
0415:15 (27 min)docs/star_model.md, sql/star_clickhouse.sql, sql/star_duckdb.sql, sql/question.sqldimensional modelling, the star, views and materialized views, and the question (sections 9 to 13)
Verification15:42 (4 min)verification (section 16)
Artifact15:46 (6 min)the artifact Data Ingestion Structure (section 18)
Closing15:52 (8 min)closing and self-study (section 21)

Step 01 · Contract of the enriched table and decision record

The first step produces no Python. The agent writes the contract of the Silver layer, with the three columns, the catalogue of tags and the layout of the lake, the ADR of the hybrid design and the DDL of ClickHouse, which it applies and displays with SHOW CREATE TABLE. Showing the catalogue of tags before writing the files gives the professor a moment to correct a key or a rule before it spreads to the code.

Prompt 01 · CREATE
[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.
Review before moving on

Are the three columns named exactly data_ingestao, data_linha and data_tag? Is data_ingestao the partition of the Bronze at 00:00, and not the date of the order? Does every tag of the catalogue have a key and its rules, and is zip_prefix a string of five characters? Is the one-year retention marked as a business hypothesis with an owner? Does SHOW CREATE TABLE show the JSON type and the TTL?

Step 02 · Enrichment and hybrid load

The second step implements the load in the order of section 6 and runs it. The expected result is 347,578 rows in 6 Parquet files and 6 tags, with the same count per tag in the lake and in ClickHouse, in about 2.5 s on the preparation machine. The unit tests use small fixtures with one example of each defect and do not access the network, so that they run without the containers.

Prompt 02 · CREATE
[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.
data_tagRows in the lakeRows in ClickHouse
olist.customer.v199,44199,441
olist.seller.v13,0953,095
olist.product.v132,95132,951
olist.order.v199,43399,433
olist.order_item.v1112,642112,642
quarantine.v11616
Total347,578 in 6 files347,578, about 32.5 MB on disk
Review before moving on

Does the run write the lake before ClickHouse and the manifest last? Does the table show 347,578 rows in both copies, 99,433 orders and 16 records in quarantine? Did purchased_at and zip_prefix stay String in ClickHouse, and does a summer timestamp carry -02:00? Does ClickHouse read the lake at S3_ENDPOINT_FROM_CLICKHOUSE, and not at localhost?

Step 03 · Audit and lifecycle

The third step answers the two questions that the partner asks before trusting the Silver layer. The agent writes the reconciliation, runs the load twice to show that a rerun arrives at the same counts, rebuilds ClickHouse from the lake and measures what a TTL on the date of purchase would keep. The expected result is the reconciliation of section 8, with 6 tags OK, 6 files and 0 SHA-256 mismatches in 0.4 s, a rebuild of 347,578 rows in about 1.0 s, and 0 of the 99,433 orders inside a window that counted from purchased_at.

Prompt 03 · CREATE
[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.
Review before moving on

Is the window read from the TTL of the table, and does the script understand toIntervalYear(1)? Did the second run arrive at the same counts? Did the agent ask before the DROP? Does the new section of the ADR address the question of the clock of the retention to the owner of the decision?

Step 04 · The star schema and the question

The last step builds the star of sections 10 to 12 in ClickHouse, builds the same star in DuckDB over the lake and answers the question of section 13 in three ways. The expected counts are dim_customer 99,441, dim_seller 3,095, dim_product 32,951, dim_date 1,096, fact_order_item 112,642 and agg_sales_month_region 107, and the expected answer is North 1,796 and Southeast 66,193 in the three sources.

Prompt 04 · CREATE
[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.
Review before moving on

Are the dimensions views and only the fact and the aggregate stored? Is a sale counted with uniqExact(order_id), and is the month the month of purchased_at in Brazil? Were the fact and the aggregate refreshed in order after the load? Do the three answers agree with 1,796 and 66,193, and does 2017-11 show 124 and 5,000?

16. Verification

The verification checks four properties of the result: that the tests of the enrichment pass, that the two copies of the Silver layer agree inside the window, that the files of the lake are the ones the manifest describes, and that the star returns the counts and the answer of the rehearsal. The sequence below runs after Step 04.

Terminal · ~/lesson_05_dw
pytest -q
python -m src.load_hybrid           # lake, then ClickHouse, then the manifest
python -m src.reconcile             # exits with a non-zero code on any DIFF or SHA-256 mismatch

docker compose exec clickhouse sh -c 'clickhouse-client --user "$CLICKHOUSE_USER" --password "$CLICKHOUSE_PASSWORD" --multiquery --query "SYSTEM REFRESH VIEW gold.fact_order_item; SYSTEM WAIT VIEW gold.fact_order_item; SYSTEM REFRESH VIEW gold.agg_sales_month_region; SYSTEM WAIT VIEW gold.agg_sales_month_region"'
docker compose exec clickhouse sh -c 'clickhouse-client --user "$CLICKHOUSE_USER" --password "$CLICKHOUSE_PASSWORD" --query "SELECT data_tag, count() FROM silver.enriched GROUP BY data_tag ORDER BY data_tag"'
docker compose exec clickhouse sh -c 'clickhouse-client --user "$CLICKHOUSE_USER" --password "$CLICKHOUSE_PASSWORD" --query "SELECT (SELECT count() FROM gold.fact_order_item), (SELECT count() FROM gold.agg_sales_month_region)"'
CheckExpected after Step 04
Bronze8 CSV objects under ingestion_date=2026-11-05
Lake and ClickHouse347,578 rows in 6 files and in silver.enriched, equal for every tag
ReconciliationOK for the 6 tags; 6 files; 0 SHA-256 mismatches; 0.4 s
Rebuild of ClickHouse from the lake347,578 rows in about 1.0 s
TTL counted from purchased_at0 of 99,433 orders would remain
Dimensionsdim_customer 99,441, dim_seller 3,095, dim_product 32,951, dim_date 1,096
Fact and aggregatefact_order_item 112,642; agg_sales_month_region 107
Question96,470 delivered orders; North 1,796 and Southeast 66,193 (2.71 %) in the three sources
Times of the question0.002 s from the aggregate, 0.06 s from the fact, 0.47 s in DuckDB over the lake

17. Recurring mistakes of agents

The traps below were found while the lab was rehearsed with the same prompts on 05/11/2026, and the prompts already carry the corresponding adjustments. Most of them pass a superficial test and are caught only by a count, by the type of a column or by one specific row, which is why each review box asks for a number.

Reading the files

The first group of mistakes happens before any transformation. An agent that lets DuckDB or pandas detect the types of the CSV columns reads the zip prefixes as integers, so the 23,995 customer prefixes and 1,027 seller prefixes without the leading zero stay wrong and the ones that had it lose it; for this reason prompt 01 asks to read every column as text and to keep zip_prefix as a string of five characters. An agent that opens the translation file with the plain encoding utf-8 receives the header product_category_name, with the byte order mark in front, and the join of the categories either fails or silently leaves every product untranslated. An agent that splits lines on commas breaks on the fields that the source quoted.

Time zones and offsets

The timestamps of Olist have no offset, and the tempting conversion appends -03:00 to every one of them. The conversion is wrong for the summer months of 2016 to 2018, when Brazil was at -02:00, and the error moves the orders of the last hour of a month into the next month of the answer. The correct conversion interprets each timestamp in the zone America/Sao_Paulo, which knows the history of daylight saving time, and writes the offset of that date, as in "2017-12-08T13:30:29-02:00". DuckDB returns values of type TIMESTAMPTZ to Python only when the package pytz is installed, and without it the load fails when it converts data_ingestao. In ClickHouse, the JSON type infers dates from strings by default, so every insert must use input_format_try_infer_dates = 0 and input_format_try_infer_datetimes = 0, or purchased_at becomes a timestamp without its offset.

Versions and connections

In DuckDB 2.0 the relations returned by con.sql(...) no longer have the method fetchone(), which agents trained on older code still write, and the call must be con.execute(...).fetchone(). ClickHouse 26.8 enables async_insert by default, which makes an insert return before the rows are visible, so a count right after the load can return fewer rows than were sent, and async_insert = 0 makes each insert synchronous. The s3() function runs inside the ClickHouse container, where localhost:9000 is the container itself, so the agent that copies the endpoint of Python into the SQL receives a connection error; the address from inside the container is http://rustfs:9000, the value of S3_ENDPOINT_FROM_CLICKHOUSE. RustFS and the native port of ClickHouse both use port 9000, so only the HTTP port 8123 of ClickHouse is published, and an agent that tries the native protocol on the host finds RustFS instead. DuckDB reaches RustFS only with URL_STYLE 'path' and USE_SSL false, and the secret must be created at the start of each session with CREATE OR REPLACE SECRET, never with CREATE PERSISTENT SECRET, which would store the password in the profile of the user.

Reading the TTL and parsing the paths

The reconciliation must read the window from the TTL of the table, and SHOW CREATE TABLE writes it as toIntervalYear(1), not as INTERVAL 1 YEAR, so a regular expression written for the text of the DDL finds no window. In a query over the whole of silver.enriched, parseDateTimeBestEffort(data_linha.purchased_at) fails on the rows of the other tags, where the path is empty; the query must filter the tag in a subquery before parsing, or use the variant parseDateTimeBestEffortOrNull.

The star

An agent that refreshes the fact with SYSTEM REFRESH VIEW gold.fact_order_item and then queries the aggregate reads the previous result, because DEPENDS ON orders only the scheduled refreshes; the sequence of section 12 refreshes and waits for each view in order. An agent that answers the question with count() over the fact counts items, 112,642 for 99,433 orders, and overstates every month; a sale is an order, counted with uniqExact(order_id). An agent that proposes an incremental materialized view for the fact produces a target that doubles at each run, for the reasons of section 12.

18. From the lab to the Data Ingestion Structure

The artifact Data Ingestion Structure, delivered as Data_Ingestion.md with weight 6 on Adalove, asks each group for an ETL process that extracts data from Object Storage and loads it into an OLAP database or Data Warehouse, together with a UML component diagram of the flow from the collection of the data to the DataApp. The lab of this lesson is a worked example of the same structure over the real data of Olist, and the group repeats the reasoning over the data of the partner.

Criterion of the artifactWhat the lab showsWhat the group produces
Efficient extraction from Object StorageDuckDB reading the Bronze over httpfs, with Hive partitionsthe extraction of the partner files, with the layout of the keys and the measured time
Transformations that ensure qualitynormalisation, aggregation, derivation, deduplication and quarantine with a reasonthe rules for the defects of the partner data and the accounting of rows
Correct loading into the OLAP databaselake first, ClickHouse from the lake, manifest and reconciliation, star in goldthe load into the chosen warehouse, with the evidence that the counts agree
Clear UML component diagramthe components and interfaces of section 2a diagram from the collection to the DataApp
Detailed documentationcontract, ADR, model of the star and prompt log written by the agentthe contract of the Silver layer, the ADR with the retention as a hypothesis and the decisions of the group

The component diagram shows the parts of the system and the interfaces through which they communicate, without the internal logic of each part. The skeleton below, in PlantUML, follows the architecture of the lab and can serve as a starting point, as long as the group replaces the source, the warehouse and the DataApp with those of its project.

PlantUML · starting point for the component diagram
@startuml
title Data ingestion of the Olist case

package "Source" {
  [Olist CSV export] as SRC
}

node "RustFS (Object Storage)" {
  [Bronze bucket] as BRONZE
  [Silver lake] as LAKE
}

component "load_bronze.py" as LB
component "Enrichment (DuckDB)" as ENRICH
component "Hybrid load" as LOAD
database "ClickHouse silver.enriched" as CH
database "ClickHouse gold (star)" as GOLD
component "DataApp" as APP

interface "S3 API :9000" as S3
interface "HTTP :8123" as HTTP

SRC --> LB : CSV files
LB ..> S3 : writes Bronze unchanged
BRONZE - S3
LAKE - S3
ENRICH ..> S3 : reads Bronze
LOAD ..> S3 : writes Parquet and manifest
LOAD ..> HTTP : loads lake files with s3()
CH - HTTP
CH --> GOLD : views and refreshable materialized views
ENRICH --> LOAD
APP ..> HTTP : tactical queries on gold
APP ..> S3 : strategic queries with DuckDB
@enduml

By the end of the session the class will have seen the whole structure working on the classroom computer, with the counts of the rehearsal as the reference. During the week, before Lesson 6 on 10/11, each group writes the contract of the enriched table for the partner data, decides its tags, records the retention and its clock as a hypothesis with an owner, writes one business question with the definition of each of its words and draws the component diagram. Lesson 6 will build the cubes and marts of the Gold layer over this Silver layer.

19. Glossary

Additive measure
Measure that can be summed across every dimension, such as the price of the order items.
Columnar storage
Storage in which the values of each column are kept together, so that analytical queries read only the columns they use.
Conformed dimension
Dimension with the same keys, attributes and meaning in every fact table that uses it, which allows separate marts to be compared.
data_ingestao
Column of the enriched table with the moment at which the record entered the platform, derived from the partition of the Bronze.
data_linha
Column of the enriched table with the normalised and derived fields of one record, in JSON.
data_tag
Column of the enriched table with the source, the entity and the version of the record, or quarantine.v1.
Dimension
Table of descriptive attributes of a context of the business process, used to filter and group the facts.
Distinct count
Count of different values of a key, such as uniqExact(order_id), which is not additive in general.
Fact table
Table with one row per measurement of a business process at the declared grain, with keys to the dimensions and numerical measures.
Grain
Exact meaning of one row of a fact table; in the case, one order item.
Incremental materialized view
Insert trigger of ClickHouse that runs a query over each block inserted into one source table and appends the result to a target table.
Manifest
JSON file written at the end of each load with the keys, rows, bytes and SHA-256 of every lake file, the rows per tag, the times and the status.
MergeTree
Family of table engines of ClickHouse that writes immutable sorted parts and merges them in the background.
MPP
Massively parallel processing: execution of a query in parallel across nodes that each hold a slice of the data, as in Redshift.
Reconciliation
Comparison of the counts of the lake inside the window with the counts of ClickHouse, per tag, plus the check of the SHA-256 of the lake files.
Refreshable materialized view
View of ClickHouse that recomputes its whole query on a schedule and swaps the stored result atomically.
Self-service analytics
Analysis done directly by business users over documented data, without a request to the engineering team for each question.
Star schema
Dimensional model with a fact table at the centre and one denormalised table per dimension around it.
TTL
Time to live: rule of a ClickHouse table that removes rows after a declared interval, counted from a declared column.
View
Stored query that the database substitutes into every query that reads it, computed at query time.

20. Checklist

  • The three columns are named exactly data_ingestao, data_linha and data_tag.
  • data_ingestao is derived from the Bronze, so that a rerun gives the same values, and it is not the date of the order.
  • Every tag of the contract has its fields, its key of deduplication and its rules.
  • Every zip prefix has five characters and stayed String in ClickHouse.
  • Every timestamp carries the offset of its date, -03:00 or -02:00.
  • data_linha is of type JSON in ClickHouse and purchased_at stayed String.
  • The load writes the lake, then ClickHouse from the lake files, then the manifest.
  • After Step 02, the lake and ClickHouse have 347,578 rows and the same count for every tag.
  • The reconciliation reads the window from the TTL and reports OK for every tag, with 0 SHA-256 mismatches.
  • The ADR marks the one-year retention and its clock as a business hypothesis and names who decides them.
  • The dimensions are views, and the fact and the aggregate are refreshable materialized views.
  • A sale is a delivered order counted with uniqExact(order_id), in the month of purchased_at and the region of the customer.
  • The aggregate, the fact and DuckDB over the lake give North 1,796 and Southeast 66,193.

21. References and self-study

Self-study

MaterialTimeWhy
DWH Concepts: Basics & Hands-On Tutorial (Exasol)40 minreview of the concepts of the warehouse, with practical examples
What is Data Mart | Data Warehouse Tutorial For Beginners (video)30 minpreparation for the data marts of Lesson 6
Recent Developments in Data Warehousing (Communications of the AIS, vol. 8)60 min, optionalhistorical view of the field and of its architectures

References

  • AMAZON WEB SERVICES. Amazon Redshift Database Developer Guide: distribution styles, sort keys, materialized views, Redshift Spectrum and the SUPER data type. Available at: docs.aws.amazon.com/redshift.
  • CLICKHOUSE. MergeTree table engine, Manipulating data with TTL, JSON data type, Incremental materialized view and Refreshable materialized view. ClickHouse documentation. Available at: clickhouse.com/docs.
  • CODD, E. F. A relational model of data for large shared data banks. Communications of the ACM, v. 13, n. 6, p. 377-387, 1970.
  • DUCKDB FOUNDATION. DuckDB documentation: S3 API support, secrets manager, Parquet and JSON. Available at: duckdb.org/docs.
  • INMON, W. H. Building the Data Warehouse. 4th ed. Indianapolis: Wiley, 2005.
  • KIMBALL, R.; ROSS, M. The Data Warehouse Toolkit: The Definitive Guide to Dimensional Modeling. 3rd ed. Indianapolis: Wiley, 2013.
  • LINSTEDT, D.; OLSCHIMKE, M. Building a Scalable Data Warehouse with Data Vault 2.0. Waltham: Morgan Kaufmann, 2015.
  • OLIST. Brazilian E-Commerce Public Dataset by Olist. MIT licence. Available at: github.com/olist/work-at-olist-data; also published on Kaggle.
  • REIS, J.; HOUSLEY, M. Fundamentals of Data Engineering. Sebastopol: O'Reilly, 2022.
  • WATSON, H. J. Recent developments in data warehousing. Communications of the Association for Information Systems, v. 8, article 1, 2002.