Contracts

Part of the free LogicWiz Data Engineering course, Module 7: Data quality and testing. The SQL and Python run in the app, on real Postgres and real Python in the browser.

It is 8:40 on Monday. Tess opens the revenue dashboard and the whole weekend says $0. Nothing failed. On Friday afternoon the payments team renamed amount to amount_usd in their export; the loader found no amount column and filled it with NULL. Nobody had written down what the export promised, so nobody had broken a promise.

You'll learn to

  • Write a data contract as code: columns, types and rules
  • Check rows against it in Python and in Postgres
  • Choose between failing, warning and quarantining bad rows
  • Explain how a schema registry guards a stream of messages

Learn

Write the promise down, as code

The payments team did nothing wrong by their own lights. Renaming a column is a tidy-up. The trouble is that nobody had agreed what the export must contain.

A data contract is that agreement, between the team that produces data and the teams that use it: which columns, which types, which may be empty, which values are allowed, who owns it and how fresh it will be.

Written in a wiki, it is ignored. Written as code, it stands at the door of your pipeline like a guard with a list. Every batch is checked against it before anything is loaded. A broken promise then stops the line, or at least makes a noise. It does not quietly turn a dashboard to zero.

SwiftKart's payments contract

Column or ruleTypeRequiredRule
paymentidintegeryesunique
orderidintegeryesmust exist in orders
methodtextyescard, wallet, banktransfer or giftcard
amountnumberyes0 or more
statustextyescaptured, failed or refunded
paidtstimestamp textyes
Across rowsat most one captured payment per order

Owner: the payments team. Freshness: new payments within 1 hour. The last line is a rule across rows: no single row breaks it, but two captured payments for one order (order 1033) do.

A contract as two small Python classes

import json
from dataclasses import dataclass

KINDS = {'int': (int,), 'number': (int, float), 'text': (str,)}

@dataclass
class Column:
    name: str
    kind: str                     # 'int', 'number' or 'text'
    required: bool = True
    allowed: tuple = ()
    min_value: float = None

    def problems(self, row):
        value = row.get(self.name)
        if value is None:
            return [f'{self.name}: missing'] if self.required else []
        if isinstance(value, bool) or not isinstance(value, KINDS[self.kind]):
            return [f'{self.name}: expected {self.kind}, got {type(value).__name__}']
        if self.allowed and value not in self.allowed:
            return [f'{self.name}: {value!r} is not allowed']
        if self.min_value is not None and value < self.min_value:
            return [f'{self.name}: {value} is below {self.min_value}']
        return []

@dataclass
class Contract:
    columns: list

    def validate(self, row):
        return [p for col in self.columns for p in col.problems(row)]

PAYMENTS = Contract([
    Column('payment_id', 'int'),
    Column('order_id', 'int'),
    Column('method', 'text', allowed=('card', 'wallet', 'bank_transfer', 'gift_card')),
    Column('amount', 'number', min_value=0),
    Column('status', 'text', allowed=('captured', 'failed', 'refunded')),
    Column('paid_ts', 'text'),
])

with open('data/payments.jsonl') as f:
    payments = [json.loads(line) for line in f]
print(len(payments), 'payments,', sum(1 for p in payments if PAYMENTS.validate(p)), 'break the contract')

renamed = {k: v for k, v in payments[0].items() if k != 'amount'}
renamed['amount_usd'] = payments[0]['amount']          # the Friday rename
print(PAYMENTS.validate(renamed))
print(PAYMENTS.validate({**payments[0], 'method': 'crypto', 'amount': -5}))

number accepts int and float, because JSON writes 50.0 as 50. bool is refused on purpose: in Python True is also an int. The last two lines print the problems for Friday's rename and for a row with a bad method and a negative amount.

Three payments against the contract

RowProblems
Payment 5001, as sent(none)
The same, with amount renamed to amountusdamount: missing
The same, with method crypto and amount -5method: 'crypto' is not allowed, amount: -5 is below 0

Each problem names the column and the rule, so whoever reads the alert knows what to tell the payments team.

Stop, shout, or set aside

