The critical ordering is **availability filter first, version selection second, event-time filter third**. An event that happened in September but was entered or corrected in November must not alter the features used for an October decision.

**Manus AI · 22 November 2026 · Code extracted from the tested example; streaming adaptation proposed, not executed**

## The timestamp filtering that prevents the backfill leak

This is the safe path from `known_versions` in `retention_leakage_demo.py`, with its deliberately unsafe switch omitted:

```python
e = events.merge(
    decisions[["student_id", "decision_time"]],
    on="student_id", how="inner", validate="many_to_one"
)

# 1. Only versions actually available at this decision.
e = e.loc[e["available_at"] <= e["decision_time"]].copy()

# 2. Choose the newest version among those eligible versions.
e = e.sort_values(
    ["student_id", "event_id", "available_at", "version"]
)
e = e.drop_duplicates(["student_id", "event_id"], keep="last")

# 3. Then enforce occurrence time, lookback and the allowed event type.
eligible = (
    (e["event_time"] <= e["decision_time"])
    & (e["event_time"] >= e["decision_time"] - pd.Timedelta(days=90))
    & e["kind"].eq("activity")
)
e = e.loc[eligible].sort_values(
    ["student_id", "event_time", "event_id"]
)
```

In the fixture, version 1 of an October student's last event is available on 14 October. Version 2 has the same occurrence date but is only available on 19 November. At the 15 October decision, the first filter removes version 2; deduplication retains version 1.

Without that filter, the current table's version 2 wins. Deduplicating first and filtering availability afterwards is also wrong: version 1 would already have been thrown away. A further subtlety is that a known correction can move an event outside the historical window. Choose the latest available version before checking window membership; do not accidentally fall back to a superseded version that happens to lie inside the window.

This rule assumes trustworthy, immutable availability metadata. A timestamp guessed from the event date cannot establish when a record was accessible.

## The assertions that catch the broken extractor

The source locations are `retention_leakage_demo.py`, functions `assert_future_invariance` and `build_features_EVENT_TIME_ONLY_POSITIVE_CONTROL`, plus `test_retention_leakage_demo.py`. No streaming tests have been added to those files.

### Exact feature invariance

The helper first extracts features, mutates only unavailable records, and extracts again:

```python
before = extractor(events, decisions)
after_events = mutate_unavailable_records(events, decisions)
after = extractor(after_events, decisions)

assert_frame_equal(before, after, check_exact=True)
```

The mutation changes payloads of later corrections and appends an old event entered after the decision. The safe extractor ignores both. Exact equality checks values, columns, student alignment and missing-value placement.

The event-time-only extractor admits the late corrections and the newly appended old event. History means, counts or last values change, so **this feature assertion fails first**. It catches forbidden influence even if the classifier would happen to ignore the changed feature.

### Frozen prediction and parameter invariance

The helper then uses the same model on both matrices:

```python
probabilities_before = model.predict_proba(before)
probabilities_after = model.predict_proba(after)
assert_allclose(
    probabilities_before, probabilities_after,
    rtol=0, atol=1e-12
)
```

This checks probabilities rather than only thresholded classes. A probability change can matter even when both predictions still say retained. The numerical tolerance is a declared setting for this example, not a universal precision requirement.

The safe-path regression also saves the logistic-regression coefficients and verifies they were not changed:

```python
coefficients = model.named_steps["model"].coef_.copy()
assert_future_invariance(model, fixture.events, fixture.decisions)
assert_allclose(
    coefficients, model.named_steps["model"].coef_,
    rtol=0, atol=0
)
```

That parameter assertion checks the classifier coefficients specifically; it is not a hash of every preprocessing component. A streaming adaptation should freeze or fingerprint the full model and preprocessing state used at the decision.

### An expected failure that proves detection sensitivity

The broken wrapper calls `known_versions(..., check_availability=False)`. Its test explicitly requires the invariance helper to fail:

```python
with pytest.raises(AssertionError):
    assert_future_invariance(
        model, fixture.events, fixture.decisions,
        extractor=build_features_EVENT_TIME_ONLY_POSITIVE_CONTROL
    )
```

`pytest.raises` makes this test pass only when the known bad extractor causes an assertion failure. If it starts passing the invariance check, the detection test fails. This is a positive control for a deliberately introduced fault, not evidence that the broken model is valid.

Because feature equality is checked first, this test does not separately demonstrate a probability failure under the broken extractor. It demonstrates that the feature boundary violation was caught before prediction comparison.

