Sign in

Validation

Schema-first data validation

A schema-first data checker: declare each column's type and quality rules once, then validate every table against them and get a full report.

Overview

A model accepts any numbers you give it. If ages suddenly arrive in months, or a column is half empty, nothing crashes: the predictions just get worse, quietly. Data validation makes such problems loud. You write down what a correct table looks like, column by column: the type, the allowed range, the allowed categories, whether values may be missing or repeat. Every table is then checked against that description before it is used, and each violation is reported with its column, row and rule.

A short history

Checking data against a declared schema comes from databases, where types and constraints have guarded tables since the relational model of the 1970s. It has no single inventor. Machine learning teams adopted the idea in the late 2010s after finding that many production failures came from changed data and not from changed code. Google described its approach in the 2019 paper Data Validation for Machine Learning by Breck and colleagues, and open source tools such as TensorFlow Data Validation and Great Expectations spread the practice.

How it works

  1. Write the schema as plain data: a dict from column name to rules such as dtype, min, max, allowed, unique, nullable, max_null_fraction and pattern.
  2. Create Validator(schema, DataValidationConfig()) and call validate(data) with a dict of columns or a list of records.
  3. The validator first checks the columns themselves: a required column that is missing, or an extra column the schema does not name.
  4. It then walks each column value by value: missing values, type, range, allowed set, pattern and uniqueness. A value of the wrong type skips the remaining rules.
  5. Cross-column rules passed as functions of a row are run next. A row fails when the function returns False or raises.
  6. The result is a ValidationReport with ok, the violations, a count per rule and the share of missing values per column. With raise_on_error a failing table raises DataValidationError.

Watch out for

  • A schema that is too loose (no ranges, everything nullable) passes bad data, so the check gives comfort without protection.
  • A schema that is too strict fails on harmless change, and people learn to ignore or disable it. Set limits from what the model actually needs.
  • Only the first max_errors violations are stored in the report, so read n_errors and by_check for the true totals.
  • Each rule looks at single values or single rows. A slow drift in the average of a column passes every rule, so distribution checks need a separate tool.
  • The max_null_fraction limit applies only to nullable columns. In a column that is not nullable, every missing value is an error by itself.

Use cases

When to use it

At the boundaries of a pipeline: right after ingestion, before training, and on every batch at serving time. It catches renamed columns, unit changes, new categories and half-empty feeds before they become a worse model.

In industry

Payments and fintech
An upstream team changes an amount column from whole units to hundredths. A range rule catches the hundredfold jump before the fraud model is retrained on it.
Retail
A nightly product feed arrives half empty after a failed export. A rule on the share of missing values stops the pipeline instead of training on the gap.
Online services
At serving time each request batch is checked for new category values and wrong types, so bad inputs are reported and not silently scored.

Choosing it: what must hold

  • Someone who knows the data well enough to write down each column's type, range and allowed values.
  • Tabular data with named columns.
  • A decision on what happens when a check fails: stop the pipeline, quarantine the batch or only warn.
  • The schema kept under version control and updated when the data changes on purpose.

When to choose something else

IfUse instead
The values are valid but dirty, with scattered gaps and outliers to repairThe data cleaning lesson
The worry is that the distribution drifts slowly while every single value stays validMonitoring of summary statistics over time, with the evaluation metrics tracked per period
The data is images, audio or free text with no columnsChecks suited to that medium, such as file format, size and length limits

Math foundations

  1. Share of missing values

    νj=#{ i:xij is missing }n,pass if νj≤νmax⁡\nu_j = \frac{\#\{\, i : x_{ij} \text{ is missing} \,\}}{n}, \qquad \text{pass if } \nu_j \le \nu_{\max}

    The fraction of rows where column jj has no value. A nullable column passes while this stays at or below its max_null_fraction. It is reported per column in null_fraction.

  2. Range rule

    value xij passes  ⟺  aj≤xij≤bj\text{value } x_{ij} \text{ passes} \iff a_j \le x_{ij} \le b_j

    Each present value must lie between the column's min and max. For text columns the same rule is applied to the length of the string.

  3. The table passes only if nothing fails

    ok  ⟺  ∑r∈ruleser=0\text{ok} \iff \sum_{r \in \text{rules}} e_r = 0

    Every rule keeps a count ere_r of its violations in by_check. The table is accepted only when all the counts are zero.

