Sub topic 8
Enforcing data quality with expectations
This chapter assumes you can write a streaming table in SQL or Python and that you know how the bronze, silver and gold layers fit together. It covers how to attach quality rules to a dataset and what happens to rows that break them.
What an expectation is
An expectation is a named rule attached to a dataset. It holds a SQL boolean condition, and the pipeline checks every row against it. The result is recorded as a metric. You choose what happens to a row that fails the condition.
Expectations usually go on the silver layer. Bronze keeps raw data as it arrived, so rejecting rows there makes problems harder to trace.
The three violation actions
| Action | SQL | Python decorator | Effect on a failing row |
|---|---|---|---|
| Warn (default) | `EXPECT (cond)` | `@dlt.expect` | Row is kept. Violations are counted. |
| Drop | `EXPECT (cond) ON VIOLATION DROP ROW` | `@dlt.expect_or_drop` | Row is removed from the target. Violations are counted. |
| Fail | `EXPECT (cond) ON VIOLATION FAIL UPDATE` | `@dlt.expect_or_fail` | The update stops with an error. |
Warn is the default and is useful when you want to measure quality before enforcing it. Drop suits records you cannot use, such as a missing key. Fail suits conditions that mean something upstream is broken, where you would rather stop than publish bad data.
Expectations in SQL
Constraints go in the parentheses after the table name:
CREATE OR REFRESH STREAMING TABLE orders_silver (
CONSTRAINT valid_order_id EXPECT (order_id IS NOT NULL) ON VIOLATION DROP ROW,
CONSTRAINT positive_amount EXPECT (amount > 0)
)
AS SELECT
order_id,
customer_id,
CAST(amount AS DECIMAL(10,2)) AS amount,
CAST(order_ts AS TIMESTAMP) AS order_ts
FROM STREAM(orders_bronze);Rows with a null order_id are dropped. Rows with a non-positive amount stay in the table, but each one is counted as a violation of positive_amount.
Expectations in Python
In Python, you stack decorators on the function that defines the dataset:
import dlt
from pyspark.sql.functions import col
@dlt.table(comment="Validated orders")
@dlt.expect_or_drop("valid_order_id", "order_id IS NOT NULL")
@dlt.expect("positive_amount", "amount > 0")
def orders_silver():
return (
dlt.read_stream("orders_bronze")
.select(
"order_id",
"customer_id",
col("amount").cast("decimal(10,2)").alias("amount"),
col("order_ts").cast("timestamp").alias("order_ts"),
)
)The first argument is the rule name and the second is the condition string. Use the same names you would use in SQL, because the names appear in the metrics.
What happens during an update
Each rule is evaluated independently. A row can pass one rule and fail another. With several drop rules, a row is removed if it fails any of them.
Reviewing the results
Pass and fail counts are written to the pipeline event log, and the pipeline UI shows them for each dataset. Chapter-level monitoring is covered later, but you can already find the data in flow_progress events.
Common errors
- Using fail too early. One malformed record then blocks the whole update. Start with warn, review the counts, and tighten later.
- Expecting dropped rows to be saved. Dropped rows are not written anywhere by default. If you need them for review, route them to a separate quarantine table with the inverse condition.
- Putting a drop rule on bronze. You lose the raw record, so you cannot replay it after fixing the rule.
- Conditions that evaluate to null.
amount > 0is null whenamountis null. A null result is not true, so it counts as a violation. Add an explicitIS NOT NULLrule if nulls need their own metric. - Mixing up names. Rule names should be unique within a dataset and descriptive, such as
valid_order_id, so the metrics are readable.
Exercise
In orderssilver, a row has orderid = 7 and amount = -5. A second row has order_id = NULL and amount = 20. Using the rules shown above, which rows appear in the table, and what is counted as a violation?
Show answer
Both rules apply. The first row passes validorderid and fails positiveamount. The warn action keeps it, so it appears in the table and counts as one positiveamount violation. The second row fails validorderid, whose action is drop, so it is removed and counts as one validorderid violation. It passes positive_amount. Only the first row is in the table.
Exercise
You want an update to stop whenever a customer_id is missing, instead of silently dropping rows. How do you write that rule in SQL and in Python?
Show answer
SQL: CONSTRAINT hascustomer EXPECT (customerid IS NOT NULL) ON VIOLATION FAIL UPDATE. Python: @dlt.expectorfail("hascustomer", "customerid IS NOT NULL").