InterviewsVector
Arc 1
Systems labFoundation70 min estimateOriginal publication

Data Contracts for Models

A tensor can have the expected shape and still encode the wrong population, unit, moment in time, or permitted purpose. The contract must protect meaning as well as syntax.

Authorship
InterviewsVector
Published / updated
2026-08-11 / 2026-08-11
Review status
Artifact tests passing · primary sources recorded

Original InterviewsVector material. Code examples are covered by repository tests and primary references are recorded. No named human reviewer is claimed.

The decision in one pass

A model data contract combines five obligations: structural schema, business meaning, temporal availability, lineage, and permitted use. Validate it where data enters the platform, when features are materialized, before training or indexing, and again at serving boundaries. Version the contract independently from a dataset snapshot; reject or quarantine incompatible records instead of coercing them into plausible inputs. A valid type is necessary, never sufficient.

Why this matters

Many damaging model failures are syntactically valid: currency changes without a unit change, an identifier is reused, a feature arrives only after the prediction, a warehouse backfill rewrites history, or data collected for support is reused for targeting. Model code cannot infer these violations from a float or string.

You will be able to

  • Distinguish structural validation from semantic, temporal, provenance, and use contracts.
  • Represent event time, feature availability time, decision time, and label time without leakage.
  • Build a versioned model-input contract with deterministic record validation.
  • Plan compatibility, quarantine, monitoring, and rollback for contract changes.
  • Explain why inferred schemas and aggregate drift checks do not replace domain ownership.

Prerequisite contract

Your Vector Loop for this lab

  1. 01

    Model

    Treat a model input as a governed claim about an entity at a specific time.

  2. 02

    Derive

    Separate schema, meaning, availability, lineage, and allowed-use invariants.

  3. 03

    Build

    Implement a versioned contract and deterministic record validator.

  4. 04

    Stress

    Inject leakage, unit changes, unknown fields, stale lineage, and prohibited reuse.

  5. 05

    Operate

    Enforce contracts across ingestion, materialization, training, and serving.

  6. 06

    Defend

    Defend compatibility and failure policy without claiming that schema equals quality.

Contract the claim, not just the container

A feature row is a set of claims: this value describes this entity, means this business concept, was produced from these sources and transformations, was available by this time, and may be used for this purpose. The storage type says almost none of that. A robust contract makes the claims explicit enough for producers and consumers to test independently.

Each layer answers a different question; passing one cannot stand in for the others.
LayerExample obligationViolation that passes a type check
schemaaccount_age_days is a non-negative integerboolean is accepted as integer in some runtimes
meaningcompleted days since account creationproducer switches to hours
timefeature was available before the decisionbackfilled value leaks future information
lineagesnapshot and transform version are knownquery changes behind the same table name
useapproved for refund triagesupport text is reused for ad targeting

Model what was knowable at the decision

event_time ≤ available_at ≤ decision_time

For an online input, the underlying event occurs, the derived feature becomes available, and only then may the decision consume it. Labels often become available later and belong to evaluation or training—not the serving feature row.

ClockQuestionTypical bug
event timeWhen did the represented event happen?processing time is mistaken for customer behavior time
available atWhen could this exact value be consumed?a backfill makes future knowledge appear historical
decision timeWhen did the system need the feature?offline join ignores the production cutoff
label timeWhen did the outcome become observable?label or proxy leaks into model input

Use timezone-aware timestamps and define inclusivity, late-arrival policy, and correction behavior. For batch training, construct point-in-time joins using availability, not merely event time. For retrieval, version document validity and index inclusion time so an evaluation cannot retrieve a document that was unavailable at the simulated query time.

Build a versioned contract that fails visibly

The reference artifact defines feature kinds, meanings, finite bounds, entity and time fields, intended and prohibited uses, and lineage sources. It runtime-allowlists feature kinds, rejects unknown fields and non-finite numeric values, treats booleans as distinct from integers, requires timezone-aware timestamps, and checks that feature availability does not cross the decision cutoff. The implementation is deliberately dependency-free so the contract mechanics stay inspectable.