Symbols

xijx_{ij}
value in row i of column j
nn
number of rows in the table
νj\nu_j
share of missing values in column j
νmax⁡\nu_{\max}
the column's max_null_fraction
aj, bja_j,\, b_j
the column's min and max
ere_r
number of violations of rule r

Worked by hand

A score column holds 0.5, a missing value and 0.9. It is nullable with max_null_fraction 0.5. An age column holds 34, −1-1 and 50 with the range 0 to 120.

νscore=13=0.333≤0.5\nu_{\text{score}} = \frac{1}{3} = 0.333 \le 0.5
0≤34≤120,−1<0,0≤50≤1200 \le 34 \le 120, \qquad -1 < 0, \qquad 0 \le 50 \le 120
enull fraction=0,erange=1,∑rer=1≠0e_{\text{null fraction}} = 0, \qquad e_{\text{range}} = 1, \qquad \sum_r e_r = 1 \ne 0

The score column passes its missing-value limit. The age column has one range violation in row 1, so the table as a whole fails.

Visual example

Loading the example.

Try this

  • Click the age in row 0 until it becomes 34.5: a value of the wrong type is reported once and skips the range rule.
  • Lower max_null_fraction for score below 0.3 and a rule about the whole column fails.
  • Click a stage in the diagram to see only the violations that stage found.

Code sample

from impl import Validator
from config import DataValidationConfig

schema = {
    "id": {"dtype": "int", "unique": True},
    "age": {"dtype": "int", "min": 0, "max": 120},
    "plan": {"dtype": "str", "allowed": ["free", "pro"]},
    "score": {"dtype": "float", "nullable": True, "max_null_fraction": 0.5},
}
data = {"id": [1, 2, 2], "age": [34, -1, 50], "plan": ["free", "pro", "gold"], "score": [0.5, None, 0.9]}
report = Validator(schema, DataValidationConfig()).validate(data, rules={"adult_pro": lambda r: r["plan"] != "pro" or r["age"] >= 18})
print(report.summary())            # FAILED: 4 error(s) in 3 rows (adult_pro=1, allowed=1, range=1, unique=1)
for error in report.errors:
    print(error["message"])
Read the implementation (235 lines)
"""Schema-first data validation: declare what a table must look like, then check data against it.

Standard library and NumPy only. The schema is written first, as plain data (a dict that can live in a
config file), and names for every column its type and its quality rules. `Validator.validate` checks a table
against it and returns a report listing every violation with its column, row and rule.

A table is either a dict from column name to a list of values, or a list of dict records.
"""
from __future__ import annotations

import math
import re
from dataclasses import dataclass, field
from typing import Callable

import numpy as np

try:
    from .config import DataValidationConfig
except ImportError:  # run from the template's own folder
    from config import DataValidationConfig

DTYPES = ("int", "float", "str", "bool")


class DataValidationError(ValueError):
    """Raised by Validator.validate when raise_on_error is on and the data fails. Carries the report."""

    def __init__(self, report: "ValidationReport") -> None:
        super().__init__(f"{report.n_errors} data validation error(s); first: {report.errors[0]['message']}")
        self.report = report


def _is_null(value) -> bool:
    """None and NaN both count as a missing value."""
    return value is None or (isinstance(value, (float, np.floating)) and math.isnan(value))


def _has_dtype(value, dtype: str) -> bool:
    """True when a non-null value has the declared type. bool is not accepted as a number."""
    if dtype == "bool":
        return isinstance(value, (bool, np.bool_))
    if isinstance(value, (bool, np.bool_)):
        return False
    if dtype == "int":
        return isinstance(value, (int, np.integer))
    if dtype == "float":
        return isinstance(value, (int, float, np.integer, np.floating))
    return isinstance(value, str)