### Direct eligibility and version-selection checks

The fixture's legal history contains only version 1, so the test checks:

```python
assert selected["version"].eq(1).all()
assert selected["available_at"].le(selected["decision_time"]).all()
assert selected["event_time"].le(selected["decision_time"]).all()
assert len(selected) == len(fixture.decisions) * 32

wrong = known_versions(
    fixture.events, fixture.decisions, check_availability=False
)
assert int(wrong["version"].eq(2).sum()) == len(fixture.decisions)
```

The last assertion confirms exactly what the faulty path admits. The event-time assertion by itself would not catch these corrections: their event dates are old enough. The availability assertion is the missing diagnostic condition.

“Version 1 only” and “32 events per student” are fixture expectations, not production rules. In production, version 2 can be perfectly legitimate for a later decision; compare with the latest version known at that particular decision.

### Boundary checks

The two boundary tests use the same pattern for availability and occurrence time:

```python
# At the cutoff, the record is eligible.
assert len(known_versions(row, decision)) == 1

# After advancing the tested timestamp by one nanosecond, it is not.
assert known_versions(row, decision).empty
```

These are extracted assertions; the original tests set the relevant timestamp to the cutoff and then advance it. They catch an incorrect inequality or the wrong clock being used. For a store that truncates timestamps to milliseconds, repeat the test at its actual supported precision rather than claiming nanosecond behavior.

### The remaining regression checks

The other tests reject duplicate immutable version keys and missing availability metadata with `pytest.raises(ValueError)`. They also reject repeated decision rows because the original example intentionally supports only one decision per student. A streaming system must replace that restriction with a proper `decision_id`, not silently overwrite earlier decisions.

Row-order shuffling is checked with `assert_frame_equal(..., check_exact=True)`. Empty histories must retain all decision rows, have zero event counts and missing channel summaries. The predictor columns must exclude `student_id`, `retained` and `decision_time`. These checks address join integrity and feature contracts; identifier exclusion alone does not establish absence of leakage.

A training-label availability test requires `fit_and_predict` to reject an outcome revealed after `MODEL_AS_OF`. Another test flips labels and late-correction payloads and requires safe feature equality. Neither establishes process-level access isolation: actual services still need separate permissions and stores for unrevealed outcomes.

The final scoring tests compare the custom rank AUC with scikit-learn, require an intentionally perfect outcome-copy panel to trigger the declared null-test flag, and reject single-class AUC. Those validate the scoring mechanism, not temporal eligibility. The original sixteen tests cover these separate failure routes; no one assertion certifies the entire system.

## Adapting the suite to an incremental streaming feature store

### Keep both source availability and feature visibility

Retain an append-only event-version ledger with immutable `(student_id, event_id, version)` identity, payload hash, occurrence time and the first time that version became accessible to the feature pipeline. Keep source partition and offset or equivalent lineage. A correction is a new version, not a rewrite of an old payload or its availability time.

Also record when each derived feature version became committed and visible to the serving read. Source availability and feature-store visibility are different. A record accessible at 09:58 but committed to the online store at 10:02 cannot have contributed to a feature vector actually read at 10:00.

For every decision, preserve `decision_id`, student identity, decision/read time, the exact feature vector including defaults, feature-definition version and the model/preprocessing version. Record serving commit/read versions and source progress where available. If a read spans several feature views without an atomic snapshot, retain the versions actually read from each view or at least the exact vector delivered to the model.

Ordinary online retrieval is not a historical audit API. Feast documents online reads as retrieving a latest value per entity without decision timestamps; historical retrieval uses timestamped entity rows. A later query to the current online store cannot reconstruct the original read unless historical serving state was retained. [2]

### Use two separate reference comparisons

The first comparison is **as served**: did replay reproduce the feature vector actually used for this decision? Its reference is the immutable decision log or a reproducible historical serving snapshot.

The second is **eligible-input replay**: did batch reconstruction select exactly the source versions that were eligible at the decision and implement the intended aggregation? The existing `build_features` supplies the simple example's reference logic. Extend it to process each `decision_id` separately, choosing versions per decision and event before applying the window.

These references need not match. The eligible-input replay can include an on-time source record that the serving pipeline had not materialized. That difference is a freshness or delivery issue, not automatically leakage. It becomes leakage if a retrospective evaluation uses later feature state while claiming to reproduce the actual earlier decision.

### Update aggregates by replacing, not double-counting