model_data_contract.py
1if __name__ == "__main__":
2 valid_errors = validate_record(
3 SUPPORT_REQUEST_CONTRACT,
4 VALID_RECORD,
5 use="refund-triage",
6 decision_time="2026-08-11T09:00:05Z",
7 )
8 print("valid_record=PASS" if not valid_errors else "valid_record=FAIL")
9
10 rejected = {**VALID_RECORD, "features_available_at": "2026-08-11T09:00:06Z"}
11 rejected_errors = validate_record(
12 SUPPORT_REQUEST_CONTRACT,
13 rejected,
14 use="automated-refund",
15 decision_time="2026-08-11T09:00:05Z",
16 )
17 print("rejected_record=FAIL" if rejected_errors else "rejected_record=PASS")
18 for validation_error in rejected_errors:
19 print(f"- {validation_error}")

Expected output

valid_record=PASS
rejected_record=FAIL
- use 'automated-refund' is prohibited
- available_at must not be after decision_time

Verify: Run python3 -m unittest discover courses/ai-engineering/reference-impl/data_contract.

  1. 01Name the entity and grainState what one row represents and the stability rules for its key. Many duplicate and join failures begin with an implicit grain.
  2. 02Write feature meaningsInclude unit, population, transformation, missing-value semantics, and any vocabulary or normalization rules.
  3. 03Bind timeRecord event and availability clocks, cutoff behavior, late data, correction policy, and label timing.
  4. 04Bind lineage and useIdentify source snapshots, transform revisions, responsible owners, intended uses, prohibited uses, and retention requirements.
  5. 05Choose failure behaviorReject, quarantine, degrade, or alert explicitly. Silent coercion creates plausible but semantically invalid model inputs.

Version compatibility around consumer behavior

Contract versioning is a change-management policy, not decoration. A field addition is compatible only if deployed consumers tolerate it; a narrower range is compatible only if existing valid producers already satisfy it; a meaning or unit change is breaking even when name and type stay constant. The reference artifact uses semantic x.y.z notation, but the team must define what major, minor, and patch mean for its producers and consumers.

ChangeDefault classificationSafe migration evidence
rename or remove required fieldbreakingdual-write and consumer cutover
change unit or business meaningbreakingnew field/version plus backfill provenance
add optional fieldpotentially compatibleunknown-field behavior tested across consumers
tighten allowed rangepotentially breakinghistorical and live producer conformance
new intended usegovernance reviewauthorization and purpose review, not just schema rollout
new source or transformlineage changeshadow comparison and point-in-time validation

Stress semantics that ordinary validators miss

  1. 01Keep the type, change the unitEmit account age in hours under a field documented as days. Range and type checks may pass while model behavior shifts.
  2. 02Backfill the futureCorrect historical rows after outcomes are known, then verify that training reconstructs what was available at the original decision cutoff.
  3. 03Reuse an identifierMerge records from a source that recycles keys. Test entity namespace and grain before joins create silent collisions.
  4. 04Add a helpful fieldSend an unknown feature to a strict consumer and a permissive consumer. Compare whether schema evolution is explicit or silently ignored.
  5. 05Change the populationKeep every record valid but route a new country, language, product tier, or acquisition channel. Contract validity and distribution fitness are separate checks.
  6. 06Reuse data for another purposeAttempt a prohibited use through the same technically valid pipeline and verify that policy is enforced before consumption.

Enforce the same meaning across the lifecycle

BoundaryValidateEvidence to retain
ingestionsource identity, schema, classification, event timerejected counts and source version
transformationgrain, joins, units, availability, lineagetransform revision and point-in-time tests
training/indexingsnapshot, contract version, intended use, slicesmanifest and validation report
serving/retrievalcompatible version, freshness, range, policyresolved versions and failure path
monitoringvalidity, missingness, drift, skew, late dataslice trends and incident linkage
deletionretention and derived copiespropagation status and audit record
  • Track contract violations separately from distribution drift and model-quality regression; they need different owners and responses.
  • Quarantine invalid batches or records with source evidence. Do not repair them invisibly inside the trainer.
  • Compare training and serving transformations from shared, versioned definitions while still testing both execution paths.
  • Include contract version and source snapshot in experiment manifests, model cards, index manifests, and inference traces.
  • Define freshness and late-arrival service objectives from product decisions rather than choosing one universal threshold.
  • Coordinate breaking changes with dual-read or dual-write periods, shadow validation, rollback, and removal dates.

