Leakage-Free Data Cleaning and ML Pipeline Design
Hard · Machine Learning · Data Scientist · Online Assessment
Prompt
Architect an end-to-end data-cleaning and supervised machine-learning workflow that fits on historical records and executes identically on held-out evaluation splits and live production traffic. Detail what each pipeline stage owns and how every channel of data leakage is prevented.
Because the exact table schema, prediction target, missingness mechanisms, and estimator family are left open, state concrete illustrative assumptions up front and anchor every cleaning decision in an explicit data contract. Never blindly discard all records containing missing values, and never estimate summary statistics or encoders across the combined dataset prior to splitting.
Clarify the following design dimensions in your answer: - What represents a single unit of observation, and whether records are mutually independent, clustered by entity, or ordered in time. - How columns partition into usable predictors, record/entity keys, ground-truth targets, and post-outcome fields not yet observable at scoring time. - How null entries, out-of-contract or malformed payloads, duplicate snapshots, and previously unseen categorical tokens are handled. - Which transformation parameters must be estimated strictly on the training split and frozen for validation, test, and live serving.
Scope & Expectations
- Establish an explicit column-by-column contract covering feature availability timestamps, valid ranges, deduplication rules, and label maturation delays before touching model code.
- Enforce a clean boundary between stateless row-level normalization and fitted cross-row transformations (
fiton training data only; frozentransformeverywhere else). - Design a validation split (chronological, grouped, and/or purged for label lag) that faithfully mirrors live scoring conditions.
- Distinguish expected missingness or novel categories from broken upstream schemas, package preprocessing state together with the trained estimator to prevent training-serving skew, and outline concrete leakage audits.
Step-by-step walkthrough
Start with an explicit data contract
Note: the prompt leaves the dataset schema, target, and model open. To make every rule concrete and testable, we use one illustrative task throughout: predicting at checkout whether an online order will be returned within 30 days. The exact same architecture applies to any tabular ML problem once you swap in its column contract.
Before writing a single line of cleaning code, we want to prevent data leakage — a bug where information from outside the training set (such as test rows or events that happen after prediction time) sneaks into model training, producing great offline scores and broken live predictions. Preventing leakage starts with a data contract (a table recording what each column represents, when it becomes known, what values are valid, and how missing values behave):
+---------------+-----------------------+----------------------------------------------------------+ | Column | Role | Contract rule | +---------------+-----------------------+----------------------------------------------------------+ | order_id | unique row identifier | deduplication key only; never fed to the model | | customer_id | entity / group key | group split & past-history key; never a raw feature | | order_time | prediction timestamp | chronological split key; derive calendar features only | | updated_at | ingestion timestamp | resolves duplicate rows; never a feature | | price | numeric feature | >= 0, sometimes missing -> impute + add missingness flag | | discount_pct | numeric feature | valid in [0, 100]; outside [0, 100] -> treat as missing | | category | categorical feature | new categories appear -> train vocabulary + unknown slot | | refund_amount | post-outcome field | written AFTER a return happens -> DROP (future leakage!) | | returned | binary target (0 / 1) | matures 30 days after order_time; exclude immature rows | +---------------+-----------------------+----------------------------------------------------------+Every open design question in the prompt is resolved directly by this contract: - Unit of observation and dependencies: One checkout order per record, ordered chronologically (
order_time) and clustered by shopper (customer_id), so records are not independent. - Post-outcome columns excluded at scoring:refund_amount(along with any post-checkout status). Offline,refund_amount > 0predicts returns with nearly 100% accuracy; at live checkout, that value has not been generated yet. - Preserving rows with missing inputs: Suppose 8% of orders lack aprice(for example, gift-bundle checkouts) and get returned twice as often. When missingness carries signal — often called missing not at random (MNAR) — discarding incomplete records biases the training sample and leaves production unable to score that 8% of live traffic. Only records lacking a valid, matured label are left out of training and evaluation.Map the pipeline and separate stateless vs fitted stages
For every transformation, ask one question: does this step's output for row
idepend on numbers learned from other rows? That divides the pipeline into three clean kinds of stages:Raw dataset | v [1. Contract check & Stateless row cleaning] (drop refund_amount, NaN/150% -> None; learns nothing) | v [2. Deduplicate by order_id] (before split so copies cannot land in both train & test) | v [3. Time / Group Split + 30-day label gap] -----> Held-out Val / Test (and future Live rows) | | v (Train rows ONLY) | [4. FIT Preprocessor (medians, means, stds, vocab) & FIT Model] | | | +-----------------> Frozen State + Trained Model ----------------+ v [5. TRANSFORM & PREDICT only]- Stateless row-level cleaning uses only the single row and fixed rules from the contract: dropping
refund_amount, normalizingNaNtoNone, and turning an impossiblediscount_pctlike150intoNone(so an explicit missingness flag lets the model learn whether corrupted discounts carry signal, rather than pretending150meant100). - Deduplication runs before splitting so two ingested copies of the same
order_idcannot end up on opposite sides of a split (which would let the model memorize training rows that reappear in test). Watch out for one subtle trap: only deduplicate to the latestupdated_atif re-ingestions represent copies of the at-checkout state; ifupdated_atrows include post-checkout edits, keep the latest snapshot withupdated_at <= order_timeinstead! - Fitted stages (imputation medians, standardization means/standard deviations, category vocabularies, outlier caps, feature selection, and the model itself) learn parameters on training rows only during
fit, and freeze those exact parameters fortransform.
import math def clean_row(raw): """Apply stateless contract rules to a single row (learns nothing across rows).""" row = dict(raw) # Drop post-checkout columns immediately so no downstream step can touch them row.pop("refund_amount", None) for column in ("price", "discount_pct"): value = row.get(column) # Normalize float('nan') from CSV/DataFrame loaders into Python None if isinstance(value, float) and math.isnan(value): row[column] = None discount = row.get("discount_pct") if discount is not None and not (0 <= discount <= 100): # Out-of-contract values become missing rather than silently clipped row["discount_pct"] = None return row def deduplicate(rows): """Keep one snapshot per order_id (assuming updated_at reflects pre-checkout ingestion).""" latest_by_id = {} for row in rows: order_id = row["order_id"] prev = latest_by_id.get(order_id) if prev is None or row["updated_at"] > prev["updated_at"]: latest_by_id[order_id] = row return list(latest_by_id.values())- Stateless row-level cleaning uses only the single row and fixed rules from the contract: dropping
Split the dataset to match live deployment
Your validation split must rehearse how the model will actually run in production — and it must happen before any
fitstep touches the data:- Chronological order (never random shuffle): In production, a model trained up to September 1 scores orders placed on September 1 and later. Randomly shuffling orders lets a model learn holiday return spikes from November and get graded on October orders.
- Purge gap for label delay: Because a return takes up to 30 days to happen, on September 1 you only know final labels for orders placed on or before August 2 (
Sept 1 - 30 days). Orders from August 3 to August 31 cannot go into training (an unreturned August 25 order might still come back on September 10!) and precede the September 1 deployment cutoff, so they sit in a purge gap:
2025 timeline (1 order per day, 30-day label maturation window, cutoff = Sept 1): Jan 1 .................. Aug 2 | Aug 3 ..... Aug 31 | Sept 1 ........ Oct 31 [ 214 Training orders ] | [ 29 Purged gap ] | [ 61 Eval orders ] Labels fully known by Sept 1 Labels NOT mature Scored like live prod- Customer grouping & point-in-time aggregates: If your goal is predicting for brand-new shoppers, also group by
customer_idso the same shopper does not appear in both train and evaluation. When computing historical customer features likepast_return_rate, count only prior orders placed at least 30 days before the currentorder_timeso their return outcomes were already known at checkout.
from datetime import datetime, timedelta LABEL_DELAY = timedelta(days=30) def time_split(rows, cutoff, end): """Train on orders whose 30-day label matured by `cutoff`; evaluate on [cutoff, end).""" train_rows = [] eval_rows = [] latest_mature_order = cutoff - LABEL_DELAY for row in rows: if row["order_time"] <= latest_mature_order: train_rows.append(row) elif cutoff <= row["order_time"] < end: eval_rows.append(row) return train_rows, eval_rowsFit every preprocessing statistic on training rows only
Every fitted transformation computes its summary numbers strictly from
train_rowsand stores them in a plain dictionary (state). Notice two subtle details below: - Forprice, we compute the median on observed training prices first, impute missing training prices with that median, and computemeanandstdon the imputed training column so standardization matches whattransform_rowwill produce. - Forcategory, any category appearing fewer thanmin_counttimes in training is folded into"__unknown__". That gives the model real training examples in the"__unknown__"slot before a brand-new category ever appears in production!NUMERIC = ["price", "discount_pct"] CATEGORICAL = ["category"] UNKNOWN = "__unknown__" def median(values): ordered = sorted(values) mid = len(ordered) // 2 if len(ordered) % 2 == 1: return float(ordered[mid]) return (ordered[mid - 1] + ordered[mid]) / 2.0 def fit_numeric(train_rows, column): """Learn median fill value, mean, and std for one numeric column from train_rows only.""" observed = [row[column] for row in train_rows if row.get(column) is not None] if not observed: raise ValueError(f"column {column!r} has no observed values in training") fill_val = median(observed) filled = [fill_val if row.get(column) is None else row[column] for row in train_rows] mean_val = sum(filled) / len(filled) variance = sum((v - mean_val) ** 2 for v in filled) / len(filled) # Guard against division by zero when a training column is constant std_val = math.sqrt(variance) if variance > 0 else 1.0 return {"fill": fill_val, "mean": mean_val, "std": std_val} def fit_vocabulary(train_rows, column, min_count=2): """Keep categories seen >= min_count times in training; fold rarer ones into UNKNOWN.""" counts = {} for row in train_rows: value = row.get(column) if value is not None: counts[value] = counts.get(value, 0) + 1 kept = sorted(cat for cat, count in counts.items() if count >= min_count) return kept + [UNKNOWN] def fit_preprocessor(train_rows): """Fit all numeric and categorical state strictly on training rows.""" state = {"numeric": {}, "vocabulary": {}} for column in NUMERIC: state["numeric"][column] = fit_numeric(train_rows, column) for column in CATEGORICAL: state["vocabulary"][column] = fit_vocabulary(train_rows, column) return stateWalk through a concrete 5-row training split to see the exact numbers — and compare what happens if two future evaluation orders (
price = 100andprice = 120) accidentally leak intofit:5 Training rows: price: [10, 20, 30, None, 40] -> observed = [10, 20, 30, 40] -> fill = median = 25.0 -> filled = [10, 20, 30, 25, 40] -> mean = 25.0, std = 10.0 discount_pct: [0, 10, 150 -> None, 20, 10] -> observed = [0, 10, 10, 20] -> fill = median = 10.0 -> filled = [0, 10, 10, 20, 10] -> mean = 10.0, std = sqrt(40) = 6.32 category: ["books", "books", "toys", "toys", "shoes"] -> "shoes" seen once (< 2) -> vocabulary = ["books", "toys", "__unknown__"] Leaky fit (accidentally including 2 future test rows with price 100 and 120): observed = [10, 20, 30, 40, 100, 120] -> fill jumps from 25.0 to 35.0! filled = [10, 20, 30, 35, 40, 100, 120] -> mean jumps to 50.7, std jumps to 39.0!Even on simple scaling, two test rows distort every single training feature. On label-aware steps such as target encoding (replacing a category with its historical return rate), fitting on all rows leaks the test answers directly into the features! (In fact, target encoding must use out-of-fold statistics even inside the training split so a training row's own label never enters its own feature.)
Transform held-out and live rows with frozen state
At validation, test, and live serving time,
transform_rownever computes a mean, median, or category list from the incoming batch — a live API call often has batch size1! It simply readsstate, emits both the standardized value and a0.0 / 1.0missingness indicator, and maps any unseen category (like"garden") intoUNKNOWN:def transform_row(row, state): """Build the numeric feature vector for one cleaned row using only frozen training state.""" features = [] for column in NUMERIC: stats = state["numeric"][column] raw_val = row.get(column) is_missing = raw_val is None filled_val = stats["fill"] if is_missing else raw_val # Standardized value followed by an explicit 1/0 missingness flag features.append((filled_val - stats["mean"]) / stats["std"]) features.append(1.0 if is_missing else 0.0) for column in CATEGORICAL: vocabulary = state["vocabulary"][column] cat_val = row.get(column) if cat_val not in vocabulary: cat_val = UNKNOWN # One-hot encode against the fixed training vocabulary (including UNKNOWN) for slot in vocabulary: features.append(1.0 if cat_val == slot else 0.0) return featuresTracing two new inference orders against the 5-row
statefrom above:Feature slots: [price_z, price_miss, disc_z, disc_miss, cat_books, cat_toys, cat_unknown] Inference row 1: {price: None, discount_pct: 5, category: "garden"} price: imputed 25.0 -> (25.0 - 25.0) / 10.0 = 0.00, missing flag = 1.0 discount: (5.0 - 10.0) / 6.32 = -0.79, missing flag = 0.0 category: "garden" not in vocab -> "__unknown__" -> [0.0, 0.0, 1.0] -> [0.0, 1.0, -0.79, 0.0, 0.0, 0.0, 1.0] Inference row 2: {price: 45, discount_pct: None, category: "toys"} -> [2.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0]Crucially, separate expected missing values (
price = None) from schema violations (price = "12"as a string,price = Truewhere Python'sboolsubclassesint, or a missing"category"key). Silently imputing a broken upstream payload hides bugs, so reject contract violations explicitly:REQUIRED_TYPES = { "order_id": str, "order_time": datetime, "price": (int, float, type(None)), "discount_pct": (int, float, type(None)), "category": (str, type(None)), } def check_contract(row): """Fail fast on missing keys or wrong types (including bool masquerading as int).""" for column, allowed_types in REQUIRED_TYPES.items(): if column not in row: raise ValueError(f"missing required column {column!r}") value = row[column] # In Python isinstance(True, int) is True, so reject booleans for numeric columns if isinstance(value, bool) or not isinstance(value, allowed_types): raise ValueError(f"{column!r} has invalid type {type(value).__name__}")Package cleaning, fitted state, and model into one artifact
If offline notebooks clean data one way and the production service reimplements cleaning another way, the model suffers training-serving skew (mismatched feature values between training and live inference). Wrapping contract validation, stateless row cleaning,
state, andmodelinside a single Pipeline object — saved and versioned as one artifact — guarantees identical execution everywhere:class ReturnModelPipeline: """Single versioned unit bundling schema checks, stateless cleaning, fitted state, and model.""" def __init__(self, model): self.model = model # estimator exposing fit(X, y) and predict_proba(X) self.state = None def fit(self, train_rows, labels): cleaned = [] for row in train_rows: check_contract(row) cleaned.append(clean_row(row)) self.state = fit_preprocessor(cleaned) X_train = [transform_row(row, self.state) for row in cleaned] self.model.fit(X_train, labels) return self def predict_proba(self, rows): if self.state is None: raise RuntimeError("call fit() before predict_proba()") X_eval = [] for row in rows: check_contract(row) X_eval.append(transform_row(clean_row(row), self.state)) return self.model.predict_proba(X_eval)During model selection, place the entire
ReturnModelPipeline.fit(...)inside every walk-forward validation fold so hyperparameters are tuned without leaking validation statistics, evaluate once on a untouched later test window, and deploy the artifact calling onlypredict_proba.Audit and test systematically for hidden leakage
Because data leakage makes offline metrics look better rather than crashing, write automated checks specifically designed to catch it:
- Frozen-state unit test: Fit
pipelineontrain_rows, deep-copypipeline.state, callpipeline.predict_proba(test_rows), and assertpipeline.stateis byte-for-byte unchanged — and also assert that fitting ontrain_rowsvstrain_rows + test_rowsproduces different states (proving the test is non-trivial). - Point-in-time timestamp audit: Require every raw column and engineered feature to declare
available_at, and assertavailable_at <= order_timeon every row (refund_amountfails immediately). - Zero-overlap assertions: Assert
set(train_order_ids).isdisjoint(eval_order_ids)(and disjointcustomer_idsets when evaluating generalization to new customers), plusmax(train_order_time) <= min(eval_order_time) - LABEL_DELAY. - Single-feature sanity check: Measure AUC (Area Under the ROC Curve — the probability from
0.0to1.0that a randomly chosen returned order scores higher than a randomly chosen kept order, where0.5is random guessing). Any single feature with AUC near0.98+is treated as a leakage suspect until proven clean. - Permuted-label (shuffled-target) test: Randomly shuffle
labelson the training split, refit the entire pipeline from scratch, and score validation. Validation AUC must collapse to ~0.50; if it stays above0.55, label information leaked across the split (for example, via a target encoder or feature selector fitted before splitting).
- Frozen-state unit test: Fit
Intuition & how it works
Think of training and evaluating a machine-learning pipeline like studying for an upcoming closed-book exam. Your training split is last semester's practice packet; the test split (and future live traffic) is next week's sealed exam. Data leakage happens whenever hints from the sealed exam — or facts written after the exam is graded — sneak into your study notes: your practice score shoots up to 99%, and then you freeze on exam day when those hints are gone.
Three naive habits cause almost every real-world pipeline failure:
1. Calling imputer.fit(full_df) or building a one-hot category list on the entire dataset before splitting, which lets future test averages and categories shape training features.
2. Using a random train/test split on time-ordered events or leaving post-outcome columns (like refund_amount when predicting checkout returns) in the table.
3. Calling df.dropna() to throw away every incomplete row, which biases the model whenever missingness is informative and leaves production unable to score incomplete live requests.
Instead, start with a column-by-column data contract, apply stateless row rules (refund_amount dropped, invalid 150% discount turned into None), deduplicate, split chronologically with a purge gap for label maturation, and enforce a strict fit vs transform wall. On 5 training orders with price = [10, 20, 30, None, 40], fit learns median = 25.0, mean = 25.0, std = 10.0 (whereas leaking two future test orders priced 100 and 120 would warp those numbers to fill = 35.0, mean = 50.7, std = 39.0!). Later, when a live order arrives with {price: None, discount_pct: 5, category: "garden"}, transform plugs in the frozen 25.0 alongside a 1.0 missingness flag and routes the unseen "garden" into an "__unknown__" slot whose weight was already trained on rare training categories.
Key points
- Write a data contract first: Document every column's role (identifier, group key, timestamp, feature, post-outcome leak, or target), valid range, missingness behavior, and exact availability time. Drop post-prediction columns (
refund_amount) unconditionally. - Separate stateless rules from fitted statistics: Stateless row checks (
NaNnormalization, turning out-of-rangediscount_pct = 150intoNone) learn nothing across rows, and deduplication runs before splitting so duplicate copies cannot straddle train and test. Every stage that computes statistics across rows (imputers, scalers, category vocabularies, outlier caps, feature selectors, target encoders, and the model) fits strictly on the training split. - Split the way production scores: Use chronological splits for time-ordered data, insert a purge gap equal to the label delay (
cutoff - 30 days) so training never uses immature labels, and keep entity groups (customer_id) together when evaluating generalization to unseen entities. - Impute + flag instead of dropping incomplete rows: Replace missing numeric values with a training statistic (such as the training median) plus a binary
is_missingindicator column so the model can learn when missingness itself predicts the target; exclude only rows without a valid, mature label. - Reserve a trained
__unknown__slot for rare and unseen categories: Folding rare training categories (count < min_count) into"__unknown__"ensures the model learns a realistic weight for that slot during training rather than encountering an all-zeros or unlearned feature column in production. - Distinguish missing values from broken contracts:
price = Noneis expected data handled by imputation;price = "12"(wrong type),price = True(boolsubclassingint), or a missing column key is an upstream pipeline bug that should raise an error or route the record to a quarantine queue. - Ship one bundled artifact and test for leakage: Serialize schema validation, stateless cleaning, frozen preprocessor
state, and the trained estimator together to prevent training-serving skew (divergent feature logic between training and live inference), and run automated timestamp, ID-overlap, and shuffled-label checks.
Common mistakes
- Fitting scalers, imputers, outlier percentiles, or vocabularies before splitting. Even unsupervised statistics like medians, means, and min/max bounds leak future distribution shifts into training features.
- Doing feature selection, target encoding, or oversampling (SMOTE) outside cross-validation. Selecting "top 20 features correlated with
y" once on the whole dataset before K-fold validation leaks held-out labels into every fold and produces wildly optimistic validation scores. - Treating recent unlabeled rows as negative examples (
returned = 0). An order placed 3 days ago has simply not had time to be returned yet; including it teaches the model that recent dates never return! - Deduplicating to the newest
updated_atwhen records mutate after prediction time. If a warehouse update overwrites an order record after a return occurs, picking the latest row smuggles post-outcome edits into training; always snapshot as of prediction time. - Feeding raw identifiers (
order_id) to the model. Sequential IDs act as a hidden proxy for timestamp, letting tree models memorize bursts in time instead of learning generalizable patterns. - Recomputing batch mean/std at inference time. Scoring a single live HTTP request has batch size
1(std = 0), and recomputing statistics on daily batch jobs makes the same order receive different scores depending on which other orders happened that day. - Creating an
__unknown__category slot that zero training rows ever visit. If every training category appears>= min_counttimes, the__unknown__column is0.0on every training row, leaving its learned weight stuck at0(or uninitialized) when a new category arrives in production.
Follow-up questions
- How should you restructure validation splitting when predicting across time-ordered events? Replace random K-fold cross-validation with walk-forward (rolling or expanding window) validation, where every fold trains strictly on past timestamps, leaves a purge gap equal to the label horizon so every training label has already matured by the cutoff date, and evaluates on the immediately following time window (for example, Fold 1 trains through June 2 and validates on July; Fold 2 trains through July 2 and validates on August). Every fitted stage (
fit_preprocessor+model.fit) is refitted from scratch inside each fold, and any rolling historical feature (such as a customer's 90-day return rate) may look back across the cutoff only at prior orders whose 30-day return outcomes were already finalized as of the current order's checkout timestamp. When evaluating financial or overlapping-horizon series with non-chronological cross-validation, removing training samples whose label intervals overlap the test window is called purging, and dropping a buffer right after the test window to prevent serial-correlation leakage is called an embargo. - How should the serving pipeline handle a categorical value at prediction time that never appeared in the training data? The pipeline should score the row deterministically without crashing by mapping the unseen string into the reserved
"__unknown__"vocabulary slot (for one-hot or embedding models) or falling back to the smoothed training-set global mean (for target-encoded features). That works cleanly provided rare training categories (count < min_count) were routed to"__unknown__"duringfitso the model actually learned a sensible weight for unfamiliar categories (verify at fit time that"__unknown__"received non-zero training support, or smooth toward the overall intercept). In parallel, log the rate of"__unknown__"hits per column in production monitoring: a trickle of new product tags is normal, whereas a sudden jump from 1% to 40% signals an upstream category rename (like"apparel"->"clothing") or major catalog launch that warrants an alert and retraining. Finally, keep unseen category values (expected, routed to"__unknown__") strictly separate from unseen column schemas or invalid types (contract violations, rejected immediately).
Follow-up questions
- How should you restructure validation splitting when predicting across time-ordered events?
- How should the serving pipeline handle a categorical value at prediction time that never appeared in the training data?
Similar questions
- From-Scratch GLM Training and Prediction
- Low-Latency Tree Ensemble Inference
- Select Score Cutoff for Target Precision
- Payment Fraud Detection Under Class Imbalance and Drift
- Diagnosing and Fixing Overfitting in Supervised Learning
- Correlation Bounds, Equicorrelated Variables, and Box-Muller Sampling