🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Data Quality Validation: Expectations, Anomalies, Contracts

Data Pipelines & OrchestrationPipeline EngineeringđŸŸĸ Free Lesson

Quality is a measurable property

Data quality fails in private. A column arrives null, a currency silently switches to a new unit, a source stops delivering, and nothing breaks — until a forecast built on that data is presented to a board. The discipline of data quality engineering is the refusal to let those failures stay silent: every assumption a consumer makes is written down, executed on every batch, and turned into a visible outcome when it stops holding.

That framing matters because it separates quality from profiling. Profiling describes what the data looks like; validation asserts what it must look like and acts when it does not. A profile that says "12 percent nulls" is a report. An assertion that nulls must stay under two percent is a control. You need both, but only one of them stops a bad batch from reaching a dashboard.

By the end of this lesson you should be able to write an expectation suite for a real table, decide which checks should block a load and which should only warn, and design the quarantine and alerting path that makes a failure actionable rather than noisy.

The dimensions worth testing

Six dimensions cover almost every practical concern. Completeness asks whether expected data arrived at all — row counts, partition presence, and freshness are its instruments. Validity asks whether values make sense inside a domain: enum membership, numeric ranges, format strings. Uniqueness asks whether keys are keys. Consistency asks whether the same fact agrees across tables or across time. Accuracy is hardest, because it needs a trusted reference. Timeliness is completeness applied to schedules: the batch for 06:00 exists by 06:15 or it does not.

DimensionExample assertionBlocking?Typical tool
CompletenessRow count within 5 percent of trailing medianYesSQL, Soda Core
FreshnessMax event time within 30 minutes of nowYesOrchestrator sensor
Validitystatus in a known set, amount between boundsYesExpectation suite
UniquenessPrimary key has no duplicatesYesDistinct count query
ConsistencyOrder totals equal sum of line itemsWarn firstCross-table test
AccuracySampled rows match an external referenceNoPeriodic audit job
Schema stabilityColumn names and types unchangedYesContract check

The blocking column is the interesting one. A check that blocks a load protects consumers but halts delivery; a check that only warns preserves delivery but preserves the problem too. The workable compromise is tiering: blocking on structural and key-level failures that would corrupt downstream joins, warning on statistical drift that a human should look at, and never silently accepting either.

Expectations that run where the data lands

Frameworks such as Great Expectations and Soda Core exist so that assertions live next to the pipeline rather than in a wiki. The value is not the library; it is that the same expectation runs on every batch, produces a machine-readable result, and can be wired into the orchestrator's success criteria.

python
import great_expectations as gx
from great_expectations.core.batch import RuntimeBatchRequest

context = gx.get_context(mode="ephemeral")

suite_name = "orders_core_v1"
context.add_or_update_expectation_suite(expectation_suite_name=suite_name)

batch_request = RuntimeBatchRequest(
    datasource_name="warehouse",
    data_asset_name="orders_fact",
    runtime_parameters={"query": "SELECT * FROM orders_fact WHERE dt = '2026-01-12'"},
    batch_identifiers={"default_identifier": "daily"},
)

validator = context.get_validator(batch_request=batch_request, expectation_suite_name=suite_name)

validator.expect_table_row_count_to_be_between(min_value=1_000, max_value=5_000_000)
validator.expect_column_values_to_not_be_null("order_id")
validator.expect_column_values_to_be_unique("order_id")
validator.expect_column_values_to_be_in_set("status", ["new", "paid", "shipped", "cancelled"])
validator.expect_column_values_to_be_between("amount", min_value=0.01, max_value=1_000_000)
validator.expect_column_pair_values_a_to_be_greater_than_b(
    "paid_at", "created_at", or_equal=True, ignore_row_if="either_value_is_null"
)
validator.expect_compound_columns_to_be_unique(["order_id", "line_no"])

results = validator.validate()
failed = [r for r in results.results if r.success is False]
if failed:
    for r in failed:
        print(r.expectation_config.type, r.result)
    raise SystemExit(2)   # orchestrator reads a non-zero exit as a failed task

Two details separate a useful suite from a ceremonial one. Row count bounds must be a band rather than an exact number, because exact counts break the first time a legitimate early arrival changes the volume — and a check that is routinely overridden stops being a check. And uniqueness assertions must run on the composite key your join actually uses, not on the surrogate column you assumed was unique.

Detecting what rules cannot express

Rules catch violations you anticipated. Anomaly detection catches distribution shift: revenue that drops forty percent, a category that disappears, a column that becomes constant, a join key whose match rate falls. These are precisely the failures that no fixed threshold would have predicted, and they are caught by comparing each batch against its own history.

python
import numpy as np
import pandas as pd

