Auditing, Tuning, and Serving a Forecasting Pipeline

Medium · Machine Learning · Machine Learning Engineer · Technical Screen

Prompt

You inherit a machine learning codebase that loads chronological observations from CSV files, constructs features, and fits a predictive model. No specific domain table, target column, or confirmed defect is handed to you up front—treat potential look-ahead leakage and implementation bugs as open hypotheses to test systematically rather than established facts.

Walk through how you would:

  1. Clarify the prediction clock, forecast horizon, data arrival delays, single-series versus multi-entity structure, and serving requirements before inspecting feature logic.
  2. Audit the CSV ingestion, target alignment, feature transformations, and preprocessing boundaries for software bugs or future-information leakage, and verify any suspected flaw on a small hand-traceable example.
  3. Tune model hyperparameters under a chronological validation protocol that prevents evaluation-period information from leaking into feature engineering or model selection.
  4. Extend the training script into a production-ready inference pipeline capable of scoring new arrivals consistently with training-time logic.

Scope & Expectations

  • Problem framing & timeline: Pin down what outcome is predicted, when each prediction is triggered, which fields have actually arrived by that timestamp, and how entity boundaries behave across splits.
  • Data & feature audit: Check raw CSV parsing, timestamps, duplicates, missingness, entity-grouped lags/windows, point-in-time joins, preprocessor fit boundaries, and reproducible leak tests.
  • Chronological model selection: Structure time-ordered or walk-forward folds matched to the forecast horizon, isolate learned transforms inside training folds, benchmark against a simple baseline, and preserve a single-use holdout block.
  • Inference & parity: Define the versioned model/preprocessor bundle, schema and historical lookback contract, missing-input handling, output fields, and training-versus-serving parity checks.

