The tests in the previous lesson protect the code. But a flawless pipeline can produce false figures if the data it receives is wrong, and NovaMarket's data has been wrong from day one: repeated orders, empty amounts, customers without a province. Until now you have been discovering and fixing these one by one. A mature platform does not discover them: it measures them, every night and automatically.
This lesson has two halves. In the first, technical one, you will learn to express quality as rules declared in code and you will write quality.py, which evaluates fifteen rules on your lake, saves the result and stops the pipeline when something serious fails. In the second, organisational one, you will look at data governance: who decides what is correct, who answers for each table and where it is documented. It fulfils three pending promises: the catalogue "for people" (lesson 02-04), systematic quality rules (03-06) and the governance of metric definitions (04-05).
What data quality is and how much it costs not to have it
Data has quality when it is fit for the use you want to make of it. The definition is deliberately relative: a null device in 0.5% of events does not affect the conversion funnel, but it would invalidate a study of behaviour by device type if that percentage were 30%.
The cost of poor quality follows a well-known rule: the later a defect is detected, the more expensive it is. At NovaMarket:
| Where it is detected | Example with the 100 duplicated orders | Cost |
|---|---|---|
| At ingestion | A uniqueness rule raises a warning when bronze is loaded | Minutes |
| In transformation | Silver deduplication removes them | Already planned for |
| In analysis | Marc notices that sales "don't tally" with accounting | Hours of investigation |
| In the decision | Irene presents the committee with sales inflated by 0.5% | The credibility of the whole team |
The last row is the one that matters. When an executive finds an error in a report, they stop trusting all the reports. Trust in data takes months to earn and one meeting to lose.
The dimensions of quality
"The data is wrong" is not a diagnosis. To measure quality, it is broken down into dimensions, each with its own question. In lesson 01-03 you checked four of them with plain Python; these are the six usual ones, with the real defects in your files:
| Dimension | Question | Example in NovaMarket's data |
|---|---|---|
| Completeness | Is any mandatory value missing? | 200 orders with an empty total_amount; 20 customers without a province; 1,000 events without a device |
| Uniqueness | Are there repeated records? | 100 duplicated rows in orders.csv; 500 in web_events.json |
| Validity | Does each value respect its format and its domain? | status must be one of four values; total_amount, greater than zero |
| Accuracy | Does the value match reality? | That the amount recorded is the one the customer actually paid |
| Consistency | Does the data agree with itself? | total_amount = sum of its lines; every customer_id in an order exists in customers; purchase events do not match rows in orders |
| Timeliness (freshness) | Is it available on time? | Yesterday's orders, loaded before 07:00 |
Three observations:
- A null is not always a defect.
customer_idis null in 30% of sessions because they are anonymous visitors, andproduct_idis null in searches. These are legitimate nulls: they have a business meaning. A completeness rule on those columns would be a mistake. - Accuracy is the hardest to measure, because it requires comparison with an external source (the bank statement, the warehouse delivery note). The others are checked with the data itself.
- Consistency across systems reveals design flaws. The fact that
purchaseevents do not matchordersis a known limitation of the course data; in a real company it would be the first finding of a quality audit.
Quality rules as code: quality.py
The idea: declare, don't program
The validate_load.py script from lesson 03-06 checked four things with four if blocks. It works, but it does not scale: with a hundred checks it would be unreadable, and it only says "good" or "bad", without measuring how much.
The alternative is to separate what is required from how it is checked. Each rule is written as data (a dictionary) with its table, its dimension, its type, a pass threshold and a severity. A single engine goes through them and evaluates them all. Adding a rule means adding a dictionary, and the list can be reviewed with someone from the business without them having to read Spark.
Two design decisions before the code:
- Threshold. The minimum percentage of rows that must pass the rule. In silver it is usually 100%. In bronze a tolerable level is set: we know that around 0.5% of duplicates arrive and that silver removes them; what we want to detect is the day 10% arrive.
- Severity. A failed rule with severity
errorstops the pipeline; one with severitywarningis logged and reviewed, but lets the pipeline continue.
The script
Create ~/novamarket/quality.py:
"""Measures the quality of the lake's data with declarative rules.
Usage: python quality.py DATE
DATE (YYYY-MM-DD) is the day of the check. Saves the report in
gold/daily_quality/date=DATE and exits with code 1 if any rule
with severity "error" falls below its threshold.
"""
import sys
from datetime import date
from pathlib import Path
from pyspark.sql import SparkSession
from pyspark.sql import functions as F
LAKE = Path.home() / "novamarket" / "lake"
BRONZE, SILVER, GOLD = LAKE / "bronze", LAKE / "silver", LAKE / "gold"
EVENTS_SCHEMA = ("event_id STRING, customer_id BIGINT, session_id STRING, event_type STRING, "
"product_id BIGINT, event_time TIMESTAMP, device STRING")
# --- The rules: WHAT is required, not HOW it is checked --------------------
# type: not_null | unique | condition (SQL expression that must be true)
# | reference (the value exists in another table) | freshness (maximum delay in days)
# threshold: minimum percentage of rows that must pass the rule
RULES = [
# Bronze: what arrives is measured. Known defects warn, they do not stop.
{"rule": "order_id_unique", "table": "bronze.orders", "dimension": "uniqueness",
"type": "unique", "column": "order_id", "threshold": 99.0, "severity": "warning"},
{"rule": "amount_present", "table": "bronze.orders", "dimension": "completeness",
"type": "not_null", "column": "total_amount", "threshold": 98.0, "severity": "warning"},
{"rule": "province_present", "table": "bronze.customers", "dimension": "completeness",
"type": "not_null", "column": "province", "threshold": 95.0, "severity": "warning"},
{"rule": "event_id_unique", "table": "bronze.web_events", "dimension": "uniqueness",
"type": "unique", "column": "event_id", "threshold": 99.0, "severity": "warning"},
{"rule": "device_present", "table": "bronze.web_events", "dimension": "completeness",
"type": "not_null", "column": "device", "threshold": 99.0, "severity": "warning"},
# Silver: what the analyses consume. Nothing is tolerated here.
{"rule": "order_id_unique", "table": "silver.orders_complete", "dimension": "uniqueness",
"type": "unique", "column": "order_id", "threshold": 100.0, "severity": "error"},
{"rule": "amount_present", "table": "silver.orders_complete", "dimension": "completeness",
"type": "not_null", "column": "total_amount", "threshold": 100.0, "severity": "error"},
{"rule": "amount_positive", "table": "silver.orders_complete", "dimension": "validity",
"type": "condition", "expression": "total_amount > 0",
"threshold": 100.0, "severity": "error"},
{"rule": "status_valid", "table": "silver.orders_complete", "dimension": "validity",
"type": "condition",
"expression": "status IN ('pending', 'shipped', 'delivered', 'returned')",
"threshold": 100.0, "severity": "error"},
{"rule": "customer_exists", "table": "silver.orders_complete", "dimension": "consistency",
"type": "reference", "column": "customer_id", "ref_table": "silver.customers",
"threshold": 100.0, "severity": "error"},
{"rule": "orders_up_to_date", "table": "silver.orders_complete", "dimension": "freshness",
"type": "freshness", "column": "order_date", "max_days": 1,
"threshold": 100.0, "severity": "error"},
{"rule": "event_id_unique", "table": "silver.web_events", "dimension": "uniqueness",
"type": "unique", "column": "event_id", "threshold": 100.0, "severity": "error"},
{"rule": "date_consistent", "table": "silver.web_events", "dimension": "consistency",
"type": "condition", "expression": "date = to_date(event_time)",
"threshold": 100.0, "severity": "error"},
{"rule": "device_present", "table": "silver.web_events", "dimension": "completeness",
"type": "not_null", "column": "device", "threshold": 99.0, "severity": "warning"},
{"rule": "province_present", "table": "silver.customers", "dimension": "completeness",
"type": "not_null", "column": "province", "threshold": 99.0, "severity": "warning"},
]
def load_tables(spark):
"""Reads the tables to be evaluated. In bronze, without inferring types."""
return {
"bronze.orders": spark.read.csv(str(BRONZE / "orders"), header=True),
"bronze.customers": spark.read.csv(str(BRONZE / "customers"), header=True),
"bronze.web_events": spark.read.schema(EVENTS_SCHEMA).json(str(BRONZE / "web_events")),
"silver.orders_complete": spark.read.parquet(str(SILVER / "orders_complete")),
"silver.web_events": spark.read.parquet(str(SILVER / "web_events")),
"silver.customers": spark.read.parquet(str(SILVER / "customers")),
}
def evaluate(rule, tables, day):
"""Returns (rows evaluated, rows failing) for a rule."""
df = tables[rule["table"]]
total = df.count()
rule_type = rule["type"]
if rule_type == "not_null":
failing = df.where(F.col(rule["column"]).isNull()).count()
elif rule_type == "unique":
failing = total - df.select(rule["column"]).distinct().count()
elif rule_type == "condition":
# coalesce: if the expression yields NULL (it cannot be evaluated), it counts as failed
failing = df.where(~F.coalesce(F.expr(rule["expression"]), F.lit(False))).count()
elif rule_type == "reference":
keys = tables[rule["ref_table"]].select(rule["column"]).distinct()
failing = df.join(keys, on=rule["column"], how="left_anti").count()
elif rule_type == "freshness":
latest = df.agg(F.max(F.to_date(rule["column"]))).first()[0]
delay = (date.fromisoformat(day) - latest).days
total, failing = 1, int(delay > rule["max_days"])
else:
raise ValueError(f"Unknown rule type: {rule_type}")
return total, failing
if __name__ == "__main__":
if len(sys.argv) != 2:
sys.exit(__doc__)
day = date.fromisoformat(sys.argv[1]).isoformat()
spark = (
SparkSession.builder.master("local[*]").appName(f"quality_{day}")
.config("spark.sql.sources.partitionOverwriteMode", "dynamic")
.getOrCreate()
)
spark.sparkContext.setLogLevel("ERROR")
tables = {name: df.cache() for name, df in load_tables(spark).items()}
results = []
for rule in RULES:
total, failing = evaluate(rule, tables, day)
pct = round(100 * (total - failing) / total, 2)
if pct >= rule["threshold"]:
result = "OK"
else:
result = "ERROR" if rule["severity"] == "error" else "WARNING"
results.append((rule["table"], rule["rule"], rule["dimension"], total,
failing, pct, rule["threshold"], rule["severity"], result))
report = spark.createDataFrame(
results,
"table STRING, rule STRING, dimension STRING, total BIGINT, failing BIGINT, "
"pct_passing DOUBLE, threshold DOUBLE, severity STRING, result STRING",
).withColumn("date", F.lit(day).cast("date"))
target = str(GOLD / "daily_quality")
report.coalesce(1).write.mode("overwrite").partitionBy("date").parquet(target)
report.drop("date", "severity").show(len(results), truncate=False)
warnings = sum(1 for r in results if r[-1] == "WARNING")
errors = sum(1 for r in results if r[-1] == "ERROR")
print(f"Quality check for {day}: {len(results)} rules, "
f"{warnings} warnings, {errors} errors. Report in {target}")
spark.stop()
if errors:
sys.exit(1)How it works
RULESis the heart of the script, and it contains no logic. Each dictionary says which table it applies to, which dimension it measures and how demanding it is. The bronze rules are warnings with a margin; the silver ones, errors with no tolerance, except for two columns in which a small percentage of nulls is knowingly accepted.load_tablesreturns a dictionary that maps each logical name (bronze.orders) to its DataFrame. The bronze CSV is read withoutinferSchema: all the columns are text and an empty field becomes a null, which is exactly what we want to count.evaluateis the engine. For each rule type it calculates how many rows fail it:not_nullcounts the nulls in the column.uniquesubtracts the distinct keys from the total: the result is the surplus rows.conditionevaluates an SQL expression withF.exprand counts the rows in which it is not true. Thecoalescetreats the case in which the expression returns null as a failure.referenceuses the left anti join from lesson 03-03: the rows whose key does not exist in the reference table.freshnesscompares the most recent date in the table with the day of the check.
.cache()keeps each table in memory, because several rules go through it (lesson 03-04).- The result is written to
gold/daily_quality, partitioned bydateand with dynamic overwriting: repeating the check for a day replaces its partition, as indaily_load.py. That way quality becomes a time series that can be queried and plotted just like any KPI. sys.exit(1)communicates the failure to the orchestrator. In thenovamarket_dailyDAG, this task would take the place ofvalidate_load, or be added just before it: if quality does not pass, the gold tables are not published.
Running it
+----------------------+-----------------+------------+------+-------+-----------+---------+-------+ |table |rule |dimension |total |failing|pct_passing|threshold|result | +----------------------+-----------------+------------+------+-------+-----------+---------+-------+ |bronze.orders |order_id_unique |uniqueness |20100 |100 |99.5 |99.0 |OK | |bronze.orders |amount_present |completeness|20100 |201 |99.0 |98.0 |OK | |bronze.customers |province_present |completeness|1000 |20 |98.0 |95.0 |OK | |bronze.web_events |event_id_unique |uniqueness |200500|500 |99.75 |99.0 |OK | |bronze.web_events |device_present |completeness|200500|1003 |99.5 |99.0 |OK | |silver.orders_complete|order_id_unique |uniqueness |20000 |0 |100.0 |100.0 |OK | |silver.orders_complete|amount_present |completeness|20000 |0 |100.0 |100.0 |OK | |silver.orders_complete|amount_positive |validity |20000 |0 |100.0 |100.0 |OK | |silver.orders_complete|status_valid |validity |20000 |0 |100.0 |100.0 |OK | |silver.orders_complete|customer_exists |consistency |20000 |0 |100.0 |100.0 |OK | |silver.orders_complete|orders_up_to_date|freshness |1 |0 |100.0 |100.0 |OK | |silver.web_events |event_id_unique |uniqueness |200000|0 |100.0 |100.0 |OK | |silver.web_events |date_consistent |consistency |200000|0 |100.0 |100.0 |OK | |silver.web_events |device_present |completeness|200000|1000 |99.5 |99.0 |OK | |silver.customers |province_present |completeness|1000 |20 |98.0 |99.0 |WARNING| +----------------------+-----------------+------------+------+-------+-----------+---------+-------+ Quality check for 2026-07-01: 15 rules, 1 warnings, 0 errors. Report in /home/your_user/novamarket/lake/gold/daily_quality
All the defects you have been finding during the course appear, measured, on a single screen:
- The 100 duplicated orders and the 500 duplicated events are in bronze and have disappeared in silver.
- There are 201 empty amounts in bronze, not 200. This is not a mistake: 200 orders have no amount, and one of them is also among the duplicates, so 201 rows are affected. For the same reason there are 1,003 null devices in bronze and 1,000 in silver. It is a good reminder that you should deduplicate before counting.
- Not a single null amount remains in
silver/orders_complete, thanks to the rebuild in lesson 03-03. - The only warning is for the 20 empty provinces, which nobody has corrected:
silver/customerspasses at 98% a rule that requires 99%. The pipeline carries on, but the warning will keep appearing every night until someone decides what to do. That is what the second half of the lesson is about.
Watching the check fail
Run the check as if it were 5 July. The latest orders are from 30 June, so the data would have gone five days without being updated:
|silver.orders_complete|orders_up_to_date|freshness |1 |1 |0.0 |100.0 |ERROR | ... Quality check for 2026-07-05: 15 rules, 1 warnings, 1 errors. Report in ... Exit code: 1
The freshness rule fails and the script ends with code 1: an orchestrator would stop the pipeline here and raise the alarm. The gold/daily_quality table now has two partitions, one for each day of checking; it is the start of the history.
What to do with invalid records: quarantine
Measuring is not enough: you have to decide what happens to the rows that fail a rule. There are four policies, and the choice depends on the defect:
| Policy | What it consists of | When it is appropriate | Example at NovaMarket |
|---|---|---|---|
| Reject the load | If the batch fails, nothing is loaded | Massive or structural defects | An events file arrives with 40% duplicates |
| Discard | The defective rows are removed | The defect carries no information | Exact duplicates |
| Repair | It is corrected with a documented rule | The correct value can be deduced | The amounts rebuilt from the lines, flagged with amount_rebuilt |
| Quarantine | They are set aside in a zone of their own, with the reason, to be reviewed | They cannot be repaired and should not be lost | Orders without an amount and without lines |
Quarantine has a decisive advantage over discarding: nothing disappears silently. The rows set aside can be counted, reviewed with the team that produced them and reinstated once they are corrected. This script illustrates it with the bronze orders. Create ~/novamarket/quarantine.py:
"""Splits the bronze orders into valid and quarantined, recording the reason."""
from pathlib import Path
from pyspark.sql import SparkSession, Window
from pyspark.sql import functions as F
LAKE = Path.home() / "novamarket" / "lake"
spark = SparkSession.builder.master("local[*]").appName("quarantine").getOrCreate()
spark.sparkContext.setLogLevel("ERROR")
orders = spark.read.csv(str(LAKE / "bronze" / "orders"), header=True)
# Sequence number of each row within its order_id: the 2nd and later ones are repetitions
repetition = F.row_number().over(Window.partitionBy("order_id").orderBy("order_date"))
flagged = (
orders
.withColumn("n", repetition)
.withColumn("reason", F.concat_ws(
",",
F.when(F.col("n") > 1, "duplicate"),
F.when(F.col("total_amount").isNull(), "empty_amount"),
))
.drop("n")
)
valid = flagged.where(F.col("reason") == "").drop("reason")
quarantined = flagged.where(F.col("reason") != "")
target = str(LAKE / "quarantine" / "orders")
quarantined.coalesce(1).write.mode("overwrite").parquet(target)
print("Valid rows: ", valid.count())
print("Quarantined rows:", quarantined.count())
quarantined.groupBy("reason").count().orderBy("reason").show()
spark.stop()row_number()over a window byorder_idnumbers the rows of each order (lesson 03-03). The first one is kept; the following ones are repetitions.F.when(condition, text)returns the text if the condition holds and null otherwise.concat_ws(",", …)joins the non-null texts separated by commas: a row can accumulate several reasons, and a row with none is left with the empty string.- Only the quarantine is written, in a new zone of the lake,
lake/quarantine/orders. The script does not touch silver.
Valid rows: 19800 Quarantined rows: 300 +--------------------+-----+ | reason|count| +--------------------+-----+ | duplicate| 99| |duplicate,empty_a...| 1| | empty_amount| 200| +--------------------+-----+
There is the row that explained the 201: a duplicate that also has no amount. In the course the choice was to repair the amounts rather than set them aside, because the order lines allowed them to be rebuilt exactly; quarantine would have been the right option if they did not exist. What is never acceptable is the fifth policy, the most widespread: doing nothing and hoping nobody notices.
Tools, data contracts and observability
Quality tools
quality.py is about 140 lines long and shows the mechanism. In a real project you do not write the engine: you use a tool that already comes with dozens of rule types, reports and integration with orchestrators.
| Tool | Approach | When it fits |
|---|---|---|
| Great Expectations | Python library; rules are called expectations and generate readable documentation | Python teams who want rich validations inside their pipelines |
| Soda | Rules declared in YAML with its own checks language | Those who prefer configuration to code and want to involve non-programmers |
| Deequ (and its PyDeequ variant) | Library on top of Spark, designed for large volumes; it calculates metrics and suggests rules | Validating very large tables inside Spark jobs |
| dbt tests | Checks (unique, not_null, accepted_values, relationships) declared alongside each SQL model |
ELT platforms that already transform with dbt (lesson 03-06) |
| Table format constraints | Conditions that Delta or Iceberg themselves enforce on write | Minimum guarantees that do not depend on someone running a check |
Notice that dbt's four basic tests are exactly the unique, not_null, condition and reference types in your script. Tools change; the dimensions are always the same.
Data contracts
The rules above are written by whoever consumes the data, defensively. A data contract reverses the relationship: it is an explicit agreement in which the team that produces a dataset commits to a schema, quality guarantees and a freshness, and to giving notice before changing them. It is usually written in a versioned file:
# Data contract (illustrative): web_events
dataset: web_events
owner: web-team
consumers: [data-engineering, analytics]
schema:
- {name: event_id, type: string, required: true, unique: true}
- {name: customer_id, type: bigint, required: false, note: "null = anonymous visitor"}
- {name: event_type, type: string, required: true,
values: [product_view, search, add_to_cart, purchase]}
- {name: event_time, type: timestamp, required: true}
quality:
max_duplicates_pct: 0.5
freshness: "events for day D available before 02:00 on day D+1"
changes: "breaking changes are announced 30 days in advance"With a contract, the day the web team wants to rename event_type they will know whom it affects and what notice period they must respect. Without one, Laura will find out when the load fails.
Data observability
Rules detect the problems that someone was able to anticipate. Data observability continuously and automatically monitors general signals from every table in order to detect the unforeseen ones too:
- Freshness: when was it last updated?
- Volume: is the number of rows the usual one? (40 million events a day, and today 3 million.)
- Schema: has any column appeared, disappeared or changed type?
- Distribution: has the percentage of nulls or the mean of a column drifted from its history?
- Lineage: if this table fails, which others are affected?
With gold/daily_quality you already have the raw material: a daily series of percentages. Comparing today's value with that of the last thirty days is the simplest form of anomaly detection.
Data governance: what it is and who exercises it
The warning about the 20 empty provinces raises questions that no script answers: who should correct them? Is it mandatory for a customer to have a province? Who decides that 99% is the right threshold? Data governance is the set of people, rules and processes through which an organisation decides who can do what with which data, and who answers for it. Quality is its most visible result, but it also covers definitions, access, the life cycle and regulatory compliance.
Roles
| Role | Responsibility | At NovaMarket |
|---|---|---|
| CDO (chief data officer, head of data) | The company's data strategy; chairs governance | Irene |
| Data owner | Business executive who answers for a data domain: defines its meaning, its quality rules and who has access | The sales director for orders; the marketing director for customers |
| Data steward | The person who looks after the data day to day: maintains the definitions, reviews quality warnings, answers questions | Marc, for the sales data |
| Data custodian (technical) | The person who operates the systems that store and move the data | Laura |
| Consumers | Use the data in line with the policies; report the defects they see | Analysts, product, finance |
The essential distinction is between ownership and technical custody. Laura can repair a pipeline, but it is not her place to decide whether a "returned" order counts as a sale: that decision belongs to the business. Governance that rests solely with the technical team ends up as a set of rules that nobody in the business recognises as their own.
The provinces warning now has a path: it reaches Marc, the data steward, who takes it to the owner of customers; the owner decides that the province is mandatory in the sign-up form from now on (the source is corrected) and that the 20 older customers are to be completed from their delivery address (the data is repaired). The rule then goes up to severity error.
Policies
Decisions are recorded in policies: short, enforceable rules. The usual ones deal with quality (which minimum rules a table must pass to be published in gold), definitions (every official metric has a definition card and an owner, as you saw in lesson 04-05), access (who can see what), retention (how long each piece of data is kept) and changes (how a schema modification is announced). A policy that cannot be checked automatically tends to be breached; that is why the best ones end up turned into code, like your rules.
The catalogue for people: business glossary and data dictionary
In lesson 02-04 you saw the technical catalogue: the registry that lets engines know which tables exist and where they are. The catalogue for people was left pending, the one that answers "what data do we have, what does it mean and can I trust it?". It has two basic parts.
The business glossary defines the terms, regardless of which table they are in:
| Term | Definition | Owner |
|---|---|---|
| Order | A purchase confirmed by a customer, with one or more lines. Includes returned orders | Sales management |
| Revenue | Sum of total_amount for the orders whose status is not returned |
Finance management |
| Session | A set of web events with the same session_id |
Product |
| Conversion rate | Sessions with a purchase divided by total sessions, according to gold/daily_funnel |
Product |
The data dictionary describes each table, column by column. This is the one for silver/orders_complete:
| Field | Content |
|---|---|
| Table | silver/orders_complete |
| Description | One order per row, deduplicated and with the full amount. It is the official source for all order analyses |
| Owner / steward | Sales management / Marc |
| Source | silver/orders and silver/order_lines, via rebuild_amounts.py |
| Update | Daily, before 07:00 |
| Quality | Rules in quality.py; results in gold/daily_quality |
| Column | Type | Nulls | Description | Sensitivity |
|---|---|---|---|---|
order_id |
integer | No | Unique identifier of the order | Internal |
customer_id |
integer | No | Customer who placed the order; key of customers |
Personal data (identifier) |
order_date |
date and time | No | Time of confirmation, mainland Spain time | Internal |
total_amount |
decimal | No | Amount in euros, taxes included; sum of the lines | Internal |
status |
text | No | pending, shipped, delivered or returned |
Internal |
channel |
text | No | web or app |
Internal |
amount_rebuilt |
boolean | No | True if the amount was missing at source and was calculated from the lines (200 orders) | Internal |
Keeping this in a spreadsheet works with ten tables. With hundreds, catalogue platforms are used: they read the schemas automatically, show the lineage, allow searching and let owners and stewards add descriptions and tags. Notable open-source options are DataHub and OpenMetadata; among those built into platforms, Unity Catalog, and each cloud offers its own (lesson 06-04). The tool does not solve the problem on its own: a catalogue with every description empty is just a list of tables.
Lineage
Lineage is the map of a piece of data's journey: which tables each table comes from and which processes transform them. This is the lineage of gold/daily_kpis, reconstructed from the course scripts:
flowchart LR
BE[bronze/web_events] -->|daily_load.py| PE[silver/web_events]
PE -->|daily_load.py| OE[gold/daily_funnel]
BP[bronze/orders] -->|build_lake.py| PP[silver/orders]
BL[bronze/order_lines] -->|build_lake.py| PL[silver/order_lines]
PP -->|rebuild_amounts.py| PC[silver/orders_complete]
PL -->|rebuild_amounts.py| PC
OE -->|compute_kpis.py| K[gold/daily_kpis]
PC -->|compute_kpis.py| K
K --> PANEL[Irene's dashboard]
Lineage is read in both directions, and each one answers a different question:
- Backwards (root cause analysis). The conversion rate on the dashboard looks odd. Where does it come from? From
gold/daily_funnel, which comes fromsilver/web_events, which comes from the bronze JSON. Now you know where to look. - Forwards (impact analysis). The web team is going to change the format of
event_time. What breaks? Everything hanging offbronze/web_events, all the way to Irene's dashboard.
Drawing it by hand, as here, is not sustainable: catalogue tools and some orchestrators extract it automatically from execution plans or from the SQL.
Classification, master data and data mesh
Classification by sensitivity. Governance labels each piece of data according to the damage its disclosure would cause, and that label determines how it is protected:
| Level | What it includes | Example at NovaMarket |
|---|---|---|
| Public | What anyone can see | The catalogue: products |
| Internal | Information for normal use within the company | gold/daily_kpis, gold/daily_funnel |
| Confidential | Personal data or data that is sensitive for the business | customers (name, province); web_events with customer_id |
| Restricted | Data whose access is kept to a minimum | Payment data, which is not part of the course lake |
The "Sensitivity" column of the data dictionary is where it is recorded. How each level is protected (permissions, encryption, pseudonymisation) and what the regulations require is the subject of Module 7.
Warning. The classification of personal data and the measures that apply to it have legal consequences. The tables in this lesson are a teaching example: in a real organisation they must be defined and reviewed by those responsible for regulatory compliance and data protection.
Master data management (MDM). Master data are the core entities shared by all systems: customers, products, suppliers. If the shop, the warehouse and accounting each keep their own product list with different codes, no join will ever come out right. Master data management establishes a single, reliable version of each entity (the "golden record") and the rules for maintaining it. In NovaMarket's lake, dim_customer and dim_product aim to be that reference for analysis.
Data mesh. As a company grows, a central data team that builds everything becomes a bottleneck. Data mesh is an organisational model that distributes responsibility: each business domain (sales, logistics, marketing) publishes and maintains its own datasets as products, with an owner, documentation, a contract and guaranteed quality, on a common platform and under shared governance rules. It is not a technology, and it cannot be bought. For a company the size of NovaMarket, with a team of three people, it would be premature; but the underlying idea, treating every published table as a product with an owner, can be applied from day one.
Common Mistakes and Tips
- Putting completeness rules on legitimate nulls. Before requiring a column to be non-null, ask what the null means. An empty
customer_idis an anonymous visitor, not a defect. - Counting defects without deduplicating. 201 rows without an amount are not 201 orders. Always state what you are counting.
- Setting every threshold to 100% with error severity. The pipeline will stop every night because of known defects and someone will end up disabling the check. Scale it: error for what invalidates the result, warning for the rest.
- Warnings nobody attends to. A warning without an owner is noise. Every rule must have someone it reaches and an expectation of what they will do.
- Always fixing downstream. Deduplicating in silver is fine; never telling the source system that it sends duplicates guarantees that it will keep doing so. The lasting fix is at the source.
- Repairing without leaving a trace. Every correction must be visible, like the
amount_rebuiltcolumn. An imputed value that looks original is an unintentional deception. - Confusing governance with bureaucracy. A committee that meets to approve documents governs nothing. Start with what hurts: an owner for every gold table and a definition for every KPI.
- Buying a catalogue before having anything to catalogue. The most expensive tool does not write the descriptions. A maintained dictionary in Markdown next to the code is worth more than an empty platform.
- Tip: when you add a table to gold, deliver it with three things: its quality rules, its entry in the dictionary and the name of its owner. If any of them is missing, it is not yet a gold table.
Exercises
Exercise 1: classifying defects
State which quality dimension each situation breaches and which policy you would apply (reject, discard, repair or quarantine):
- An order with an
order_datein the year 2062. - Order lines whose
product_iddoes not exist inproducts. - Yesterday's events file arrives at 11:00 instead of 02:00.
- A customer appears twice with the same name and a different
customer_id. - An order with
channelequal toWEB, in capitals.
Exercise 2: three new rules
Add three rules to quality.py, all with severity error and threshold 100, and run the check again for 1 July 2026:
- In
silver.order_lines, thequantitymust be greater than zero. - In
silver.order_lines, everyproduct_idmust exist insilver.products. - In
silver.web_events,event_typemust be one of the four permitted values.
You will need to register two more tables in load_tables.
Exercise 3: the dictionary entry for a gold table
Write the data dictionary entry for gold/daily_funnel: the general card and the table of columns. Include the caveat that any user should know before adding up the sessions column.
Solutions
Exercise 1
- Validity (outside the permissible range) and probably accuracy. Quarantine: the correct date cannot be deduced, and discarding it would lose a real sale.
- Consistency (referential integrity). Quarantine, and a warning to the owner of the catalogue: either the product is missing or the line is wrong.
- Timeliness. There are no records to deal with: the load is rejected (not launched) until the file arrives, and consumers are notified if the freshness commitment is breached.
- Uniqueness, in its hardest form: it is not an exact duplicate, but the same entity with two identifiers. It requires master data management; in the meantime, quarantine or a "possible duplicate" flag for manual review. It must not be merged automatically without an agreed rule.
- Validity (value outside the domain). Repair: normalising to lower case is a safe rule that can be documented.
Exercise 2
In load_tables, two entries are added to the dictionary:
"silver.order_lines": spark.read.parquet(str(SILVER / "order_lines")),
"silver.products": spark.read.parquet(str(SILVER / "products")),And at the end of RULES:
{"rule": "quantity_positive", "table": "silver.order_lines", "dimension": "validity",
"type": "condition", "expression": "quantity > 0",
"threshold": 100.0, "severity": "error"},
{"rule": "product_exists", "table": "silver.order_lines", "dimension": "consistency",
"type": "reference", "column": "product_id", "ref_table": "silver.products",
"threshold": 100.0, "severity": "error"},
{"rule": "event_type_valid", "table": "silver.web_events", "dimension": "validity",
"type": "condition",
"expression": "event_type IN ('product_view', 'search', 'add_to_cart', 'purchase')",
"threshold": 100.0, "severity": "error"},python quality.py 2026-07-01 now shows 18 rules; the three new ones give OK with 0 failures on 50,107, 50,107 and 200,000 rows, and the summary is still 1 warning and 0 errors. The engine has not been touched: that is the advantage of declarative rules.
Common mistake: writing the reference rule on silver.products with ref_table equal to silver.order_lines. That would check that every product has been sold at least once, which is a different question. The rule's table is the one that contains the foreign key.
Exercise 3
| Field | Content |
|---|---|
| Table | gold/daily_funnel |
| Description | The website's conversion funnel by day: total sessions and sessions that reach each step |
| Grain | One row per day |
| Owner / steward | Product / Marc |
| Source | silver/web_events, via daily_load.py |
| Partitioning | By date |
| Update | Daily; idempotent reprocessing by date |
| Column | Type | Description |
|---|---|---|
date |
date | Calendar day of the events |
sessions |
integer | Sessions with at least one event that day |
with_view |
integer | Sessions with at least one product_view event |
with_cart |
integer | Sessions with a view and add_to_cart |
with_purchase |
integer | Sessions with a view, cart and purchase |
Usage caveat: a session that crosses midnight counts on two days. The sum of sessions for June (30,952) exceeds the month's distinct sessions (30,759); for monthly figures of unique sessions you have to calculate from silver/web_events. In addition, the funnel checks that the session contains each event type, not their order. All the columns have internal sensitivity: the table contains no personal data.
Conclusion
Data quality is measured in dimensions: completeness, uniqueness, validity, accuracy, consistency and timeliness. Instead of discovering defects by chance, rules are declared as code, with a threshold and a severity, and evaluated on every load: your quality.py measures fifteen rules on bronze and silver, saves the series in gold/daily_quality and stops the pipeline when a critical rule fails. Invalid rows are rejected, discarded, repaired or sent to quarantine, but never ignored. Tools such as Great Expectations, Soda, Deequ or dbt tests industrialise the mechanism; data contracts shift the commitment to the producer and observability watches over what nobody foresaw. Around all this, data governance assigns responsibilities (owner, steward, CDO), sets policies and maintains the catalogue for people: business glossary, data dictionary, lineage and classification by sensitivity.
NovaMarket now has orderly practices and data it can trust. What remains is the question Irene will have to answer before the board before moving from the laptop to a real platform: how much does all this cost? Every decision you have made in the course, the format, the partitioning, bronze retention, batch or streaming, has a translation into euros. In the next lesson, Sizing and Cost Control, you will learn to estimate the storage and compute a platform needs, to compare the cloud with on-premises infrastructure and to keep the bill under control.