Operate at three altitudes

Production lens

  • Version contract, snapshot, transform, vocabulary, and use authorization independently and emit resolved versions together.
  • Validate point-in-time availability in offline joins so evaluation matches what serving could actually know.
  • Expose violation counts, late data, missingness, drift, and training-serving skew by source and product slice.
  • Keep quarantine and rollback paths for incompatible producer changes; never normalize a breaking semantic change invisibly.

Staff lens

  • Give every high-value data product a producer owner, consumer owners, compatibility policy, and deprecation process.
  • Separate technical conformance from governance approval; a valid record can still be prohibited for the requested use.
  • Require lineage that reaches source and transformation revisions without forcing all platforms into one storage product.
  • Treat contract enforcement as shared infrastructure while domain meaning stays with accountable domain experts.

Interview defense

Design a data contract for features used by a real-time model.

I would define entity grain and stable keys; types, presence, bounds, vocabularies, units, and business meanings; event, availability, decision, and label-time semantics; source and transform lineage; intended and prohibited uses; and version compatibility. Producers validate at ingestion and materialization, consumers verify compatible versions before training and serving, and invalid data is rejected or quarantined with evidence. I would test point-in-time joins, training-serving skew, drift, late data, and breaking migrations separately because schema conformance alone does not establish correctness or permission.

Expect the interviewer to press on

  • How do you detect feature leakage from a backfill?
  • Is adding an optional field always backward compatible?
  • Where should permitted use be enforced?
  • How do schema validation and drift detection differ?

Misconceptions to remove

A JSON or protobuf schema is the complete data contract.

It can express structure and some value constraints, but meaning, time, lineage, purpose, ownership, and migration behavior need explicit contracts too.

If offline data is historically correct, it is safe for training.

The value must also have been available at the simulated decision time; later corrections and labels can leak future information.

An automatically inferred schema should become the production contract.

Inference describes observed data and can overfit one snapshot. Domain owners must define intended ranges, meanings, evolution, and use.

Schema validity means the data is suitable for the model.

A fully valid dataset can have shifted populations, bad labels, prohibited use, or insufficient coverage; suitability needs additional evidence.

Check your model

1. Why is available_at different from event_time?

An event may occur before the pipeline observes or computes its feature. The model may use only information available by the decision cutoff, not all events that happened earlier.

2. Why can a unit change be breaking when the field remains a number?

Consumers interpret values according to the prior meaning and scale, so unchanged syntax produces systematically wrong features without a validation error.

3. What does provenance add beyond a dataset digest?

It connects the fixed bytes to source entities, transformations, versions, and responsible agents, enabling impact analysis and reconstruction rather than identity alone.

Prove the mechanism

Write and enforce a contract for one model or retrieval input. Include grain, semantics, units, event and availability time, lineage, intended and prohibited use, compatibility rules, and three failure fixtures that pass ordinary type checks.

Add a production constraint

Build a point-in-time join test that replays historical decisions, then add contract-diff logic that classifies proposed changes against real producer and consumer fixtures.

Artifact: Versioned model data contract

courses/ai-engineering/reference-impl/data_contract/model_data_contract.py

Download reference implementation

Primary references and next links

References

  1. 1. JSON Schema Validation: A Vocabulary for Structural Validation of JSON

    JSON Schema specification. Official specification for instance types, required properties, value constraints, and validation outcomes.

  2. 2. PROV-O: The PROV Ontology

    World Wide Web Consortium. W3C Recommendation defining entities, activities, agents, derivation, and responsibility for interoperable provenance.

  3. 3. TensorFlow Data Validation

    TensorFlow. Official guidance for checked schemas, anomaly detection, training-serving skew, and drift validation.

Continue through the graph

Glossary: data contract · entity grain · event time · availability time · lineage · training-serving skew · feature leakage