The contract has found a problem. Now what? There are three answers, and a real pipeline uses all three, chosen rule by rule.

  • Fail: stop and load nothing. For a broken promise that makes everything wrong: a missing column, a changed type. Better no data than wrong data.
  • Warn: load everything and tell someone. For things worth knowing and not worth stopping for: a customer with no email.
  • Quarantine: load the good rows and move the bad ones to a side table, with the reason. Nothing is lost, and the bad rows can be fixed and replayed. For a few bad rows in a good batch: one order line pointing at product 999. The side table is called a quarantine table, or a dead-letter table.

The contract at the door

A batch arrives and is checked against the contract. From there four arrows leave: fail and load nothing, quarantine the bad rows, warn and load everything, or load the rows that pass.

Follow one arrow out of the contract for each rule: the label on the arrow says when that exit is the right one.

Fail the batch or quarantine the rows?

Fail the batchQuarantine the bad rows
Nothing is loaded until someone fixes itGood rows arrive on time; bad rows wait aside
Right when the whole batch is suspect (a schema change)Right when a few rows are bad in a good batch
Loud: the pipeline is redQuiet, unless you alert on the quarantine's size
Downstream is late, but correctDownstream is on time, but missing a few rows

One bad line goes to quarantine

Twelve landed order lines are checked. Eleven go into the clean table; the line for product 999 goes into the quarantine table with its reason; the two counts add up to the twelve that landed.

  1. The file lands. Twelve order lines from 2 June wait in the landing table. One rule is checked on each: the product must exist.

  2. Eleven lines pass. Their products exist, so they go into the clean table and arrive on time.

  3. One line fails. Product 999 does not exist. The line is not thrown away, and it does not stop the batch. It moves to the quarantine table with the reason beside it.

  4. Count both sides. 11 loaded + 1 quarantined = 12 landed. Every row went to exactly one place. Check that sum every time you split a batch.

Follow the amber line from the left box to the right one. The next two examples do exactly this, first in Python, then in SQL.

Quarantine the 2 June order lines

import csv

with open('data/products.csv', newline='') as f:
    known_products = {int(r['product_id']) for r in csv.DictReader(f)}

good, quarantine = [], []
with open('landing/order_items/2025-06-02.csv', newline='') as f:
    for row in csv.DictReader(f):
        reasons = []
        if int(row['product_id']) not in known_products:
            reasons.append('unknown product_id')
        if int(row['qty']) <= 0:
            reasons.append('qty must be positive')
        if reasons:
            quarantine.append({**row, 'reason': '; '.join(reasons)})
        else:
            good.append(row)

print(len(good), 'lines loaded')
for row in quarantine:
    print('quarantined:', row['order_id'], row['line_no'], row['product_id'], '->', row['reason'])

Eleven lines go through; the line for product 999 waits in quarantine with its reason. Notice the int(...): values read by csv are always text.

Quarantine in Postgres

BEGIN;
INSERT INTO dw.order_items_quarantine
SELECT i.*, 'unknown product_id' AS reason
FROM staging.order_items_landed AS i
WHERE NOT EXISTS (SELECT 1 FROM products AS p WHERE p.product_id = i.product_id);

INSERT INTO dw.order_items
SELECT i.*
FROM staging.order_items_landed AS i
WHERE EXISTS (SELECT 1 FROM products AS p WHERE p.product_id = i.product_id);
COMMIT;

SELECT (SELECT COUNT(*) FROM dw.order_items) AS loaded,
  (SELECT COUNT(*) FROM dw.order_items_quarantine) AS quarantined;

The two WHERE clauses are exact opposites, so every landed row goes to exactly one place: 11 loaded plus 1 quarantined is the 12 that landed.

Remember: decide rule by rule. Fail when the whole batch is wrong, quarantine a few bad rows, warn for things worth knowing. And the rows loaded plus the rows set aside must equal the rows that landed.

Let the table say no

Some of the contract can live in the table itself. Postgres will enforce NOT NULL, CHECK (amount >= 0), CHECK (status IN (...)), UNIQUE and REFERENCES. A row that breaks one is rejected with an error. That is a "fail" policy nobody can forget to run.

The big analytical platforms enforce much less. Snowflake and BigQuery enforce NOT NULL but not primary or foreign keys. Databricks Delta tables enforce NOT NULL and CHECK, and treat keys as information only. On those platforms most of the contract has to live in your pipeline code or in a tool.

The table refuses a broken row