@dataclass(frozen=True)
class Column:
    """Rules for one column.

    dtype:             "int", "float" (ints are accepted), "str" or "bool".
    required:          the column must be present in the data.
    nullable:          None / NaN values are allowed.
    max_null_fraction: for a nullable column, the largest allowed share of missing values (1.0 = no limit).
    min, max:          inclusive bounds for numbers (or for the length of strings).
    allowed:           the closed set of permitted values, or None for no restriction.
    unique:            no value may appear twice (missing values are not compared).
    pattern:           regular expression a string must match in full, or None.
    """

    name: str
    dtype: str = "float"
    required: bool = True
    nullable: bool = False
    max_null_fraction: float = 1.0
    min: float | None = None
    max: float | None = None
    allowed: tuple | None = None
    unique: bool = False
    pattern: str | None = None

    def __post_init__(self) -> None:
        if self.dtype not in DTYPES:
            raise ValueError(f"column {self.name!r}: dtype must be one of {DTYPES}, got {self.dtype!r}")
        if not 0.0 <= self.max_null_fraction <= 1.0:
            raise ValueError(f"column {self.name!r}: max_null_fraction must be in [0, 1]")
        if self.min is not None and self.max is not None and self.min > self.max:
            raise ValueError(f"column {self.name!r}: min {self.min} is above max {self.max}")
        if self.allowed is not None:
            object.__setattr__(self, "allowed", tuple(self.allowed))
        if self.pattern is not None:
            re.compile(self.pattern)  # fail now, not on the first row


@dataclass(frozen=True)
class Schema:
    """An ordered set of Column rules."""

    columns: tuple

    @classmethod
    def from_dict(cls, spec: dict) -> "Schema":
        """Build a schema from {"column name": {"dtype": "int", "min": 0, ...}, ...}."""
        return cls(tuple(Column(name=name, **rules) for name, rules in spec.items()))

    def names(self) -> list[str]:
        return [column.name for column in self.columns]


@dataclass
class ValidationReport:
    """Result of one validation.

    ok:           True when nothing failed.
    n_rows:       number of rows checked.
    n_errors:     total number of violations found.
    errors:       the first max_errors violations, each a dict with "column", "row" (None for a
                  column-level problem), "check" and "message".
    by_check:     violation count per rule name, for example {"range": 3, "null": 1}.
    null_fraction: share of missing values per schema column that is present.
    """

    ok: bool = True
    n_rows: int = 0
    n_errors: int = 0
    errors: list = field(default_factory=list)
    by_check: dict = field(default_factory=dict)
    null_fraction: dict = field(default_factory=dict)

    def summary(self) -> str:
        """One line for a log."""
        if self.ok:
            return f"OK: {self.n_rows} rows passed"
        parts = ", ".join(f"{check}={count}" for check, count in sorted(self.by_check.items()))
        return f"FAILED: {self.n_errors} error(s) in {self.n_rows} rows ({parts})"


def _to_columns(data) -> tuple[dict, int]:
    """Normalise a table to ({column: list of values}, n_rows). Records missing a key get None there."""
    if isinstance(data, dict):
        columns = {name: list(values) for name, values in data.items()}
        lengths = {len(values) for values in columns.values()}
        if len(lengths) > 1:
            raise ValueError(f"columns differ in length: {sorted(lengths)}")
        return columns, (lengths.pop() if lengths else 0)
    records = list(data)
    names: list[str] = []
    for record in records:
        for name in record:
            if name not in names:
                names.append(name)
    return {name: [record.get(name) for record in records] for name in names}, len(records)