Step-by-step walkthrough

  1. Define the prediction contract before reading feature code

    Feature leakage (also called data leakage) happens when a model trains or validates on information that would not actually exist at the exact moment a real-world prediction must be made. Because no concrete schema or confirmed bug is given ahead of time, approach every suspected leak as a falsifiable hypothesis—and start by locking down the timeline.

    Before inspecting a single line of feature code, clarify four questions: 1. Prediction time (t) and horizon (h): What outcome are we predicting, at what exact timestamp is the prediction triggered, and how far ahead does the target reach? 2. Availability delays: When does each input table actually arrive in storage, as opposed to the calendar period it describes? 3. Entity structure: Is this one time series or panel data (a table tracking multiple entities—such as stores, sensors, or financial assets—across time)? Will the model only score known entities or brand-new ones too? 4. Serving mode: Does inference run as a scheduled batch or low-latency online call, and how many days of history are kept online?

    To make every check concrete, assume the following explicit contract (if the interviewer specifies a 5-day horizon or intraday bars, only the numbers below change):

    Timeline for one entity on day d:
    
      ... ----+--------------------+--------------------+--------------------> time
            day d-2              day d                day d+1
                                 ^                    ^
                                 |                    |
                      prediction time t        target y(d) = value(d+1)
                      (end of day d)           lands at end of day d+1
    
    What is legally usable at prediction time t (end of day d)?
      - value: lands at the end of the same day -> days <= d are known.
      - ext:   external report with a 2-day publishing delay -> available_at = date + 2 days,
               so at the end of day d only reports for periods <= d - 2 are known!
    

    Two rules govern the entire audit: - Event time is not availability time. A macroeconomic or accounting figure describing 2024-03-05 that is published on 2024-03-07 cannot be used on 2024-03-05. Every source table needs an explicit available_at timestamp (or a conservative documented lag to compute one). - A feature leaks if and only if it touches any record with available_at > t (including the target itself).

  2. Audit raw CSV ingestion: schema, sorting, duplicates, and gaps

    Many apparent "leaks" or wild validation swings are actually ordinary CSV-reading bugs. Audit the raw table structure before examining feature formulas:

    • Parsed types and a single timezone: Parse timestamps as real datetimes in one canonical timezone (such as UTC), never plain strings ("10/1/2024" sorts before "2/1/2024" alphabetically). Check whether a date stamped 00:00:00 actually summarizes activity up to 23:59:59 of that day.
    • Primary key uniqueness: (entity, date) should identify at most one row unless the file stores historical revisions. Duplicate keys often come from concatenating CSV exports where a later export overwrote numbers with restated values.
    • Explicit chronological sorting: Always sort by (entity, date) before running positional window operations. Calling .shift(1) or .rolling(3) on an unsorted DataFrame silently averages unrelated rows.
    • Irregular time gaps: Weekends, holidays, sensor outages, or paused stores mean .shift(1) is "the previous recorded row," which after a 4-day outage is four days ago, not yesterday.
    • Missingness over time and survivorship bias: Survivorship bias is the distortion caused by keeping only entities that survived to the end of the dataset while dropping failed, closed, or delisted ones. Also check whether any column is 100% missing before a certain month and suddenly populated afterward (a classic sign of a backfilled column).
    import pandas as pd
    
    
    def audit_raw(df: pd.DataFrame) -> dict:
        """Run structural sanity checks on a raw (entity, date) panel CSV."""
        checked = df.copy()
        # Parse dates into a single timezone before sorting or differencing.
        checked["date"] = pd.to_datetime(checked["date"], utc=True)
        checked = checked.sort_values(["entity", "date"]).reset_index(drop=True)
    
        # Measure spacing between consecutive rows within each entity separately.
        time_gaps = checked.groupby("entity")["date"].diff()
        months = checked["date"].dt.tz_localize(None).dt.to_period("M")
    
        return {
            "row_count": len(checked),
            "entity_count": int(checked["entity"].nunique()),
            "duplicate_entity_dates": int(checked.duplicated(subset=["entity", "date"]).sum()),
            "top_gap_sizes": time_gaps.value_counts().head(5).to_dict(),
            # Look for columns whose missing rate drops from 1.0 to 0.0 mid-history.
            "monthly_missing_rate": checked.isna().groupby(months).mean(),
        }
    
  3. Audit target and feature construction for look-ahead leakage

    Next, trace every column transformation and ask: "Which input rows feed this calculation, and was every single one of them available at t?" Watch for two window types in particular: a trailing window averages only the current row and earlier rows (t - k + 1 .. t), whereas a centered window averages rows on both sides (t - 1, t, t + 1), reaching into the future.

    Buggy / leaky pattern                       Why it breaks or leaks                  Clean fix
    ------------------------------------------  --------------------------------------  ------------------------------------------
    y = df["value"].shift(-1) without groupby   Entity A's last date gets Entity B's    df.groupby("entity")["value"].shift(-1)
                                                first date as its target!
    rolling(k, center=True)                     Window includes future dates > t        Trailing window only (center=False)
    Rolling over the target column y            Feature directly averages future y      Compute features from raw inputs first;
                                                                                        attach label y as the final step
    Equi-join on event date for delayed table   Uses day d's ext value 2 days before    As-of join matching available_at <= t
                                                ext is actually published
    bfill() / linear interpolation              Fills a gap using values after the gap  Forward-fill (ffill) within entity only,
                                                                                        plus a "days since last observation" flag
    Scaler / imputer / PCA / quantile clip      Mean, std, or quantiles include future  Fit transformers inside each training fold
    fit on the entire CSV before splitting      validation and test periods             only (e.g., inside a Pipeline)
    Target encoding or feature selection        Validation labels leak into training    Compute out-of-fold inside training only
    fit on all rows                             features or chosen column subset
    

    To join delayed external sources safely, use an as-of join—a time-aware join that pairs each left row at timestamp t with the single most recent right row for the same entity whose available_at <= t:

    import pandas as pd
    
    
    def join_as_of(predictions: pd.DataFrame, external_source: pd.DataFrame) -> pd.DataFrame:
        """Attach the latest external record already published by prediction_time."""
        left = predictions.sort_values("prediction_time")
        right = external_source.sort_values("available_at")
        return pd.merge_asof(
            left,
            right,
            left_on="prediction_time",
            right_on="available_at",
            by="entity",
            # "backward" guarantees we only match available_at <= prediction_time.
            direction="backward",
        )
    
  4. Prove or disprove a suspected leak with a 6-row trace and truncation test

    Never stop at code inspection—prove a suspected bug by reconstructing one prediction row by hand, then automate the check. Suppose the pipeline defines mean_3 = value.rolling(3, center=True).mean() while predicting tomorrow's value y(d) = value(d + 1) at the end of day d:

    day   value   target y = value(day+1)   centered mean_3 (BUGGY)        trailing mean_3 (VALID)
    ---   -----   -----------------------   ----------------------------   ----------------------------
     1      10              12              None                           None
     2      12              11              (10 + 12 + 11) / 3 = 11.00     None
     3      11              15              (12 + 11 + 15) / 3 = 12.67     (10 + 12 + 11) / 3 = 11.00
     4      15              14              (11 + 15 + 14) / 3 = 13.33     (12 + 11 + 15) / 3 = 12.67
     5      14              18              (15 + 14 + 18) / 3 = 15.67     (11 + 15 + 14) / 3 = 13.33
     6      18             None             None                           (15 + 14 + 18) / 3 = 15.67
    

    Look at day 3 (predicted at the end of day 3): - Its target is day 4's value, 15. - The centered feature 12.67 averages days 2, 3, and 4 (15), baking one-third of tomorrow's answer straight into today's input! Notice that day 3's buggy centered mean (12.67) equals day 4's valid trailing mean.

    Turn this manual trace into an automated prefix-truncation test that works on any black-box feature function: compute features on the full dataset, then recompute them after deleting every record with available_at > t. Any feature that truly depends only on the past must stay bit-for-bit identical at t:

    def centered_mean_3(values: list) -> list:
        """Buggy feature: averages previous, current, and NEXT value."""
        result = []
        for i in range(len(values)):
            if i == 0 or i == len(values) - 1:
                result.append(None)
            else:
                result.append((values[i - 1] + values[i] + values[i + 1]) / 3.0)
        return result
    
    
    def trailing_mean_3(values: list) -> list:
        """Valid feature: averages current value and two preceding values."""
        result = []
        for i in range(len(values)):
            if i < 2:
                result.append(None)
            else:
                result.append((values[i - 2] + values[i - 1] + values[i]) / 3.0)
        return result
    
    
    def uses_future_information(feature_fn, values: list) -> bool:
        """Return True if truncating future rows changes any historical feature value."""
        full_features = feature_fn(values)
        for cutoff in range(len(values)):
            # Feed only observations up to and including index `cutoff`.
            past_only_features = feature_fn(values[: cutoff + 1])
            if past_only_features[cutoff] != full_features[cutoff]:
                return True
        return False
    
    
    sample_values = [10, 12, 11, 15, 14, 18]
    assert uses_future_information(centered_mean_3, sample_values) is True
    assert uses_future_information(trailing_mean_3, sample_values) is False
    

    A quick diagnostic companion check: lag a suspiciously dominant feature by one extra day. A genuine predictive signal usually loses a modest amount of accuracy when made one day staler; if validation performance instead collapses all the way down to a trivial baseline, the unlagged feature was almost certainly smuggling target information.

  5. Tune hyperparameters with purged walk-forward validation

    Random K-fold cross-validation shuffles days, letting a model train on Wednesday and Friday to "predict" Thursday. Instead, evaluate parameter changes with walk-forward validation—a chronological scheme where each fold trains on historical dates up to a cutoff and validates on the next contiguous block of dates.

    Two panel and horizon details are critical: 1. Split by date, not row index: All entities on date d must sit on the same side of the split so cross-sectional market or weather shocks on date d never appear in both train and validation. (If production must also score cold-start entities never seen during training, hold out a subset of entities in validation too.) 2. Purge overlapping label horizons: Purging removes training rows right before the validation start day v whose future target window overlaps the validation period. If row d predicts day d + h (made at the end of day d), its outcome lands at the end of day d + h. Keeping only training days with d + h <= v ensures every training label has already landed by the time the first validation prediction is made at the end of day v, with zero overlap into validation targets v + 1 .. v + h. (If the model is fitted before day v begins—at the end of day v - 1—tighten this to d + h <= v - 1, purging one more day.)

    def walk_forward_splits(total_labeled_days: int, first_val_day: int, val_size: int,
                            n_folds: int, horizon: int):
        """Yield 1-based (train_days, val_days) ranges with horizon purging."""
        for fold_idx in range(n_folds):
            val_start = first_val_day + fold_idx * val_size
            val_end = min(val_start + val_size - 1, total_labeled_days)
    
            # Keep training day d only if its target day (d + horizon) <= val_start.
            last_train_day = val_start - horizon
            train_days = range(1, last_train_day + 1)
            val_days = range(val_start, val_end + 1)
            yield train_days, val_days
    

    With 700 labeled days, horizon h = 5 days, and 60-day validation blocks (first_val_day = 401):

    Fold         Train days   Purged days (h - 1 = 4)   Validation / test days
    ----------   ----------   -----------------------   ---------------------------------------
    Fold 1        1 .. 396          397 .. 400           401 .. 460  (tune parameters)
    Fold 2        1 .. 456          457 .. 460           461 .. 520  (tune parameters)
    Fold 3        1 .. 516          517 .. 520           521 .. 580  (tune parameters)
    Final test    1 .. 576          577 .. 580           581 .. 700  (refit once, evaluate ONCE)
    

    Inside every fold: - Fit all learned preprocessors (imputers, scalers, category encoders, feature selectors) on train_days only, then transform val_days. - Compare every candidate parameter set against a persistence baseline—a zero-parameter benchmark that simply predicts y_hat(d) = value(d) (or last week's same weekday for seasonal series). For example, using MAE (Mean Absolute Error, the average of |y - y_hat|), if our tuned model scores fold MAEs of 1.8, 2.0, 1.9 (mean 1.90) while persistence scores 2.4, 2.5, 2.6 (mean 2.50), relative skill is 1 - 1.90 / 2.50 = 0.24 (a 24% error reduction). Across entities of very different scales, also report MASE (Mean Absolute Scaled Error, which divides each entity's MAE by that entity's in-sample naive-forecast MAE). - Lock hyperparameters using the mean and stability of validation folds 1..3, refit on 1..576, and score the untouched final test block 581..700 once.

  6. Package inference artifacts and share one feature builder

    Training-serving skew occurs when live inference computes different feature values than offline training would have produced for the exact same timestamp. Prevent skew by bundling five versioned artifacts together and sharing one feature-construction function across offline training and live inference:

    Inference bundle (saved together under one model_version):
      1. Estimator           fitted model weights / trees
      2. Preprocessing state training-only imputer medians, scaler means/stds, category maps + "OTHER"
      3. Feature schema      exact ordered column list, expected dtypes, valid value bounds
      4. Data contract       source schemas, per-source availability lag, horizon h,
                             required history lookback = max_window + max_lag (e.g. 20 + 5 = 25 days)
      5. Lineage metadata    git commit hash, training date range, snapshot ID, validation/test metrics
    

    Write build_features(history, as_of, lookback) so it enforces available_at <= as_of internally, deduplicates any revised records up to as_of, and uses the exact same minimum-history rules as training (for example, returning NaN when fewer than 3 observations exist, matching rolling(3, min_periods=3)):

    import math
    import pandas as pd
    
    
    def _trailing_mean_3(series: pd.Series) -> float:
        """Mean of the latest 3 values, or NaN if fewer than 3 observations exist."""
        if len(series) < 3:
            return math.nan
        return float(series.tail(3).mean())
    
    
    def build_features(history: pd.DataFrame, as_of: pd.Timestamp, lookback: int) -> pd.DataFrame:
        """Build one feature row per entity using only records available at `as_of`."""
        # Filter by availability time first so future records can never leak in.
        known = history[history["available_at"] <= as_of].sort_values(
            ["entity", "date", "available_at"]
        )
        # If a date was revised multiple times before `as_of`, keep the latest known revision.
        known = known.drop_duplicates(subset=["entity", "date"], keep="last")
    
        recent = known.groupby("entity").tail(lookback)
        grouped_val = recent.groupby("entity")["value"]
    
        features = pd.DataFrame({
            "last_value": grouped_val.last(),
            "mean_3": grouped_val.apply(_trailing_mean_3),
            "n_history": grouped_val.size(),
        })
        features["as_of"] = as_of
        return features
    

    Define explicit failure and missing-value behavior in the contract: - Missing required column or stale upstream table: Fail loudly and alert—never silently fill an entire broken feed with 0. - Individual missing cell: Impute with the saved training statistic (plus a missingness indicator column if the model was trained with one). - Cold-start entity (n_history < lookback): Populate n_history, let under-populated windows emit NaN for the saved imputer, or route rows below a minimum history threshold to a safe baseline forecast with a status flag. - Prediction output schema: Emit (entity, as_of, target_date, prediction, model_version, feature_hash, fallback_flag) so every live decision is auditable.

  7. Verify parity with historical replay and monitor live drift

    Before routing live traffic to the extended pipeline, prove training/inference parity in three stages: 1. Point-in-time replay test: Pick several historical dates (including a Monday or post-holiday gap), feed the inference runner raw[raw["available_at"] <= t], and assert that both the generated feature vector and the predicted score match the offline training/validation rows for (entity, t) within floating-point tolerance (1e-9). 2. Load-time schema gate: Verify column names, column order, and dtypes against the saved feature schema before calling model.predict. 3. Shadow deployment: Run daily inference live alongside the existing process without acting on predictions until live data delivery and latency are confirmed.

    Once live, monitor inputs immediately and accuracy as labels mature h days later: - Input health and feature drift: Track missing-value rates and the Population Stability Index (PSI)—a summary number measuring how much a feature's live bin proportions (a_i) have shifted away from its training bin proportions (e_i): PSI = sum_i (a_i - e_i) * ln(a_i / e_i). For a 2-bin example where training shares 0.50 / 0.50 shift to live shares 0.60 / 0.40, PSI = (0.60 - 0.50) * ln(1.2) + (0.40 - 0.50) * ln(0.8) = 0.0182 + 0.0223 = 0.041 (rules of thumb treat < 0.10 as stable, 0.10..0.25 as moderate shift, and > 0.25 as major drift). - Output sanity: Track prediction quantiles and mean per entity group to catch unit mismatches (such as cents vs. dollars) on day one. - Delayed realized error: Join predictions to actual outcomes h days later and compare live MAE against both the backtest expectation and the live persistence baseline.

Intuition & how it works

Think of training a time-series model like practicing for a daily weather forecast exam: when you stand at 6:00 PM on Tuesday predicting Wednesday's temperature, you are only allowed to open notebooks that had already arrived on your desk by 6:00 PM Tuesday. If someone accidentally slips Wednesday's newspaper—or an average computed across the whole month—onto your study desk, you will ace every practice quiz and then fail immediately on your first real forecast when Wednesday's newspaper does not exist yet.

Standard tabular ML habits break down on time series for three plain reasons. First, a random train/test split scatters future days into the training set, letting the model memorize tomorrow's conditions to "predict" yesterday. Second, innocent-looking operations like rolling(3, center=True), joining a delayed report on the date it describes rather than the date it was published, or fitting a StandardScaler on the entire CSV quietly smuggle future numbers into past rows. Third, rewriting feature logic from scratch for production almost guarantees training-serving skew—a mismatch between what offline training computed and what live inference computes for the exact same timestamp.

Walk through a tiny 4-day series with daily values [10, 12, 11, 15], where at the end of day d we predict tomorrow's value y(d) = value(d + 1): - Consider day 3 (value = 11), whose target is day 4's value (15). - A valid trailing window (averaging the current day and prior two days) computes (10 + 12 + 11) / 3 = 11.00, touching only days 1, 2, 3. - A buggy centered window (rolling(3, center=True), averaging the prior, current, and next day) computes (12 + 11 + 15) / 3 = 12.67—hiding one-third of the target 15 inside day 3's feature! - If we delete all data after day 3 and recompute features (the truncation test), the trailing mean stays 11.00, whereas the centered mean changes to None, exposing the leak automatically.

Key points

  • Write the prediction contract first: Fix prediction timestamp t, target horizon h, entity grain, and each data source's available_at timestamp (when the record is actually published, as opposed to its calendar event date). Feature leakage means using any record with available_at > t.
  • Audit raw CSV structure before feature math: Enforce UTC datetime parsing, unique (entity, date) keys, explicit sorting by (entity, date), gap inspection, and checks for survivorship bias (keeping only entities that survived to the end of the dataset). Always group .shift() and .rolling() by entity in panel data (multiple entities tracked across dates).
  • Use as-of joins and prefix truncation to guarantee point-in-time safety: Join delayed external tables with an as-of join (matching the latest record per entity with available_at <= t), and verify features with an automated truncation test (features(raw[available_at <= t]) at t must equal features(raw) at t).
  • Tune with purged walk-forward validation: Walk-forward validation trains on past dates and validates on successive future date blocks. Apply purging (dropping training days with d + h > v before validation start v so multi-day labels finish before validation starts), fit scalers/encoders strictly inside each training fold, benchmark against a persistence baseline (y_hat(d) = value(d)—e.g., fold MAE, or Mean Absolute Error, dropping from 2.50 to 1.90 for a 24% error reduction), and touch the final test block once.
  • Share one feature function and replay-test inference: Bundle the fitted model, training-fit preprocessor state, ordered feature schema, lookback requirement (max_window + max_lag), and version metadata; reuse the exact same build_features(history, as_of, lookback) function in training and serving; verify 1e-9 parity on replayed past dates; and monitor missingness, Population Stability Index (PSI) (a binned measure of distribution shift from training to live), and delayed realized error.

Common mistakes

  • Using random K-fold or a shuffled train_test_split on chronological data, or splitting a multi-entity panel by row count instead of by calendar date.
  • Calling df["value"].shift(-h) or .rolling(w) without .groupby("entity"), bleeding one entity's history or target into the neighboring entity's rows.
  • Fitting imputers, scalers, quantile clippers, target encoders, or feature selectors on the entire dataset before splitting into folds.
  • Joining external reports on event date rather than publication timestamp (available_at), or training on restated database snapshots instead of point-in-time values.
  • Forgetting to purge the last h - 1 training days before a split when the target horizon h > 1, letting training targets overlap the validation window.
  • Tuning hyperparameters directly on the final test period, or reporting model MAE/RMSE without comparing against a naive persistence baseline on the exact same folds.
  • Maintaining separate offline and online feature code, silently defaulting missing live feeds to 0, or feeding inference fewer historical days than lookback requires.

Follow-up questions

  • How can a moving-average feature still introduce look-ahead leakage even when train and test sets are split strictly by date? A chronological split only separates which prediction rows go into train versus test; it does not stop a feature column computed beforehand from peeking past each row's prediction timestamp. For example, if rolling(3, center=True) is computed on the full CSV before splitting at day 3, day 3 sits in the training set while day 4 sits in the test set, yet day 3's feature (12 + 11 + 15) / 3 = 12.67 already contains day 4's value 15. Even within the training set alone, every training row's centered mean contains tomorrow's target, so the model learns a shortcut that vanishes at live prediction time when tomorrow's value is missing. A moving average also leaks after a clean split if it includes day d when predictions must be made before day d closes, rolls over a target-derived column, lacks .groupby("entity"), or is scaled using full-sample statistics—all of which the prefix-truncation test catches.
  • Suppose backtest scores look strong, yet accuracy drops sharply on the very first day of live scoring. How would you diagnose the root cause? An abrupt day-one drop points to an offline leak or a pipeline bug (training-serving skew), not gradual market drift. First, run the prefix-truncation and point-in-time audit on the offline backtest to verify the strong offline score was genuine rather than an artifact of restated data or a leaky join. Second, run a historical replay for recent dates and diff offline versus live feature vectors column by column, checking for unapplied scalers, swapped column order, timezone offsets, category-map mismatches, a history buffer shorter than lookback (producing NaN or truncated rolling windows), or delayed external feeds that had already arrived in the historical CSV but are still pending at live cutoff time. Third, check the live persistence baseline over the same days: if the naive baseline also spiked in error, the underlying regime jumped; if only the ML model degraded, the serving pipeline or feature contract is broken. Finally, verify that live evaluation joins predictions to the exact same target definition and horizon h used offline.

Follow-up questions

Similar questions

More Voleon interview questions

All 34 Voleon questions →