INSERT INTO dw.payments
VALUES (6001, 1001, 'crypto', -5.00, 'captured');

Postgres stops at a broken rule and names it (payments_amount_check). Change the amount to 5.00 and run it again: now the method check stops it. Use card as well, and the row goes in.

On a stream, a registry holds the contract

A file arrives as a batch, and you can check a batch at the door. On Kafka (Module 15) messages flow all day, the sender and the readers never meet, and a bad message reaches every reader before anyone notices.

There the contract is a schema in a registry, the service you met in Lesson 4.2. Before the payments app may send a new shape of message, it registers the new schema. The registry compares it with the previous version under a compatibility rule. If the change would break readers, the registry refuses with HTTP 409, and the broken promise fails in the sender's deploy, not in a dashboard.

Each message then carries only the schema's id. A reader fetches the schema by that id once, keeps it, and decodes.

A producer, the registry and a consumer

The producer registers a new schema version, the registry checks compatibility and returns id 42, the producer sends messages framed with that id, and the consumer fetches schema 42 once to decode them.

Read it top to bottom. The red arrow is the contract check: it happens once, when the schema is registered. After that every message carries id 42, and the loader asks the registry for schema 42 only the first time.

One message on the wire

A bar splits a 43-byte message into a one-byte magic number, a four-byte schema id and a thirty-eight-byte Avro payload.

Read it left to right: one zero byte, the schema id, then the data. Avro binary has no field names or types, only values in schema order, so it cannot be read without the writer's schema. That is why the id travels with every message.

Frame and unframe a message

import struct

SCHEMAS = {42: {'name': 'payment', 'fields': ['payment_id', 'order_id', 'method', 'amount']}}

def frame(schema_id, payload):
    return struct.pack('>bI', 0, schema_id) + payload      # magic 0, then a 4-byte id

def unframe(message):
    magic, schema_id = struct.unpack('>bI', message[:5])
    if magic != 0:
        raise ValueError(f'unknown magic byte {magic}: not registry-framed')
    return schema_id, message[5:]

msg = frame(42, b'\x92\x4e\xd2\x0f\x08card\x00\x00\x00\x00\x00\x00\x49\x40')
schema_id, body = unframe(msg)
print(len(msg), 'bytes; schema id', schema_id, '->', SCHEMAS[schema_id]['name'], '| payload', len(body), 'bytes')
print(msg[:5].hex(' '))
try:
    unframe(b'{"payment_id": 5001}')
except ValueError as e:
    print(e)

>bI means big-endian, one signed byte, then one unsigned 4-byte number. The last line is a classic incident: a producer sends plain JSON to a topic whose readers expect registry-framed Avro, and the first byte, {, is not 0.

Why a default decides everything

Lesson 4.2 stepped through how Avro reads old data with a new schema. Fields match by name. A field only the writer has is ignored. A field only the reader has takes the reader's default, and with no default the read fails.

The registry's rule is that walkthrough turned into a gate. Adding currency with a default passes in both directions: new readers fill the default into old messages, and old readers ignore the new field. Adding it without a default breaks the default rule, BACKWARD, because a new reader has nothing to put into old data.

And Friday's rename? A rename is a delete plus an add with no default. On a topic guarded by a registry it would have been refused on Friday afternoon.

Compatibility modes (Confluent Schema Registry; the default is BACKWARD)

ModeGuaranteeAllowed Avro changesUpgrade first
BACKWARDThe new schema can read data written with the latest oneDelete fields; add fields with a defaultConsumers
FORWARDThe latest schema can read data written with the new oneAdd fields; delete fields that had a defaultProducers
FULLBoth of the aboveAdd or delete fields that have a defaultEither, in any order
TRANSITIVEThe same, against every earlier version, not just the latestAs aboveAs above
NONENo checkAnythingEveryone at once, carefully

Plain BACKWARD only compares with the latest version, so a chain of steps that are each fine can still leave a reader unable to read data from three versions ago. Topics kept for a long time, or replayed from the start, want the transitive modes.

The trap: a quarantine nobody reads. Setting bad rows aside keeps the pipeline green, and that is exactly the danger. The quarantine table grows, revenue is a little short every day, and nobody notices. Alert on its size, give it an owner, and make replaying fixed rows a normal, tested path.

dbt model contracts (contract: {enforced: true}) check column names and types when a model builds. On Databricks, Lakeflow Declarative Pipelines (formerly Delta Live Tables, hence the dlt module) choose a policy per expectation: @dlt.expect warns and keeps the row, @dlt.expect_or_drop drops it, @dlt.expect_or_fail stops the update. Great Expectations groups rules into suites, and in Python services pydantic models play the part of the contract classes above. For contracts between teams, the Open Data Contract Standard (ODCS, version 3, from Bitol, a Linux Foundation AI & Data project) writes schema, quality rules, owner and SLAs as YAML.

The contract as Databricks pipeline expectations

Runs on Databricks:

import dlt

@dlt.table(comment="Payments that passed the contract")
@dlt.expect_or_fail("amount_present", "amount IS NOT NULL")
@dlt.expect_or_drop("known_method", "method IN ('card', 'wallet', 'bank_transfer', 'gift_card')")
@dlt.expect("non_negative_amount", "amount >= 0")
def payments_clean():
    return spark.readStream.table("swiftkart.raw.payments")

One rule for each policy: a missing amount stops the update (fail), an unknown method drops the row, a negative amount is kept and counted (warn). The pipeline's page shows how many rows each expectation failed or dropped.

Numbers to remember

WhatNumber or nameGood to know
Registry subject<topic-value by defaultThe producer registers its Avro, Protobuf or JSON schema under it and gets an id back
An incompatible schemaHTTP 409Schema being registered is incompatible with an earlier schema for subject "payments-value"
Message framing1 magic byte (0) + a 4-byte schema id, big-endianConfluent's wire format: 5 bytes before the data
RegistriesConfluent Schema RegistryApicurio and AWS Glue Schema Registry work the same way
Avro type wideningint to long, float or double; long to float or double; float to doublestring and bytes go either way. A rename needs the old name in the reader's aliases
Postgres enforcesNOT NULL, CHECK, UNIQUE, REFERENCESA failed check is named in the error, such as paymentsamountcheck
Snowflake and BigQuery enforceNOT NULL onlyPrimary and foreign keys are not enforced
Databricks Delta enforcesNOT NULL and CHECKKeys are information only

What changed at SwiftKart

The payments export now has a contract, kept beside the loader's code and agreed with the payments team. A missing amount fails the batch within minutes and names the column, so a rename can no longer turn a weekend to $0. A stray bad row goes to quarantine with its reason. The quarantine has an owner and an alert on its size. Liam's missing email is a warning, not a failure.

A contract checks data at the door. It cannot tell you whether everything that left the source arrived in the warehouse. Lesson 7.3 proves that, by reconciling the two sides.

In one line

A contract writes down what the data promises and checks it at the door; rule by rule you fail the batch, quarantine the bad rows or warn, and you count that every row went somewhere.

Interview corner

What is a data contract?

An agreement between a data producer and its consumers about the schema (names, types, required fields), the meaning and allowed values, freshness and ownership. To be useful it is versioned as code and checked automatically when data crosses the boundary, so a breaking change fails loudly instead of corrupting dashboards.

Fail, warn or quarantine: how do you decide?

Fail the batch when the problem makes all of it untrustworthy, like a missing column or a changed type. Quarantine individual rows that break row-level rules in an otherwise good batch, with the reason and a replay path. Warn for issues worth tracking that do not make data wrong for most uses. I decide per rule, with the consumers.

A Kafka topic's Avro schema needs `amount` renamed to `amount_usd`, under BACKWARD compatibility. How do you roll it out?

A rename is a delete plus an add, and the add has no value in old data, so registering it straight away is refused with a 409. Under BACKWARD consumers upgrade first: I add amount_usd with a default (or give the reader field an alias for amount), deploy the consumers on the new schema, then switch producers to fill amount_usd, and only later remove amount once nothing reads it. If the topic is replayed from the start or retained for months, I would use BACKWARD_TRANSITIVE so every old version stays readable.

Can the warehouse enforce the contract for you?

Partly. Postgres enforces NOT NULL, CHECK, UNIQUE and foreign keys. Snowflake and BigQuery enforce NOT NULL but not keys, and Databricks enforces NOT NULL and CHECK constraints but treats keys as informational. So key and cross-row rules usually live in pipeline checks (dbt tests, expectations) rather than in the table.