Aller au contenu

Leçon 18 · Validation and Pipelines

Writing Validation Rules

Write reusable data validation rules for schemas, columns, rows and datasets, set severity levels, collect all failures and stop bad data from loading.

Cleaning fixes today's file. Validation checks every file, including next month's, against explicit expectations. It tells you quickly when something changed, before bad data reaches a report.

Four levels of checks

Check from outside in

Schema Columns and types
Column Allowed values
Row Fields agree
Dataset Counts and keys
1 / 2

Check the schema first. If a column was renamed, hundreds of row errors would only hide the real cause.

Severity

Give each rule a level that decides what happens:

  • Stop the batch: the whole load is rejected, for example because a key column is missing.
  • Reject the row: the bad row goes to a quarantine file with the reason, and the rest continues.
  • Warn: the data loads, and someone is told.

A small rule engine

Python Validate a batch with schema, row and share checks

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Three ideas matter here. All problems for a row are collected, not just the first. Rejected rows are kept with reasons. And a batch threshold stops the load if too much is wrong, since that often means the source changed. The numbers are examples, so set yours according to your risk. Try changing the threshold to 0.3 and run it again.

The duplicate rule here keeps the first copy. When copies conflict, you may want to quarantine all of them instead.

Dataset-level checks

Row rules cannot notice that half the file is missing. Add checks on the batch as a whole:

  • The row count is within an expected range of recent loads.
  • Total amounts match a control total sent by the source.
  • The newest date is recent enough.
  • The share of missing values has not jumped.
  • References exist in their lookup tables.
Python Compare a batch with expectations

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that the control total passes while the row count fails. If the source computed its total from the same truncated data, that check cannot catch the loss. Independent checks protect each other.

Rules in databases and libraries

Databases can enforce NOT NULL, UNIQUE, CHECK and foreign key constraints, which apply no matter which program writes the data. In SQLite, foreign key enforcement is usually off until you enable it for the connection. See SQL constraints. Validation libraries for Python also offer declared schemas. Check their current documentation before you choose one.

Write good rules

  • Name each rule so reports are readable.
  • Explain why it exists.
  • Base limits on knowledge of the process, not only on past data.
  • Review rules when the business changes. A rule that fires every day tends to be ignored.
  • Test the rules themselves with rows that should pass and rows that should fail.

Common mistake: error messages that include whole records. Logs may be widely visible, so report row IDs and rule names rather than personal details.

Where to put the checks

You can validate at several points, and each catches different failures:

  • At entry, in forms and APIs, while the person can still correct the value.
  • On arrival, before you clean, to confirm that the file has the expected structure.
  • After cleaning, to confirm that your output meets its promises.
  • Before publishing, to compare totals and freshness with expectations.

Checks on arrival and after cleaning are different. Raw data may legitimately contain spaces and mixed case that your pipeline will fix, while your output should not.

An empty result is not a pass

Be careful with rules that succeed when there is nothing to check. A statement such as "all rows have a positive quantity" is true for an empty table. In Python, all([]) returns True. Add an explicit minimum row count, and make sure a failed or skipped check is never reported as a pass.

A rule has a life cycle

Start a new rule as a warning if you are unsure how often it will fire. Watch it for some deliveries, read the rows it catches and adjust the limit. Then raise it to a rejecting rule if the false alarms are rare and the owner agrees. Keep the history: who changed the rule, when and why.

When you relax a rule to let a batch through, write down the exception and when it ends. Temporary exceptions that nobody removes slowly turn validation into decoration.

Make failures useful

A good failure message tells the reader what to do: the rule name, the number of affected rows, a few row IDs and where the rejected records are stored. "Validation failed" alone forces someone to start the investigation from nothing.

Test the validator

A validator can have bugs like any other code. Keep a small batch that contains one deliberate violation of each rule, plus one fully valid row. Run it whenever you change the rules. Every violation should be reported under the expected name, and the valid row should pass.

This check protects you from a quiet failure: a typo in a column name or a reversed comparison can leave a rule that never fires. From the outside, a rule that never fires looks exactly like perfect data. If a rule has not reported anything for a long time, confirm with the test batch that it still can.

Also keep validation separate from repair. A check that silently changes values while it tests them is hard to trust, because you can no longer see what arrived. Let the checks report, and let clearly named cleaning steps make the changes.

Check your understanding

Quick check · 3 questions

of 3 answered You scored / 3 · perfect!

  1. 1. Which check should run first?

    A structural problem makes later row checks misleading.
  2. 2. What is a quarantine file?

    It keeps bad rows for repair and review instead of losing them.
  3. 3. Why stop a batch when many rows fail?

    Loading the remaining rows could produce misleading partial results.

Summary

  • Validate the schema, columns, rows and the whole batch.
  • Give rules severity levels and quarantine failures with reasons.
  • Add thresholds and independent control checks.
  • Enforce key rules in the database too.

Next: Building a Repeatable Cleaning Pipeline

Votre progression est enregistrée dans ce navigateur. Aucun compte nécessaire.