Part IV — Expert Production Engineering · Chapter 19 · Lesson 6 of 7 · 6 min read
Lesson 6: Pipelines, Persistence, Schema Validation, and Reproducibility
Lesson level: Advanced
Purpose: Package preprocessing, model, calibration, and decision rules into one artifact that validates its inputs, can be saved and reloaded safely, and can be rebuilt bit-for-bit from recorded inputs.
Learning objectives
By the end of this lesson you will be able to:
- compose preprocessing and model steps into a single pipeline
- route different column types to different transformers
- define and enforce an input schema at fit and predict time
- persist a fitted pipeline with metadata, and reload it safely
- record everything needed to reproduce a model exactly
- test that a reloaded pipeline produces identical predictions
6.1 Why pipelines
Lessons 1 to 5 built a chain: impute, scale, encode, fit a model, calibrate, apply a threshold. Done as separate steps, the chain is easy to break — a step can be fitted on the wrong data, skipped in production, or applied in a different order. A pipeline makes the chain one object with one fit and one predict:
- Every step is fitted only on the data passed to fit, so cross-validation and search (Lesson 4) cannot leak.
- Production calls apply exactly the same steps in exactly the same order.
- The whole chain can be saved, versioned, reviewed, and reloaded as one unit.
6.2 Column-wise preprocessing
Real tables mix types. A column transformer sends numeric columns to imputation and scaling, categorical columns to encoding, and drops or passes through the rest, then joins the results in a fixed, documented order.
Illustrative listing.
from pealang.ml import (Pipeline, ColumnTransformer, SimpleImputer,
StandardScaler, OneHotEncoder, LogisticRegression)
numeric = Pipeline([("impute", SimpleImputer(strategy="median", add_indicator=True)),
("scale", StandardScaler())])
categorical = OneHotEncoder(handle_unknown="unknown_bucket", min_frequency=20)
prep = ColumnTransformer([
("num", numeric, ["age", "tenure_days", "monthly_spend", "tickets_90d"]),
("cat", categorical, ["region", "plan", "channel"]),
], remainder="drop")
churn_pipe = Pipeline([("prep", prep),
("model", LogisticRegression(penalty="l2", seed=42))])
Use remainder="drop" deliberately: a new column that appears upstream should not silently enter the model. Adding a feature is a model change that deserves review and retraining.
6.3 Input schema validation
A fitted pipeline assumes a particular input shape. Make that assumption explicit with a schema — the data foundation's Schema and Field types from Chapter 16 — and check it at both fit time and predict time.
- Presence and type: every required column exists with the expected data type.
- Nullability: which fields may be null, and which must not.
- Ranges and domains: numeric bounds (age 18–120) and allowed category sets, with a policy for unseen values.
- Extra columns: ignored and reported, or rejected.
Decide what a violation does. For batch scoring, reject offending rows and report them with reasons; for an online service, return a clear validation error rather than a prediction from malformed input. Never let a model score data it was not designed for and present the result as normal. The rejection rate per field is one of the best early warnings of upstream change, and Chapter 20 monitors it.
Illustrative listing.
from pealang.data import Schema, Field, DataType
INPUT_SCHEMA = Schema([
Field("customer_id", DataType.STRING, nullable=False),
Field("age", DataType.INT64, nullable=True, min=18, max=120),
Field("tenure_days", DataType.INT64, nullable=False, min=0),
Field("monthly_spend", DataType.FLOAT64, nullable=True, min=0),
Field("tickets_90d", DataType.INT64, nullable=False, min=0),
Field("region", DataType.STRING, nullable=False),
Field("plan", DataType.STRING, nullable=False),
Field("channel", DataType.STRING, nullable=True),
])
report = INPUT_SCHEMA.validate(batch)
valid_rows, rejected = report.valid, report.rejected
6.4 Persisting a fitted pipeline
A saved model is more than its weights. Persist the fitted pipeline together with the metadata that makes it understandable and safe to load:
| Metadata | Example |
|---|---|
| Identity | Model name, version, creation time (UTC) |
| Inputs | Input schema, feature list in order, target definition |
| Training data | Dataset identifier, row count, date range, content hash |
| Configuration | Hyperparameters, seeds, split strategy, threshold and decision policy |
| Environment | PeaLang version, host package version, dependency versions |
| Evaluation | Cross-validation and test metrics, calibration summary, segment results |
| Integrity | Hash of the serialized artifact |
Load only trusted artifacts. Some general-purpose serialization formats can execute code while loading, so a tampered model file can be an attack vector. Prefer the serialization format provided by the ML layer, verify the artifact hash before loading, and load only from controlled locations. Chapter 20 adds integrity-checked bundles, registries, signing, and encryption on top of these basics.
Illustrative listing.
from pealang.ml import save_pipeline, load_pipeline
meta = {"name": "churn", "version": "1.0.0", "seed": 42,
"threshold": 0.09, "train_rows": X_train.height,
"data_hash": data_hash, "metrics": test_metrics}
path = save_pipeline(churn_pipe, "models/churn-1.0.0", metadata=meta,
schema=INPUT_SCHEMA)
loaded = load_pipeline("models/churn-1.0.0", expected_hash=artifact_hash)
assert loaded.predict_proba(X_test) == churn_pipe.predict_proba(X_test)
6.5 Reproducibility
A model is reproducible when someone else, later, can rebuild it from recorded inputs and obtain the same artifact and the same predictions. That requires controlling every source of variation:
- Code: a version-control commit for the training code.
- Data: an immutable snapshot or a content hash of the exact training data, with the extraction query.
- Randomness: seeds for splitting, shuffling, initialization, resampling, and search.
- Environment: the PeaLang version (pea --version), host package version, and a lock file of dependencies (Chapter 11).
- Ordering: sort input rows and columns deterministically; unordered inputs can change floating-point sums and iterative solvers.
Treat exact equality as the goal and a documented tolerance as the fallback. Some numerical libraries produce tiny differences across hardware or thread counts; if so, record the tolerance and test against it.
6.6 Testing the pipeline
Apply the testing discipline of Chapter 10 to the model artifact:
- Golden predictions: store predictions for a small fixed input set and assert that the reloaded pipeline reproduces them.
- Schema tests: missing column, wrong type, out-of-range value, and unseen category each produce the documented behaviour.
- Invariance tests: changing an irrelevant field (such as customer ID) does not change the prediction.
- Directional tests: where the domain is clear, a change in a feature moves the prediction in the expected direction (more support tickets should not lower churn risk without explanation).
- Rebuild test: retraining from recorded inputs reproduces the artifact hash or the golden predictions within tolerance.
Common mistakes
- Saving only the model, not the preprocessing: production then preprocesses differently.
- Passing through unknown columns: new upstream fields silently change the model.
- No schema check at prediction time: malformed inputs produce confident nonsense.
- Loading untrusted serialized files: verify hashes and load only from controlled locations.
- Missing seeds or data hashes: the model cannot be rebuilt or audited.
- No golden-prediction test: silent behaviour changes go unnoticed after upgrades.
Guided practice
- Convert the step-by-step preprocessing of Lesson 1 into a single pipeline and confirm identical outputs.
- Feed the pipeline a batch with a missing column, a negative age, and an unseen region; record what happens.
- Save, reload, and compare predictions; then change one dependency version in a scratch environment and repeat.
Hands-on lab: A reproducible model artifact
- Build the churn pipeline with a column transformer, schema, logistic model, and Platt calibration.
- Train with recorded seeds on a hashed data snapshot; evaluate with cross-validation and once on the test set.
- Save the pipeline with full metadata and an artifact hash.
- Write tests for golden predictions, schema violations, invariance, and one directional expectation.
- Delete the artifact, rebuild it from the recorded inputs, and confirm the golden predictions match.
Review questions
- How do pipelines prevent leakage during cross-validation?
- Why should unknown columns be dropped rather than passed through?
- What should an online service do when input fails schema validation?
- Which metadata must be saved with a model, and why?
- Why is loading an untrusted serialized model dangerous?
- List five sources of variation that reproducibility must control.
- What does a golden-prediction test protect against?
Applied challenge
A model trained six months ago is producing different predictions after a platform upgrade, and nobody can say why. Write the reproducibility runbook that would have prevented this: what is recorded at training time, where it is stored, how a rebuild is run, and which tests must pass before an upgraded environment may serve the model.
Lesson summary
A pipeline turns preprocessing, model, calibration, and decision policy into one artifact with one fit and one predict. Enforce an explicit input schema at both ends, drop unknown columns, persist the fitted pipeline with full metadata and an integrity hash, load only trusted artifacts, and record code, data, seeds, and environment so the model can be rebuilt and tested exactly.
Lesson status: Ready for review.