When a correction becomes eligible for a later decision, remove the superseded contribution and apply the corrected one. For a count or sum, do not treat every version as a new event. For first/last values, a late arrival must be ordered by the declared event-time/version rules rather than simply becoming “last” because it arrived last.

A correction can remove an event from the window or alter which event supplies the maximum timestamp. Window expiry must also work for inactive students: a 90-day count cannot remain stale forever merely because no new event triggers an update. Use a declared read-time evaluation or timer policy.

Recompute the appropriate sufficient statistics or retained event state. Means, standard deviations and first/last summaries do not all support the same update method. Validate incremental values against the batch reference with justified floating-point tolerances rather than hashing differently ordered floating-point sums as though every difference were leakage.

### Extend the mutation test around a fixed serving frontier

Capture the feature state and frozen model used at decision `d1`. Then inject a later correction with `event_time < d1` but `available_at > d1`, process it, and ask the historical API for `d1` again. The historical vector and frozen prediction must remain unchanged.

Then query a later decision `d2`, after the correction is eligible and its feature update is visible. That result may legitimately change. This is the key streaming distinction: **protect old decisions; do not prevent legitimate future updates**.

In a test harness, the expected comparisons would be:

```python
# Illustrative adapter API; not implemented by the existing example.
old = store.read_historical(decision_id="d1")
store.ingest(late_correction)
store.flush_until_visible()

assert_features_equal(
    old, store.read_historical(decision_id="d1")
)
assert_features_close(
    batch_reference_for_d2,
    store.read_at_decision(decision_id="d2")
)
```

Compare feature values first, then use the model version captured for the relevant decision. If the model itself learns incrementally, record its update frontier too and prohibit learning from an outcome before that outcome becomes available.

### Test retries, recovery and late-data policy explicitly

An identical delivery retry should not increase counts or sums. The same immutable version identity with a different payload is a conflict to reject or quarantine, not a duplicate to silently overwrite. The batch fixture currently rejects duplicate keys; the streaming adapter should permit verified identical retries while rejecting conflicts.

Crash and resume around sink writes. Under an equivalent source/visibility frontier, recovery should not double-apply events, lose corrections or assign an earlier historical availability. Spark's micro-batch fault-tolerance description depends on replayable sources, progress tracking and idempotent sinks; that is not a certification of an unspecified feature-store sink. [3]

Reordering and changing batch sizes are legitimate invariance tests only when the eligible records, visible commits, logical decision clock and late-data policy are held equivalent. Changed scheduling can change backpressure and what was served at a wall-clock instant. Test that freshness effect separately instead of automatically labelling it leakage.

Watermarks manage event-time progress and retained state, not prediction-time permission. Spark also states that data beyond its declared lateness threshold may or may not be aggregated. A watermark therefore cannot replace `available_at <= decision_time`, and different processing orders can affect state eviction. Compare with a reference that applies the same declared lateness policy, while separately measuring what that policy discards. [3]

### A concrete Feast configuration caveat

The current Feast documentation explicitly says its default point-in-time join filters event time, while a created timestamp normally serves deduplication. It documents this additional option: [1]

```python
training = store.get_historical_features(
    entity_df=decision_rows,
    features=feature_references,
    filter_by_created_timestamp=True,
).to_df()
```

That flag adds a created-time cutoff. Use it only if the installed Feast version and offline backend support it, and the source's created timestamp truly represents availability under the intended contract. The documentation says null created timestamps are excluded and unsupported stores raise an error. Even with the flag, reproducing what was actually served requires trustworthy online visibility metadata; source publication time is not necessarily feature commit time. [1]

For the streaming null-data test, feed independent synthetic student outcomes and serially correlated histories through the actual ingestion, state updates and serving path. Retain every seed, delivery schedule, decision vector and later outcome. Inject known backfill leaks as isolated positive controls. Keep future outcomes out of both feature updates and online model learning until their recorded release time. This extends the earlier diagnostic; it is not evidence that an unspecified streaming deployment has already passed.

## References

[1]: https://docs.feast.dev/getting-started/concepts/point-in-time-joins "Feast: Event-time joins, creation-time filtering, backfills and backend limitations"
[2]: https://docs.feast.dev/getting-started/concepts/feature-retrieval "Feast: Historical and online feature retrieval and timestamp semantics"
[3]: https://spark.apache.org/docs/3.5.6/structured-streaming-programming-guide.html "Apache Spark 3.5.6: Structured Streaming watermarks, recovery and fault-tolerance conditions"
