ML data engineering
Data Quality Rules, Constraints, and Release Gates
Design validation layers and release responses that catch real ML data failures without freezing legitimate change.
By the end you can
- Distinguish invariants, service objectives, statistical guardrails, and observations
- Write quality rules with scope, evidence, ownership, and response
- Select validation layers for structural, semantic, temporal, and population failures
- Manage the lifecycle of inferred and manually authored controls
Comparison
Not every data expectation should block a release
A quality program needs several response levels. Hard failure is costly, and silence is dangerous.
The service-objective column is not an abstraction invented for teaching. Banking supervisors wrote it into a standard. BCBS 239, issued by the Basel Committee in January 2013, sets out fourteen numbered principles. Principle 3 covers accuracy and integrity, Principle 4 completeness, Principle 5 timeliness. G-SIBs designated in 2011 or 2012 had until January 2016 to comply.
Five years after publication, and two years past that deadline, the European Central Bank went to look. It reviewed 25 significant institutions and reported, in May 2018: “Thus far, none of those significant institutions – some of which are classified as global systemically important banks – have fully implemented the BCBS 239 principles.”
The supervisor attributed the weaknesses mainly to unclear responsibility and accountability for data quality. Note what that diagnosis is not. It is not that the thresholds were wrong, or that the banks lacked metrics. Twenty-five of the largest institutions in Europe had a numbered standard demanding accuracy, completeness and timeliness, and zero of them had it working. A target with no owner and no prescribed response is an observation wearing the costume of a control.
Invariant
A rule whose violation means the data cannot represent a valid state.
- Examples: impossible key scope or future feature time
- Usually blocks or quarantines
- Requires owner and remediation
- Should be rare and precise
Service objective
A consumer-centered target for freshness, coverage, or correctness over time.
- Measured as a rate or distribution
- Allows an error budget
- Supports escalation policy
- Connects reliability to consequence
Statistical guardrail
A deviation signal that prompts investigation rather than automatic rejection.
- Useful for drift and tails
- Needs reference and seasonality
- Can create false positives
- Best paired with slice context
Observation
A recorded metric retained for diagnosis without an immediate action threshold.
- Builds history
- Supports future baselines
- Low operational burden
- Not a substitute for controls
A useful rule includes action, scope, and explanation
“Null rate below five percent” is incomplete. The rule should name the field, population, window, reference, severity, owner, and response when it fails.
Rules should distinguish producer defects from legitimate population change. A holiday can alter order volume without breaking the pipeline. A stable row count can hide duplicated events.
So the output of validation has to carry evidence: violating examples, affected slices, first-seen time, lineage, and the prior successful version.
Amazon built exactly that and published the design in 2018. Deequ offers “a declarative API, which combines common quality constraints with user-defined validation code, and thereby enables ‘unit tests’ for data”. It runs the workload “by translating it to aggregation queries on Apache Spark”, so the check executes at the size of the table rather than at the size of a sample.
Deequ also retains its historic quality metrics, which is the precondition for anomaly detection over the series. Without the stored history there is no reference. Without a reference, a threshold is a guess about yesterday.
A threshold without an action contract creates either alert fatigue or silent acceptance.
Visual
Validation operates at several layers of meaning
Higher layers catch failures that lower layers cannot see.
Google runs this stack at scale and published how in 2019. Its data validation system is “deployed in production as an integral part of TFX” and “used by hundreds of product teams” to “continuously monitor and validate several petabytes of production data per day”. The paper names the hard part as pipelines that must “soldier on in the face of unexpected patterns, schema-free data, or training/serving skew”. Scale changes which checks are affordable.
Field semantics — the second layer — carries the most expensive documented failure of the five. NASA lost the Mars Climate Orbiter at Mars on 23 September 1999. The mishap board’s report states: “The MCO MIB has determined that the root cause for the loss of the MCO spacecraft was the failure to use metric units in the coding of a ground software file, “Small Forces,” used in trajectory models.” Thruster impulse data had been delivered in pound-seconds where the software interface documentation specified Newton-seconds. The small-forces values feeding orbit determination were low by a factor of 4.45. At insertion the trajectory ran approximately 170 kilometres lower than planned, and post-hoc estimates put periapsis at 57 km against a survivable minimum of 80 km. The U.S. General Accounting Office recorded the same cause independently: “The loss was due to the mistaken use of English rather than metric units in the navigation software.”
Every value in that file parsed. Every value was typed, and every value fell inside a plausible numeric range. The encoding layer had nothing to report, because no rule compared the delivered unit against the declared one. The FDA states the general form of the defect in one sentence about laboratory records: “the number ‘23’ is meaningless without metadata, such as an indication of the unit ‘mg.’” The values were fine. What was missing was what they meant.
Population fitness sits at the top because it is the layer at which every record can be individually valid and the dataset still wrong. Three researchers audited the test sets of ten of the most widely used vision, NLP and audio benchmarks in 2021. Their estimate: “we estimate an average of at least 3.3% errors across the 10 datasets, where for example label errors comprise at least 6% of the ImageNet validation set”. Human crowdworkers confirmed 51% of the algorithmically flagged candidates as genuine errors.
The consequence is a reversed decision, not just a worse number. On corrected labels ResNet-18 overtakes ResNet-50, once the prevalence of originally mislabelled test examples rises by just 6 percentage points. A separate group re-annotated the same ImageNet validation set and landed in the same place: “we find the original ImageNet labels to no longer be the best predictors of this independently-collected set”. No row-level validator can see any of this. No individual row is malformed.
- 01
Encoding and schema
Can the record be parsed, typed, and interpreted structurally?
- 02
Field semantics
Are units, categories, ranges, and missing states legitimate?
- 03
Relational consistency
Do keys, joins, totals, and effective intervals reconcile?
- 04
Temporal correctness
Were observations available and ordered under the declared cutoff?
- 05
Population fitness
Does the released cohort cover the intended users, conditions, and rare cases?
The higher the layer, the more domain context the validator needs.
Example
Five green checks that can accompany a bad dataset
These examples show why row-level schema validation is necessary but insufficient. Three of the five are documented failures with a public record and a cost attached. In each case the structural checks were correct.
- Every field parses and every value is in range, but the unit is wrong. Mars Climate Orbiter’s ground software file supplied thruster impulses in pound-seconds where the interface documentation specified Newton-seconds, low by a factor of 4.45, and on 23 September 1999 the spacecraft arrived approximately 170 km below the planned trajectory.
- Dashboards look healthy while roughly one case in five is missing. Public Health England failed to report 15,841 positive COVID-19 results between 25 September and 2 October 2020, 11,968 of them from 30 September to 2 October, because case rows were silently truncated once an Excel file hit its row limit.
- Category values remain allowed while a measurable share of them is simply wrong: at least 3.3% of test labels on average across ten standard benchmarks, at least 6% in the ImageNet validation set. That is enough to change which model appears to win.
- Freshness meets the target, but a backfill makes future data visible in historical examples.
- Global positive rate is stable, but label coverage collapses for one region.
Key idea
Inferred thresholds can institutionalize yesterday’s bias
A validator can infer allowed categories or numerical ranges from a reference dataset, which is useful for discovering sudden changes, but the reference may already underrepresent a population or omit a legitimate rare case. Review inferred rules with domain owners and slice analysis. Distinguish “unseen before” from “invalid by definition.” Otherwise the data gate can reject the exact expansion in coverage that the product intended to support.
The cost of confusing the two has been measured. A commercial risk-prediction algorithm affecting millions of patients was trained on historical health-care costs as a proxy for illness. Less had been spent on Black patients at the same level of sickness. The algorithm absorbed that regularity and re-emitted it as a statement about who needs help. Obermeyer and colleagues dissected it in Science in 2019, and put a number on the correction: “Remedying this disparity would increase the percentage of Black patients receiving additional help from 17.7 to 46.5%.” The regularity in the reference data was entirely real. Its authority was not.
The gap was wide enough to draw regulators within days of publication. On 25 October 2019 the New York State Department of Financial Services and Department of Health wrote jointly to the CEO of UnitedHealth Group Incorporated about the same algorithm, Optum’s Impact Pro. The company had to demonstrate that the tool was not racially discriminatory “or to cease using Impact Pro”.
Historical regularity is evidence, not authority.
Analogy
Preflight checks, and what a warning light means
Schema checks confirm that the instruments power on. Invariants verify that readings obey physical relationships, and service objectives track reliability across flights. A warning light does not diagnose every cause; it names one state the crew must answer in a prescribed way. Some warnings ground the aircraft, while others permit a controlled fallback.
That last sentence is not a figure of speech. Two sensors measuring one quantity disagreed for a whole flight, and in 2019 the National Transportation Safety Board wrote it down. Of Lion Air flight 610 on 29 October 2018 it states: “The airplane’s digital flight data recorder (DFDR) recorded a difference between the left and right angle of attack (AOA) sensors that was present during the entire accident flight; the left AOA sensor was indicating about 20° higher than the right AOA sensor.” On Ethiopian flight 302 on 10 March 2019 the left AOA reading rose to 74.5°, 59.2° higher than the right. No physical state explains a gap of that size. This is the purest form of an invariant, and it is not a threshold anyone had to tune.
The regulator’s answer was graded rather than absolute. The FAA did not ground the fleet. Its emergency airworthiness directive of 7 November 2018 prescribed one operating response instead, a runaway stabilizer trim procedure added to the Airplane Flight Manual. Its Unsafe Condition paragraph explains the signal it was answering: “This AD was prompted by analysis performed by the manufacturer showing that if an erroneously high single angle of attack (AOA) sensor input is received by the flight control system, there is a potential for repeated nose-down trim commands of the horizontal stabilizer.” The same NTSB report documents the failure mode of an alerting scheme with no priority contract. A single erroneous input fired several alerts at once, and the crews “lacked tools to identify the most effective response”.
An altimeter has one correct behavior, and any departure from it is a fault. Data populations are not like that. They change through product and social behavior, so a new but valid category arrives at the gate looking exactly like a broken instrument.
Good validation couples a signal with a proportionate operating response.
Rules need owners, versioning, and retirement
Quality controls accumulate as systems evolve. Without review, teams inherit obsolete thresholds, duplicate alerts, and exceptions that nobody understands. Version rules with the data contract, record suppressions and overrides, and evaluate which incidents each rule actually detects. Retire controls whose premise no longer holds. A release report should show rule version, result, affected population, action taken, and unresolved waivers. That history is part of the dataset’s evidence.
Two medicines regulators already require this discipline as a condition of releasing a batch, and they arrived at it independently. The FDA defines data integrity as completeness, consistency and accuracy under the ALCOA attributes — attributable, legible, contemporaneous, original, accurate — and refuses to let the obligation stop at the moment of capture. Its December 2018 guidance is explicit: “Data integrity is critical throughout the CGMP data life cycle, including in the creation, modification, processing, maintenance, archival, retrieval, transmission, and disposition of data after the record’s retention period ends.” Questions 7 and 8 of the same guidance cover audit-trail review, which is the release report’s ancestor.
The MHRA states the ownership half. Its March 2018 guidance requires that “Data governance should address data ownership and accountability throughout the lifecycle, and consider the design, operation and monitoring of processes/systems to comply with the principles of data integrity including control over intentional and unintentional changes to data.” It carries the same ALCOA attributes.
Ownership, lifecycle, controlled change: that is also what BCBS 239 asked of banks from January 2013. By the ECB’s May 2018 count, none of the 25 significant institutions reviewed had fully implemented it, and the supervisor blamed unclear responsibility and accountability for data quality rather than any missing metric. Two industries, two regulators each, one finding. The hard part of a quality rule is not the threshold. It is the name attached to it, and the record of what happened when it fired.
A quality rule is production logic and deserves the same lifecycle discipline as feature code.
Key takeaways
- Invariants, service objectives, statistical guardrails and observations should trigger different responses. BCBS 239 named accuracy, completeness and timeliness as Principles 3, 4 and 5 in January 2013, and in May 2018 the ECB still found that none of 25 significant institutions had fully implemented them.
- A validation rule needs scope, reference, severity, owner, diagnostics and an explicit action contract. Deequ compiles declarative constraints into aggregation queries on Apache Spark and retains the metric history that any reference threshold depends on.
- Quality checks should cover encoding, semantics, relationships, temporal correctness and population fitness. Mars Climate Orbiter's pound-seconds parsed cleanly, ran low by a factor of 4.45, and put the spacecraft roughly 170 km below its planned trajectory.
- Green schema checks can coexist with unit changes, row substitution, leakage and slice-specific coverage loss. Public Health England's 15,841 truncated cases and an average of at least 3.3% mislabelled benchmark test examples both passed structural validation.
- Automatically inferred thresholds need domain and slice review, because history can encode bias or omit valid novelty. A cost-based health risk model selected 17.7% of Black patients for extra help where an illness-based target would select 46.5%.
- Version quality rules, evaluate them against incidents, waive them transparently, and retire them when their premise expires. The FDA and the MHRA both make ownership and accountability across the whole record lifecycle a release condition.