Sub topic 4
Cause 1: The Same Feature Written Twice
This chapter assumes you can read Python and pandas, and that you know the train, validate, predict workflow. It also assumes you have a rough picture of a model served behind an API or batch job. By the end you should be able to spot duplicated feature logic in a codebase, explain how the copies diverge, and see why that divergence produces no error.
How the same feature ends up written twice
Training and serving usually start as separate projects with different owners and constraints.
- Training runs in a notebook or batch job. It uses pandas or SQL over a large table, and it works on whole columns at once.
- Serving runs in a low-latency service. It receives one request at a time, often as JSON, and cannot afford to scan a table.
A data scientist writes age cleaning, days_since_signup and similar features in the notebook. An engineer then reads that notebook and re-implements it in the service, often in a different language. Each rewrite is a chance to change the behavior. The two copies start in agreement, and then they drift apart as bug fixes and tweaks land in only one of them.
This is called code skew. The model's weights are fixed, so any disagreement between copy A and copy B changes the inputs the model sees in production but not the model itself.
A minimal example
The two snippets below implement "fill missing ages" in two places. The training path uses the column mean. The serving path was written separately and uses 0.
import pandas as pd
# Training path: missing ages are filled with the training mean (40.0)
train = pd.DataFrame({"age": [30, 40, None, 50]})
train["age"] = train["age"].fillna(train["age"].mean())
# Serving path: a separately written handler fills missing ages with 0
def serve_features(request: dict) -> dict:
return {"age": request.get("age") or 0}
print(train["age"].tolist()) # [30.0, 40.0, 40.0, 50.0]
print(serve_features({"age": None})) # {'age': 0}During training, a missing age looked like a typical 40-year-old. In production, the same missing age looks like a newborn. The model has never seen a feature value of 0 in that column, so its output for these requests is unreliable.
The handler has a second bug: request.get("age") or 0 also turns a real age of 0 into 0. This case is harmless here, but the same or pattern replaces any falsy value, such as 0.0 or an empty string, with the default.
The usual ways copies diverge
Missing-value defaults are the most visible case. The table lists others that appear in real systems.
| Divergence | Offline (training) | Online (serving) | Effect |
|---|---|---|---|
| Missing-value fill | Mean or median of the training column | A constant such as 0 or -1 | Shifted values for every request with a gap |
| Rounding and casting | Float kept as is | Cast to `int` (truncates) | Small systematic bias |
| Time boundaries | Calendar days (midnight cutoffs) | Elapsed 24-hour periods | Off-by-one on counts of days |
| Time zones | Everything converted to UTC | Server local time | Wrong day or hour near midnight |
| String cleanup | `.str.lower().str.strip()` | No cleanup, or only `.lower()` | Categories fail to match |
| Window definition | Trailing 30 days, inclusive | Last 30 events | Different aggregates |
| Unknown categories | Mapped to an "other" bucket | Raises or maps to 0 | Errors or a wrong bucket |
| Library version | Older version of a function | Newer version with different defaults | Subtle numeric changes |
Example: two definitions of "days since signup"
The offline version subtracts calendar dates. The online version counts completed 24-hour periods. They disagree whenever the time of day of the event is earlier than the time of day of the signup.
import pandas as pd
def offline_days_since_signup(df: pd.DataFrame) -> pd.Series:
# Calendar-day difference: midnight to midnight
return (df["event_time"].dt.normalize() - df["signup_time"].dt.normalize()).dt.days
def online_days_since_signup(row: dict) -> int:
# Elapsed time floored to whole 24-hour periods
return int((row["event_time"] - row["signup_time"]).total_seconds() // 86400)
df = pd.DataFrame({
"signup_time": pd.to_datetime(["2026-01-01 23:00", "2026-01-01 08:00"]),
"event_time": pd.to_datetime(["2026-01-02 01:00", "2026-01-02 09:00"]),
})
print(offline_days_since_signup(df).tolist()) # [1, 1]
print([online_days_since_signup(r) for r in df.to_dict("records")]) # [0, 1]The first row differs: two hours after signup, the offline code says one day and the online code says zero. Each function looks reasonable in isolation, and a code reviewer reading only one of them would not flag it.
Why it fails silently
Nothing in this setup raises an error.
- The service receives a number where it expects a number, so type checks pass.
- The model returns a probability for any numeric input, so the API returns 200.
- Offline evaluation used the training-path features, so the validation metrics still look good.
- Latency, error rate and throughput dashboards stay green.
The only visible symptom is lower accuracy or business impact, and it appears later and is easy to blame on something else, such as a seasonal change or a new customer segment. Because you cannot see the problem from system health, you need explicit checks, which later chapters cover.
How to find duplicated logic in your own code
Start with an audit of where each model input is computed.
- List every feature the model consumes, using the training column names.
- For each one, find the code that produces it in the training pipeline and the code that produces it at serving time.
- If you find two separate implementations, mark the feature as at risk, even if they look identical today.
- Check the implicit steps too: default values, type casts, column ordering, and which library version runs in each environment.
- Check whether the serving code receives raw values or values already transformed upstream. A transformation applied twice, or applied in only one path, is also a form of code skew.
Signs that duplication exists include a feature function with a "ported from the notebook" comment, SQL and Python versions of the same name, and a utils file that exists in only one repository.
A quick empirical check
You can compare the two implementations directly on the same raw data. Here is a small script that does this for the two days-since-signup functions above.
import pandas as pd
def offline(df: pd.DataFrame) -> pd.Series:
return (df["event_time"].dt.normalize() - df["signup_time"].dt.normalize()).dt.days
def online(row: dict) -> int:
return int((row["event_time"] - row["signup_time"]).total_seconds() // 86400)
df = pd.DataFrame({
"signup_time": pd.to_datetime(["2026-01-01 23:00", "2026-01-01 08:00"]),
"event_time": pd.to_datetime(["2026-01-02 01:00", "2026-01-02 09:00"]),
})
off = offline(df)
on = pd.Series([online(r) for r in df.to_dict("records")], index=df.index)
mismatch = df[off != on]
print(f"{len(mismatch)} of {len(df)} rows differ")
print(mismatch.assign(offline=off[mismatch.index], online=on[mismatch.index]))Run on a few thousand real events, a mismatch rate above zero tells you which feature to fix and which inputs trigger it. The chapter on parity testing turns this into an automated test.
What the fix looks like
The goal is that each feature has one definition that both paths call. There are three common routes.
- Shared library. Put the feature function in a package that both the training job and the service import.
- Bundled pipeline. Package the preprocessing with the model so serving calls the same object that training fitted.
- Feature store. Define features once in a registry that produces both training data and online values.
Later chapters cover each in turn. The key point here is that code review and good intentions are not enough. Two copies of the same logic will diverge over time unless something makes them one.
Exercise
A serving handler computes income_k = int(request["income"] / 1000). The training pipeline computes income_k = df["income"] / 1000. Name the divergence, give an input that exposes it, and explain why no error appears.
Show answer
The serving copy truncates to an integer and the training copy keeps the fraction. For income = 52900, training gives 52.9 and serving gives 52. Both are valid numbers, so the model accepts them and returns a prediction. The error is a small systematic bias that no type check or health metric detects.
Exercise
Your service returns HTTP 200 for every request, latency is normal, and offline validation AUC is 0.91, but the production conversion rate from the model's recommendations is much lower than expected. List two checks that would test the code-skew hypothesis.
Show answer
First, audit each feature for separate offline and online implementations. Second, run both implementations on the same raw events and compare the outputs, or compare logged serving feature values against the training distribution for the suspect features. Either check shows whether the inputs differ before you retrain or tune the model.