---
url: /blog/leakage-multi-table-features.md
description: >-
  Why aggregating child tables leaks future data into a model, how to measure it
  with temporal cross-validation, and how per-sample cutoffs prevent it.
---

# Data leakage in multi-table feature engineering, and how to avoid it

**If a feature includes orders placed after the prediction date, validation
uses information the model would never see at prediction time. Give each
sample a cutoff and aggregate only earlier orders, in training and validation.**

## Where the leak hides

A typical churn or fraud dataset has an entity table and event tables.

* `customers`: one row per customer.
* `orders`: one row per order, with a date.

Suppose you predict at the start of April. A `groupby` over the full orders
table can include a purchase made in May. A chronological split alone cannot
fix that feature, because it has already mixed past and future records into
each customer's row.

## A dataset that punishes the leak

`make_relational_classification(with_time=True)` builds such a dataset. Each
customer is observed at four cutoffs, 90 days apart. The label at a cutoff
depends on the orders created before it, and after each cutoff the generator
adds orders that follow the pattern of the opposite class. A model that reads
those orders is misled.

```python
from sklearn.model_selection import cross_val_score
from sklink.datasets import make_relational_classification
from sklink.model_selection import TemporalCutoffSplit
from sklink.tree import RelationalDecisionTreeClassifier

db, X, y = make_relational_classification(
    n_entities=600,
    signal="child_categorical",
    with_time=True,
    n_cutoffs=4,
    random_state=0,
)
print(X.head(3))
splits = list(TemporalCutoffSplit(time="cutoff", n_splits=3).split(X))
```

```text
   customer_id     cutoff
0            0 2024-03-31
1            1 2024-03-31
2            2 2024-03-31
```

## Measure the damage

Fit the same tree twice on the same temporal splits. The first ignores the
cutoff, like a `groupby` over all orders. The second only reads orders created
strictly before each sample's cutoff. Order items inherit visibility from
their parent orders, so an item in a future order is hidden too.

```python
leaky = RelationalDecisionTreeClassifier(
    db, entity="customers", key="customer_id", max_depth=3
)
safe = RelationalDecisionTreeClassifier(
    db, entity="customers", key="customer_id", time="cutoff", max_depth=3
)
print(
    f"ignores the cutoff:  {cross_val_score(leaky, X[['customer_id']], y, cv=splits).mean():.3f}"
)
print(f"respects the cutoff: {cross_val_score(safe, X, y, cv=splits).mean():.3f}")
```

```text
ignores the cutoff:  0.699
respects the cutoff: 0.998
```

Ignoring the cutoff lowers accuracy here because the generator adds later
orders with the opposite class pattern. On another dataset, later orders
might reveal the target and inflate accuracy. In both cases the score uses
information unavailable when the prediction is made.

## Three rules that prevent it

1. **Give event tables a time column**, and every sample a cutoff. In
   scikit-link: `Database(..., time_columns={"orders": "created_at"})` and
   `time="cutoff"` on the estimator.
2. **Split by time.** `TemporalCutoffSplit` puts every training cutoff before
   every test cutoff. `label_horizon` drops training samples whose label
   period reaches the test period, and `gap` adds a safety margin.
3. **Fit learned choices inside each fold.** Category vocabularies and rankings,
   bins and thresholds come from the training samples only. scikit-link learns these
   in `fit`. In your own pipeline, apply the same rules to feature selection,
   encoders and any statistics shared across samples.

## When to use static mode {#static-data-is-fine}

Static mode is the default. Use it when the related tables already describe
what was available for each prediction. An untimed table that changes over
time, such as a product catalog, needs special care. A current price can
leak a later change into an earlier prediction even when the orders have
correct cutoffs.

## Learn more

* [Time, cutoffs and temporal cross-validation](https://scikit-link.rodrigo-arenas.com/stable/tutorials/time-and-cutoffs),
  with windows such as the last 30 days and recency features such as `last`
  and `trend`.
* [What is relational machine learning?](../relational-machine-learning), including
  the leakage pitfalls of multi-table data.