def robust_z(values: pd.Series, window: int = 28) -> pd.Series:
    """Median absolute deviation z-score over a rolling window of prior batches."""
    median = values.rolling(window).median().shift(1)
    mad = (values - median).abs().rolling(window).median().shift(1)
    return 0.6745 * (values - median) / mad.replace(0, np.nan)

def detect(profile: pd.DataFrame) -> pd.DataFrame:
    """Flag batches whose key metrics deviate from trailing behaviour."""
    profile = profile.sort_values("dt").copy()
    profile["revenue_z"] = robust_z(profile["revenue"])
    profile["null_rate_z"] = robust_z(profile["null_rate"])
    profile["row_z"] = robust_z(profile["row_count"])
    flags = profile[
        (profile["revenue_z"].abs() > 4)
        | (profile["null_rate_z"].abs() > 4)
        | (profile["row_count"] == 0)
    ]
    return flags

def should_alert(flags: pd.DataFrame, consecutive: int = 2) -> bool:
    """Alert on repeat offenders, not on a single noisy point."""
    return len(flags) >= consecutive

Using median absolute deviation rather than a standard deviation matters when history contains its own incidents: the median and MAD ignore outliers that would otherwise flatten the threshold and hide a fresh anomaly. The consecutive-batch rule is equally important. One deviation is frequently a holiday, a promotion, or a late-arriving partition; two in a row is a change worth waking someone for.

Data contracts as prevention

Validation detects bad data after a producer has already shipped it. A data contract moves the conversation upstream: the producer publishes a schema, field semantics, freshness promise, and change policy, and both sides agree on what a breaking change is. Without one, schema drift arrives as a null-filled column or a renamed field discovered downstream.

A useful contract is small and enforced. It states the schema with types and required fields, the freshness bound, the volume envelope, the owner on both sides, and the deprecation window for changes. It is registered in a catalog, checked in CI when the producer changes its output, and verified at runtime by the same expectation suite that validates content. The organisational half matters more than the technical one: a contract without an agreed escalation path is documentation.

Failing well

A quality failure has three audiences — the pipeline, the on-call engineer, and the data consumer — and each needs something different. The pipeline needs a deterministic exit code so the orchestrator can retry or halt. The engineer needs a message naming the expectation, the observed value, the expected range, and a link to the failing sample. The consumer needs to know whether the previous good batch is still being served or the table is now a mixture of states.

Quarantine is what makes blocking safe. Write rejected rows to a side location with their raw payload and the failed expectation, publish the last known-good batch to the serving table, and let the repair flow reprocess quarantined rows once fixed. Without quarantine, a blocking check turns a data problem into a total outage of the feed; with it, the degradation is visible and bounded.

âš ī¸Alert on the trend, not only the threshold

A freshness check that fails at 06:30 every Monday and gets manually cleared teaches everyone to ignore it. Track alert frequency per check and retire or re-tune anything that fires without producing a real fix — an ignored alert is worse than no alert.

Common Mistakes

Writing assertions that must hold exactly, so they break on legitimate variation

Fix: Use bands derived from trailing distributions and revisit them when the business changes

Blocking the load with no quarantine path, turning a quality issue into a full outage

Fix: Park rejected rows, keep serving the last good batch, and reprocess after repair

Validating only the new batch and never comparing it to history

Fix: Add drift and anomaly checks on row counts, null rates, and key metrics

Letting alerts fire repeatedly without a follow-up action

Fix: Track alert volume per check, retire noisy checks, and assign an owner to every rule

Best Practices

  • Version expectation suites in source control alongside the transformation code
  • Separate blocking, warning, and informational severity and document which is which
  • Attach a sample of failing rows to every failure so triage starts from evidence
  • Pair every rule with a freshness and completeness check so silence is detectable
  • Review the suite quarterly: new columns and new joins deserve new assertions

Interview Questions

Q1: What is the difference between data profiling and data validation?

Profiling summarises what the data contains; validation asserts what it must contain and acts when the assertion fails.

Q2: Why should row-count checks use a range instead of an exact value?

Exact values break on legitimate variation, and a check that is habitually overridden stops functioning as a control.

Q3: How does anomaly detection complement rules?

Rules catch known violations; anomaly detection catches distribution shifts that no fixed threshold anticipated.

Q4: What does a data contract contain?

Schema and types, field semantics, freshness and volume bounds, ownership, and a change or deprecation policy agreed by both sides.

Key Takeaways

  • Validation turns consumer assumptions into executable, per-batch assertions
  • Tier checks by severity so structural failures block while statistical drift only warns
  • Anomaly detection on trailing distributions catches what fixed rules cannot anticipate
  • Quarantine keeps a blocking check from becoming an outage of the whole feed
  • Contracts move prevention upstream, which is cheaper than any amount of downstream detection
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Data Engineering Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement