A vendor renames a column on a Friday evening, and on Monday a report goes out with a column of zeros. Nothing in the pipeline complained, because nothing in it knew what the table should look like. How do you make a table state its own shape, refuse itself when it breaks it, and say where it came from? On 60 days of SPY, one drifted table shows 5 distinct ways to break a contract.
Why a table needs a contract
Where we are: the last topics loaded, repaired and versioned data. All of that assumed the table has the right shape. In real pipelines the shape changes without warning: a column is renamed, a number arrives as text, a new column appears, a price turns negative because of a sign error. The damage is quiet. A step that reads a column that is no longer there may fail loudly, which is the good case, or it may read a column that has a different meaning now, which is the bad case. By the end of this topic you will be able to write a schema contract, check a table against it, refuse a table that breaks it, classify a change of the contract, and record where each table came from.
A schema contract is an agreement between the code that writes a table and the code that reads it. It is data, not prose: a dictionary that a program can check. The producer promises that every table it writes matches the contract, and the reader can then depend on the shape without defending against every possible surprise. The two sides can change independently as long as they tell each other through the contract.
A machine-readable promise about a table: the columns, their types, whether each may be empty and the range of its values. A table that does not meet it is refused before anything downstream uses it.
Types come first. A contract says that volume is an integer and date is a date, and the check compares that with what the table has. The table below looks like a perfectly good table of three columns. The code prints the kind of each column, a letter that pandas uses for its types: M for dates, f for floats and i for integers.
table = pd.DataFrame({"date": pd.to_datetime(["2021-03-01", "2021-03-02"]), "close": [10.0, 10.2], "volume": [1000, 2000]})print({name: table[name].dtype.kind for name in table})1
{'date': 'M', 'close': 'f', 'volume': 'i'}- 1The kind letter is stable across pandas versions; the full type name is not.
A contract for the columns
The first check is about names and types, and it can find three problems. A column that the contract names and the table does not have is missing. A column that the table has and the contract does not know is unexpected: it may be harmless, but it may be a renamed column in disguise, as when volume becomes shares, so it is reported as well. And a column that is present but has another type is wrongly typed, for example prices that arrive as text. Each problem is a short sentence, and the list is sorted so that the same table always gives the same report.
Worked example 1. *Problem:* the contract wants day (datetime), price (float) and qty (int). The table has day, price as text, and a column quantity. List what is wrong. *Plan:* names first (missing and unexpected), then the types of the names that both have. *Steps:* two list comprehensions for the names, has_type for the types.
contract = {"day": "datetime", "price": "float", "qty": "int"}frame = pd.DataFrame({"day": pd.to_datetime(["2021-03-01"]), "price": ["10.0"], "quantity": [5]})missing = [name for name in contract if name not in frame.columns]1unexpected = [name for name in frame.columns if name not in contract]2print(missing, unexpected)print(has_type(frame["price"], "float"), has_type(frame["day"], "datetime"))3
['qty'] ['quantity'] False True
- 1Names the contract has and the table lacks.
- 2Names the table has and the contract does not know.
- 3has_type compares a column with a contract type.
*Check:* qty is missing and quantity is unexpected, which together say that a column was renamed, and price is not a float because it holds text, while day is a datetime. *What to notice:* the missing and the unexpected columns come as a pair when a name changed, and the report shows both so that a person can see the rename. The simple method of looking only at the contract's columns would never mention quantity.
A contract for the values
The right columns can still hold wrong values. The second check is about the values: a column that must not be empty has missing values, a price is below zero, a volume is above any possible amount. A contract states a nullable flag and optional min and max bounds, and the check counts the values that break them. Two details decide whether the check is right. A value equal to a bound is allowed, so the comparisons are strict. And a missing value is not a value: it is counted as a null, never as being below a bound.
Worked example 2. *Problem:* the column holds 10.0, -2.0, missing, 12.0, 0.0. It may not be below 0 or above 11. How many missing values, how many below and how many above? *Plan:* count the missing values with isna, remove them with dropna, then count each comparison. *Steps:* isna, dropna, compare. The second line of output is the simple method, which treats everything that is not at least 0 as a violation.
prices = pd.Series([10.0, -2.0, None, 12.0, 0.0])print(int(prices.isna().sum()), int((prices.dropna() < 0).sum()), int((prices.dropna() > 11).sum()))1print(int((~(prices >= 0)).sum()), int((prices < 0).sum()))
1 1 1 2 1
- 1dropna first, so that a missing value is counted once, as a null.
*Check:* there is 1 missing value, 1 value below 0 (the -2.0; the 0.0 is allowed) and 1 above 11 (the 12.0). *What to notice:* the second line shows the trap: ~(prices >= 0) counts the missing value as a violation, because any comparison with a missing value is False, and so it reports 2 where only 1 value is below zero. Count nulls and bounds separately.
Comparisons with a missing value are always False, and negating them turns them True. A rule written as "not (value >= 0)" therefore flags nulls twice, once as a null and once as a bound violation. Say what you mean: count the nulls, remove them, and then count the values below the bound.
Refuse it loudly
A check that returns a list is for people to read. A pipeline also needs a check that stops: a function that returns the table when it is fine, so that it can sit inside a chain of steps, and raises an exception when it is not. The exception should carry the whole list of problems, not just the first, because the person who reads the failure wants to fix everything at once. A special exception class makes it possible to catch exactly this kind of failure and nothing else.
Worked example 3. *Problem:* write a gate that returns "ok" for an empty list of problems and raises an error that carries the list otherwise; show both. *Plan:* a subclass of ValueError that stores the problems, and a function that raises it when the list is not empty. *Steps:* class, function, try and except.
class Broken(ValueError): def __init__(self, problems): super().__init__("; ".join(problems)) self.problems = list(problems)1def gate(problems): if problems: raise Broken(problems)2 return "ok"print(gate([]))try: gate(["missing column volume", "open has 1 values below 0.0"])except Broken as error: print(error.problems)
ok ['missing column volume', 'open has 1 values below 0.0']
- 1The error keeps the list, so the caller can read it, not only the text.
- 2Raising stops the pipeline at the border instead of letting bad data in.
*Check:* the empty list passes and the list of two problems comes back out of the error, whole. *What to notice:* because Broken is a ValueError, code that already handles bad values will handle it too, and code that wants to treat contract failures specially can catch Broken alone. The best place for the gate is at the border: right after a table is read from outside, and right before it is written for others.
Validate a table when it enters your pipeline and again when it leaves. Between those two points you trust your own code. Inside the border, a failed check means a bug of yours; at the border, it means a bug of somebody else's.
Lineage: where did this table come from
Contracts say what a table should be. Lineage says where it came from. When a number is questioned, lineage lets you walk back step by step to the source. To tell tables apart without keeping copies, you give each a fingerprint: a short code computed from its content, so that equal content gives an equal code and a change of one value gives a different code. A hash function such as sha256 does this.
Worked example 4. *Problem:* give a table of three numbers a fingerprint; show that a copy has the same one and a table with one value changed has another. *Plan:* turn the table into text with to_csv, encode the text to bytes, hash the bytes, keep the first characters. *Steps:* text, bytes, digest, cut.
def fp(frame): return hashlib.sha256(frame.to_csv(index=False, lineterminator="\n").encode("utf-8")).hexdigest()[:12]1a = pd.DataFrame({"x": [1, 2, 3]})b = a.copy()c = a.copy()c.loc[1, "x"] = 20print(fp(a), fp(b), fp(c))print(fp(a) == fp(b), fp(a) == fp(c))
4bf0e63035dd 4bf0e63035dd 823200c93638 True False
- 1lineterminator fixes the line ending, so the code is the same on every computer.
*Check:* a and its copy have the same fingerprint and c has another. *What to notice:* the line ending is fixed on purpose. Without it, to_csv uses the line ending of the operating system, and the same table would get a different fingerprint on Windows. A fingerprint that depends on the computer cannot be compared between computers.
A lineage record for one step is then small: the name of the step, the fingerprint and the number of rows of each input, and the fingerprint and rows of the output. It contains no time stamp, which is deliberate: running the same step on the same tables must give the same record, so that two runs can be compared by simply comparing the records.
Worked example 5. *Problem:* a step keeps the first two rows of a four-row table. Write its record. *Plan:* fingerprint the input and the output, and count their rows. *Steps:* two fingerprints, two counts, one dictionary.
def fp(frame): return hashlib.sha256(frame.to_csv(index=False, lineterminator="\n").encode("utf-8")).hexdigest()[:12]a = pd.DataFrame({"x": [1, 2, 3, 4]})step = {"step": "take_two", "inputs": [fp(a)], "rows_in": [len(a)], "output": fp(a.iloc[:2]), "rows_out": 2}print(step)
{'step': 'take_two', 'inputs': ['1fb5a4e10b93'], 'rows_in': [4], 'output': 'aea284871dde', 'rows_out': 2}*Check:* the record names the step, shows one input of 4 rows and an output of 2, and every fingerprint is a fixed code. *What to notice:* nothing in the record says when the step ran or where. What matters for the lineage is which content went in and which came out.
When the contract changes
Contracts change, because data changes. The question that matters is who is hurt. A change is breaking when a reader of the old data might break, and compatible when it cannot. Removing a column breaks the readers of that column. Changing a type breaks readers that expect the old type. Allowing missing values in a column that was never empty breaks readers that never checked. Loosening a bound, a lower minimum or a higher maximum, lets in values that old readers never saw. The opposite changes only tighten the promise: adding a column, forbidding missing values, raising a minimum or lowering a maximum cannot break any reader of the old data.
Worked example 6. *Problem:* four changes of bounds: a minimum from 0.0 to -1.0, a minimum from 0.0 to 1.0, a maximum from 10.0 to 20.0, a maximum from 10.0 to 5.0. Which are breaking? *Plan:* a minimum is loosened when it goes down and a maximum when it goes up; a loosened bound is breaking. *Steps:* test the direction, print the verdict.
cases = [("min", 0.0, -1.0), ("min", 0.0, 1.0), ("max", 10.0, 20.0), ("max", 10.0, 5.0)]for bound, before, after in cases: looser = after < before if bound == "min" else after > before1 print(bound, before, "->", after, "breaking" if looser else "compatible")
min 0.0 -> -1.0 breaking min 0.0 -> 1.0 compatible max 10.0 -> 20.0 breaking max 10.0 -> 5.0 compatible
- 1A lower minimum or a higher maximum lets in new values.
*Check:* the first and the third lines are breaking, the second and the fourth are compatible. *What to notice:* "compatible" always means compatible for readers of the old data. A producer that tightens a bound can still break itself, if its own data no longer fits. The report is for the readers, who need to know before the data changes.
- FunctionQuestion it answers
- check_columns(frame, contract)Are the right columns there, with the right types?missing, unexpected, wrong type
- check_values(frame, contract)Are the values inside what is promised?nulls and bounds counted apart
- validate(frame, contract)Return the table or stop.raises ContractError with all problems
- fingerprint(frame)Which table is this, exactly?same content, same code
- diff_contracts(old, new)Will the change break a reader?breaking and compatible lists
- lineage_step(name, inputs, output)What went in and what came out?no time stamp
- study(bars)Does a drifted table get caught?uses all of the above
What you will build
The lab follows the lecture. Task 1 checks the columns of a table against a contract and task 2 checks the values. Task 3 turns the two checks into a validator that returns the table or raises. Task 4 gives a table its fingerprint and task 5 classifies a change of a contract. Task 6 writes the lineage record of a step, and task 7 runs it all on real SPY, with a table that drifts.
Next topic: you now have the pieces of a trustworthy pipeline. The last topic of the skill, Capstone: a validated ingestion pipeline for prices and fundamentals, puts them together: parse, name, adjust, check, load, record, in one flow, with the fundamentals added so that a price can be joined to what was known when.
Lab · what's graded
7 tasks · 100 pts- Check the columns15 pts
- Check the values15 pts
- Refuse a bad table10 pts
- Fingerprint a table10 pts
- Classify the change15 pts
- Record a step10 pts
- The study on the SPY table25 pts