class Validator:
    """Check tables against a Schema."""

    def __init__(self, schema: Schema | dict, config: DataValidationConfig | None = None) -> None:
        self.schema = schema if isinstance(schema, Schema) else Schema.from_dict(schema)
        self.config = config or DataValidationConfig()

    def validate(self, data, rules: dict[str, Callable[[dict], bool]] | None = None) -> ValidationReport:
        """Check a table and return a ValidationReport.

        data:  {column: list of values} or a list of dict records.
        rules: optional cross-column rules, {"name": function(row dict) -> bool}. A row fails the rule when
               the function returns False. Rows where the function raises also fail.
        """
        columns, n_rows = _to_columns(data)
        report = ValidationReport(n_rows=n_rows)

        def issue(column, row, check: str, message: str) -> None:
            report.n_errors += 1
            report.by_check[check] = report.by_check.get(check, 0) + 1
            if len(report.errors) < self.config.max_errors:
                report.errors.append({"column": column, "row": row, "check": check, "message": message})

        if self.config.on_extra_columns == "error":
            for name in columns:
                if name not in self.schema.names():
                    issue(name, None, "extra_column", f"column {name!r} is not in the schema")

        for column in self.schema.columns:
            if column.name not in columns:
                if column.required:
                    issue(column.name, None, "missing_column", f"required column {column.name!r} is missing")
                continue
            self._check_column(column, columns[column.name], report, issue)

        for name, rule in (rules or {}).items():
            for row in range(n_rows):
                record = {column: values[row] for column, values in columns.items()}
                try:
                    passed = bool(rule(record))
                except Exception:  # a rule that cannot be evaluated on a row counts as a failed row
                    passed = False
                if not passed:
                    issue(None, row, name, f"row {row} fails rule {name!r}")

        report.ok = report.n_errors == 0
        if not report.ok and self.config.raise_on_error:
            raise DataValidationError(report)
        return report

    @staticmethod
    def _check_column(column: Column, values: list, report: ValidationReport, issue: Callable) -> None:
        """Run every rule of one column over its values."""
        name = column.name
        pattern = re.compile(column.pattern) if column.pattern else None
        seen: dict = {}
        n_null = 0
        for row, value in enumerate(values):
            if _is_null(value):
                n_null += 1
                if not column.nullable:
                    issue(name, row, "null", f"{name}[{row}] is missing but the column is not nullable")
                continue
            if not _has_dtype(value, column.dtype):
                issue(name, row, "dtype", f"{name}[{row}] = {value!r} is not of type {column.dtype}")
                continue  # the remaining rules assume the right type
            size = len(value) if column.dtype == "str" else value
            if column.dtype != "bool":
                if column.min is not None and size < column.min:
                    issue(name, row, "range", f"{name}[{row}] = {value!r} is below the minimum {column.min}")
                if column.max is not None and size > column.max:
                    issue(name, row, "range", f"{name}[{row}] = {value!r} is above the maximum {column.max}")
            if column.allowed is not None and value not in column.allowed:
                issue(name, row, "allowed", f"{name}[{row}] = {value!r} is not one of {list(column.allowed)}")
            if pattern is not None and column.dtype == "str" and not pattern.fullmatch(value):
                issue(name, row, "pattern", f"{name}[{row}] = {value!r} does not match {column.pattern!r}")
            if column.unique:
                if value in seen:
                    issue(name, row, "unique", f"{name}[{row}] = {value!r} repeats row {seen[value]}")
                else:
                    seen[value] = row
        fraction = n_null / len(values) if values else 0.0
        report.null_fraction[name] = fraction
        if column.nullable and fraction > column.max_null_fraction:
            issue(name, None, "null_fraction",
                  f"{name}: {fraction:.1%} of the values are missing, the limit is {column.max_null_fraction:.1%}")
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
9, run with python3 -m unittest -v

Practice

Define a schema with an int id that is unique, an int age between 0 and 120, and a str plan with allowed values free and pro. Validate a table that breaks each rule once and print report.summary(), report.by_check and each error["message"]. Then add a cross-column rule through the rules argument and make one row fail it.

Check on learning

  1. An upstream team changes a height column from centimetres to metres. No type changes and nothing crashes. Which rule in a schema would catch it, and how would you choose its limits?
    A way to think about it

    Compare the range of plausible heights in each unit. Ask whether the two ranges overlap, and what a range rule does with a value of 1.8.

  2. Why should validation stop the pipeline (raise_on_error) before training, instead of logging a warning and carrying on?
    A way to think about it

    Follow the bad table forward: a model is trained, saved and deployed. Compare the cost of a stopped run with the cost of finding the problem a week later.

  3. Your schema allows the plans free and pro. Marketing launches a third plan and serving-time validation starts failing. Is the validator wrong to fail?
    A way to think about it

    Ask what the model does with a category it has never seen. Then decide who needs to know about the new plan, and when.

  4. Every individual value in a column passes its rules, yet the model's accuracy has dropped. What kind of change could cause that, and why can a per-value rule not see it?
    A way to think about it

    Think of a column whose values all stay inside 0 to 120 while their average moves from 35 to 60. Ask what you would need to compare to notice.

  5. A column is set to nullable with max_null_fraction 0.5. On Monday 2 percent of values are missing and on Tuesday 45 percent. Both pass. What does this say about how to set the limit?
    A way to think about it

    The limit should separate normal days from abnormal ones. Look at the history of the missing share and ask where a useful alarm line would sit.