Chapter 1 · Reproduce the workflow

Contracts before models

Contracts keep bad meaning from becoming good-looking features.

65–90 min4 key conceptsReviewed 26 Aug 2026
01 · Production proposition

A churn notebook cannot be reproduced by the teammate expected to ship it.

This chapter moves from write semantic expectations to version compatible change. We will make the idea concrete in a small code example before placing it back inside a production system with a declared latency, cost, and operator-capacity budget.

Decision

Additive nullable fields may be compatible; unit or meaning changes require a new contract version and consumer migration.

Evidence

Verify the behavior illustrated in validate_rows.py, then measure decision utility, slice reliability, and system latency.

Failure consequence

A mutable data/latest path and unpinned dependencies create a different model from the same command. An unsafe release must degrade to a named baseline or the last known-good version.

02 · Guided chapter

Build the idea one layer at a time.

A model cannot repair a column whose meaning changed from dollars to cents. The earliest useful ML test is therefore a data contract, not an accuracy score.

A contract states more than column names. It captures types, units, allowed ranges, null policy, uniqueness, and the event whose value a row represents. These rules turn silent semantic drift into a visible failure at the boundary.

Validation belongs before feature computation because downstream transforms often make bad input look plausible. A negative age can be standardized into an ordinary-looking number; rejecting it first preserves the real diagnosis.

Keep in view
  • immutable data snapshots
  • dependency locks
  • run manifests
  • schema contracts
WORKED PATH

Follow the reasoning before touching the code.

  1. 01

    Write semantic expectations

    For every required field, document its type, unit, valid domain, null policy, and producing owner.

  2. 02

    Validate at ingestion

    Fail a run with row-level evidence before invalid values enter feature or label logic.

  3. 03

    Version compatible change

    Additive nullable fields may be compatible; unit or meaning changes require a new contract version and consumer migration.

pythonvalidate_rows.py
rows = [
    {"customer_id": "c-1", "age_years": 34, "spend_usd": 81.5},
    {"customer_id": "c-2", "age_years": 19, "spend_usd": 12.0},
]
contract = {
    "age_years": (int, 0, 120),
    "spend_usd": ((int, float), 0, 1_000_000),
}
for row_number, row in enumerate(rows, start=1):
    assert row["customer_id"], f"row {row_number}: empty customer_id"
    for name, (kind, low, high) in contract.items():
        value = row[name]
        assert isinstance(value, kind), f"row {row_number}: {name} type"
        assert low <= value <= high, f"row {row_number}: {name} range"
print("contract v1 accepted", len(rows), "rows")

Enforce a tiny typed and bounded input contract.

READ THE EXAMPLE

What to notice

  • The error identifies both the row and violated field, which makes a producer incident actionable.
  • The range check encodes units implicitly; a cent-valued spend will often expose itself immediately.
YOUR TURN Pause and predict before revealing the answer.

Change the second age to -1, then change spend_usd to the string "12.0". Which contract rule catches each defect?

Need a hint?

Range and runtime type are separate promises.

Check your reasoning

The age fails its range assertion; the string spend fails its type assertion before any numeric comparison is trusted.

Bring forward

Lessons 1 in this course.

03 · Formal treatment

Connect the chapter to the course’s quantitative spine.

Contracts keep bad meaning from becoming good-looking features. The content-addressed run identity below is the shared course-level lens that helps quantify the surrounding system. Name each symbol, check its units or shape, and use only values that were available at the production cutoff.

Formal treatment
run_id⁡=SHA256⁡(code∥data∥image∥config∥seed)\operatorname{run\_id} = \operatorname{SHA256}(\mathrm{code} \mathbin{\|} \mathrm{data} \mathbin{\|} \mathrm{image} \mathbin{\|} \mathrm{config} \mathbin{\|} \mathrm{seed})

Content-addressed run identity

Symbol, shape or unit contract
SymbolMeaning / shape / unit
codesource revision digest
dataimmutable dataset digest
imageOCI image digest
seeddeclared random seed
Open derivation and numerical substitution

Start from the production quantity being optimized, substitute the observed values with their declared units, then isolate the model-controlled term. Preserve shape annotations at each step so broadcasting or aggregation cannot silently change the result.

  1. Write the named inputs: code, data, image, seed.
  2. Substitute one small, hand-checkable batch before vectorizing.
  3. Calculate an independent reference value and compare within a declared tolerance.
# equation → code contract
inputs = validate_shapes_and_units(batch)
value = compute_c01(inputs)
assert is_finite(value)
04 · Deterministic lab

Change one assumption and make the tradeoff visible.

Use the worked chapter as your prediction, then change one input in the lab and explain why the output moves. The lab runs predefined TypeScript and never executes learner code, so the focus stays on the concept rather than setup.

Simplified simulation

Reproducibility fault injector

Change how many declared inputs remain mutable and observe replay parity.

inputs
Primary72.0%
Secondary3/5 captured
DiagnosisManifest incomplete

Assumption: Each mutable input independently creates a 14-point replay risk.

Open nonvisual data table
ItemComputed stateInterpretation
input 1mutablereplay risk
input 2mutablereplay risk
input 3content-addressedverified
input 4content-addressedverified
input 5content-addressedverified
05 · Production implications

Trace the complete operating path.

Carry the chapter’s central idea into the system: Contracts keep bad meaning from becoming good-looking features. The path below shows where that reasoning needs an artifact, a test, an owner, or a fallback.

  1. 01

    Turn “Write semantic expectations” into a written invariant and a failing test.

  2. 02

    Promote validate_rows.py from illustration to a versioned implementation with representative fixtures.

  3. 03

    Use “Version compatible change” as the release checkpoint: Additive nullable fields may be compatible; unit or meaning changes require a new contract version and consumer migration.

  4. 04

    Serve or materialize behind explicit a declared latency, cost, and operator-capacity budget.

  5. 05

    Join telemetry to mature outcomes and retain a rollback path.

Observability

Join service health, input quality, prediction distributions, slice behavior, and mature outcomes by exact version.

Cost

Measure storage, preprocessing, compute, queueing, and human review under a representative arrival pattern.

Failure modes

A mutable data/latest path and unpinned dependencies create a different model from the same command. Add a detector, owner, mitigation, and stop condition for this class of failure.

Alternatives

Compare a rule, a simpler statistical baseline, and a different system boundary before adding model complexity.

06 · Check understanding

Explain the contract, not just the vocabulary.

Browser-graded checkpointPass ≥ 80%
01Why record an image digest?
02What makes a retry safe?
03Does reusing a seed make changed data reproducible?
07 · Apply in production

Reproducible baseline package

Design a Docker-only workflow that validates data, trains, evaluates, serializes, performs golden inference, and emits complete lineage.

  • Run manifest and data contract
  • Raw-input golden parity test
  • Failure and retry runbook
  • Model card with residual nondeterminism
Open assignment and rubric
08 · Sources & next depth

Read primary material with a purpose.

09 · Production resolution

Return to the opening failure.

Reject promotion when any artifact lacks lineage, golden raw-request parity, or a failure-safe recovery path.

For this lesson, the release evidence is the worked code example, a hand-checked formal result, deterministic simulation output, a ≥80% checkpoint, the production rubric, and a named fallback. The course resolves when the system can produce a seeded, tested, packaged, versioned training workflow with a model card.