Sub topic 12
Testing offline and online parity
This chapter assumes you can write pytest tests and use pandas. It also assumes you have seen the earlier chapters on duplicated feature code, shared transformations, and bundled pipelines. Those chapters reduce the chance of skew. A parity test checks that the reduction worked, and it keeps working as the code changes.
What a parity test checks
A parity test feeds the same raw input through the offline (batch) feature code and the online (serving) feature code. It then compares the outputs. If the two paths disagree beyond a small tolerance, the test fails before the code ships.
The test does not check that the features are good. It checks that the two paths are the same function, which is the property training-serving skew breaks.
Parity tests are most valuable in three situations:
- You could not fully share code, for example a batch job in Spark and a service in Python.
- You use a feature store with separate offline and online materialization paths.
- You share code today but expect it to change. A refactor can quietly add a branch to only one path.
Even a fully bundled pipeline benefits from a parity test. Its preprocessing is shared, but the code around it (request parsing, type coercion, default filling) often is not.
A runnable parity test
The first example defines both transforms in one file so you can run it with pytest. In a real project you would import them from your offline and online modules.
The offline transform works on a whole DataFrame. The online transform works on one request dictionary, as a serving handler would.
import pandas as pd
import pytest
from pandas.testing import assert_frame_equal
TRAIN_MEAN_AGE = 40.0
def offline_transform(df: pd.DataFrame) -> pd.DataFrame:
out = pd.DataFrame(index=df.index)
out["age"] = df["age"].fillna(TRAIN_MEAN_AGE)
out["is_new"] = (df["days_since_signup"] < 30).astype(int)
return out
def online_transform(event: dict) -> dict:
age = event.get("age")
return {
"age": TRAIN_MEAN_AGE if age is None else float(age),
"is_new": int(event["days_since_signup"] < 30),
}
def buggy_online_transform(event: dict) -> dict:
# Serving handler that fills missing ages with 0 instead of the training mean
return {
"age": float(event.get("age") or 0),
"is_new": int(event["days_since_signup"] < 30),
}
@pytest.fixture
def raw_events():
return [
{"age": 30, "days_since_signup": 5},
{"age": None, "days_since_signup": 400},
{"age": 0, "days_since_signup": 30},
{"age": 52.5, "days_since_signup": 29},
]
def check_parity(offline_fn, online_fn, raw_events):
offline = offline_fn(pd.DataFrame(raw_events))
online = pd.DataFrame([online_fn(e) for e in raw_events])
assert_frame_equal(
offline.reset_index(drop=True),
online[offline.columns].reset_index(drop=True),
check_exact=False,
rtol=1e-6,
)
def test_parity_holds(raw_events):
check_parity(offline_transform, online_transform, raw_events)
def test_parity_catches_zero_fill_bug(raw_events):
with pytest.raises(AssertionError):
check_parity(offline_transform, buggy_online_transform, raw_events)The second test is a guard on the guard. It shows that your comparison fails when it should. A parity test that cannot fail is worse than no test, because it gives false confidence.
The edge-case events were chosen on purpose. They include a missing value (None), a legitimate zero (age: 0), a value on a threshold boundary (days_since_signup: 30), and a fractional value. The buggy handler's or 0 treats a real zero and a missing value identically. Here that is harmless for age: 0, but the same pattern breaks features where 0 is meaningful.
What to compare and how
Naive equality checks produce false alarms or miss real differences. Decide these points explicitly.
| Concern | Typical trap | What to do |
|---|---|---|
| Floating point | Batch (vectorized) and per-row code round differently | Compare with a relative tolerance such as `rtol=1e-6`, not exact equality |
| Missing values | `None`, `NaN`, empty string, and absent key are handled differently | Include every missing form your sources can emit in the test events |
| Dtypes | `int` vs `float`, or `object` vs `category`, can change model input | Let `assert_frame_equal` check dtypes (its default), and cast deliberately |
| Column order | Models index features by position | Reorder to the offline column order before comparing, as above |
| Unseen categories | One path errors and the other ignores | Add an unseen category to the events and assert the same outcome |
| Timestamps | Time zone and truncation differ | Use time-zone-aware values and events near day or hour boundaries |
| Row independence | Batch code uses a whole-column statistic computed on the test set | Use statistics fitted in training, never recomputed from the test data |
The last row is a frequent source of false parity. If the offline code calls df["age"].mean() on the data it receives, the test passes only because the test data is small and consistent. Fitted statistics belong in saved state, as covered in the chapter on fit-time state.
Choosing test inputs
The quality of a parity test depends on the events it uses. Three sources work well together.
- Hand-written edge cases. Missing values, zeros, negatives, extremes, unseen categories, and boundary values for every threshold in your features.
- Golden events from production. Sample real requests from your serving logs, with identifiers removed. These contain the odd formats and combinations you did not think of. Store them as a small fixture file in the repository.
- Generated inputs. A property-based tool such as Hypothesis can generate many events from a schema and assert that the two paths agree on all of them. This finds inputs no one wrote down.
Keep the golden set small enough to run on every commit, for example a few hundred events. Run a larger replay on a schedule.
Features that depend on history
Single-event comparison works for features computed from the request alone. Aggregates such as logins_30d depend on past events, so the test needs history as well as the event.
For these features, replay a short event log through both paths:
- Offline: compute the feature for each label time using an as-of join, as in the chapter on point-in-time correctness.
- Online: feed the same events, in time order, to the online aggregation (a stream job or a feature store's online store) and read the value at each label time.
Compare the two values per (entity, time) pair. Expect some boundary disagreements. A streaming window may include an event that arrived at exactly the cutoff, while the batch window excludes it. Decide which behavior is correct, document it, and make both paths follow it. Do not widen the tolerance to hide it.
import pandas as pd
def compare_by_key(offline: pd.DataFrame, online: pd.DataFrame, feature: str, tol=1e-6):
"""Return the rows where offline and online values of `feature` disagree.
Both frames need columns user_id, label_time and the feature column.
"""
merged = offline.merge(
online,
on=["user_id", "label_time"],
how="outer",
suffixes=("_offline", "_online"),
indicator=True,
)
missing = merged[merged["_merge"] != "both"]
both = merged[merged["_merge"] == "both"]
diff = (both[f"{feature}_offline"] - both[f"{feature}_online"]).abs()
return pd.concat([missing, both[diff > tol]])
offline = pd.DataFrame({"user_id": [1, 1], "label_time": ["t1", "t2"], "logins_30d": [12, 7]})
online = pd.DataFrame({"user_id": [1, 1], "label_time": ["t1", "t2"], "logins_30d": [12, 8]})
print(compare_by_key(offline, online, "logins_30d"))The outer join matters. An inner join would silently drop keys that exist in only one path, and a missing key is itself a parity failure.
Where the test runs
Place the parity test in continuous integration so it runs whenever either path changes. It should trigger on changes to the offline feature code, the serving code, the feature definitions, and the saved preprocessing artifacts.
A parity test also cannot see data it never receives. It will not catch an upstream team changing what a column means, or a source returning stale rows. Those problems are handled by serving-time validation and by the logging and distribution comparisons in the following chapters.
Reading a failure
When a parity test fails, work in this order:
- Find which feature column differs and for which events.
assert_frame_equalnames the column and the first differing values. - Check whether the difference is a missing-value case. This is the most common cause.
- Check dtype and rounding differences next. If the gap is around 1e-9, loosen the tolerance. If it is larger, there is a real logic difference.
- Identify which path is correct according to the training data, then change the other path to match. Do not change the offline path to match a serving bug, because the trained model has already learned from the offline values.
Exercise
Your parity test passes, but production accuracy is still lower than offline evaluation. Name two reasons the test might not have caught the problem.
Show answer
First, the test events may not cover the inputs that cause the mismatch, such as a new category, a missing-value form, or a boundary value that only appears in production. Second, the problem may lie outside the two transforms: an upstream data source may differ between training and serving, or a historical aggregate may be computed differently, which single-event tests cannot see. Refresh the test events from serving logs and add replay-based comparisons and serving-time validation.
Exercise
The offline code computes df["income"].fillna(df["income"].median()). Why can a parity test pass with this code even though the code is wrong for serving, and how would you fix it?
Show answer
The test passes because the median is computed from whatever test data is passed in, and the online path may be written to use the same constant. In serving, a single request has no meaningful median, so the value must come from the training data. Fix it by fitting the median once on the training set (for example with SimpleImputer(strategy="median") inside a saved pipeline) and using that stored value in both paths.