38  Point-in-time correctness — the feature value as it was known, not as it is now

Verbs: asof_join (backward · inclusive · by entity · tolerance look-back · deterministic tie-break) · verify_materialization (the materialized training set’s definition hash + input as-of anchors) · the contrast against a naive current-state JOIN. · Background: point-in-time correctness and label leakage (Kaufman et al. 2012), bitemporal valid-time vs transaction-time (Snodgrass 1999), the feature store’s reason to exist is the as-of join (Orr et al. 2021), and why a leaky split breaks the exchangeability conformal coverage rests on (Barber et al. 2023). · Checked: measurement (the leakage delta and the conformal coverage, live) + parity (the same as-of join in process and from a server, row for row).

The feature-store chapter keeps a feature current in a mutable companion table and federates it into a query by key: the current value. That is the half of a feature store a plain JOIN already does well — and the half that leaks the future into the past the moment a label carries a timestamp.

This chapter demonstrates the hard half, the half that makes a feature store a feature store rather than a join: point-in-time correctness. It is built on the engine’s asof_join and verify_materialization primitives. The measured lesson is sharp and uncomfortable: assembling a labelled set with a current-state join silently inflates a downstream metric and breaks conformal coverage, while the as-of join keeps both honest. The chapter ends in real numbers that show the leak and show it closed.

38.1 The leak, stated plainly

A paper \(p\) carries a label observed at a horizon \(T\), one year after publication: “is \(p\) cited again after \(T\)?” A feature is its citation in-degree. The naive recipe joins the label to the current in-degree — which counts citations that arrived after \(T\). That is leakage: the feature knows the future of the label (Kaufman et al. 2012).

The fix is to keep the feature as a time series — each paper’s in-degree as of each year a citation arrived, stamped with the citing paper’s year — and to read, for each label, the value as of its horizon.

This is the valid-time vs transaction-time distinction (Snodgrass 1999) made operational: the citation edge’s event time (cited_at) bounds the join; the as-of instant is the valid time of the label.

38.2 The as-of fix — one verb, four pinned knobs

asof_join matches each spine row to at most one fact row — the fact valid as-of the spine’s temporal key, within each equality group. Four knobs are pinned on the call, and each changes the result. We show them live on a tiny worked relation so the semantics are unmistakable, then apply the same verb to the full committed graph.

The Python surface takes lowercase direction / boundary strings, resolves the bare registered source ids, and the output result table is read as "jammi.<table>".

import tempfile

import jammi
import pyarrow as pa
import pyarrow.parquet as pq
from jammi_cookbook import fixtures
from jammi_cookbook.claims import claim

work = tempfile.mkdtemp()
db = jammi.connect(f"file://{tempfile.mkdtemp()}")

# A tiny spine (one entity 'p', as-of horizon T = 20) and four facts at increasing
# event times, one of them stamped EXACTLY at the spine instant (t = 20).
pq.write_table(pa.table({"entity": ["p"], "as_of": [20]}),
               f"{work}/spine.parquet")
pq.write_table(pa.table({
    "entity": ["p", "p", "p", "p"],
    "t":      [10,  20,  25,  40],   # t=20 is coincident with the spine instant
    "val":    [1,   2,   3,   4],
}), f"{work}/facts.parquet")
db.add_source("spine", url=f"file://{work}/spine.parquet", format="parquet")
db.add_source("facts", url=f"file://{work}/facts.parquet", format="parquet")


def asof(direction, boundary, **kw):
    out = db.asof_join(
        "spine", "facts",
        spine_by=["entity"], spine_time="as_of",
        facts_by=["entity"], facts_time="t",
        direction=direction, boundary=boundary, project=["val"], **kw,
    )
    row = db.sql(f'SELECT val FROM "jammi.{out}"').to_pylist()[0]
    return row["val"]

Direction — backward is the only leakage-safe choice for a past label: it takes the most recent fact at or before the spine instant. forward would import a fact from after the label — leakage by construction.

print(f"backward (leakage-safe): val = {asof('backward', 'exclusive')}  "
      f"# the most recent fact before t = 20")
print(f"forward  (LEAKS):        val = {asof('forward', 'exclusive')}  "
      f"# the first fact after t = 20 — imports the future")
backward (leakage-safe): val = 1  # the most recent fact before t = 20
forward  (LEAKS):        val = 3  # the first fact after t = 20 — imports the future

Boundary — inclusive (<=) lets a fact stamped exactly at the spine instant match; exclusive (<) excludes it. This is the single most error-prone as-of decision; the verb pins it rather than inferring it.

print(f"backward inclusive (<=): val = {asof('backward', 'inclusive')}  "
      f"# the t=20 fact matches")
print(f"backward exclusive (<):  val = {asof('backward', 'exclusive')}  "
      f"# the t=20 fact is excluded — falls back to t=10")
backward inclusive (<=): val = 2  # the t=20 fact matches
backward exclusive (<):  val = 1  # the t=20 fact is excluded — falls back to t=10

Tolerance — a look-back limit, measured relative to each spine instant (never wall-clock now). A candidate older than the limit is treated as no-match — the spine row is preserved with a null fact, never matched to a stale fact.

# Drop the coincident t=20 fact's reach: with a 5-step look-back the nearest backward
# fact (t=10, distance 10) is too stale, so the match is null; with no tolerance it hits.
print(f"backward, tolerance=5 steps: val = "
      f"{asof('backward', 'exclusive', tolerance_steps=5)}  # t=10 is >5 steps stale → null")
print(f"backward, no tolerance:      val = "
      f"{asof('backward', 'exclusive')}  # the stale t=10 fact matches")
backward, tolerance=5 steps: val = None  # t=10 is >5 steps stale → null
backward, no tolerance:      val = 1  # the stale t=10 fact matches

Tie-break — when more than one fact shares the matched instant, the match is ambiguous unless disambiguated by a secondary descending column; otherwise the verb refuses loudly rather than pick non-deterministically. The refusal is the caller’s to fix, so it is an InvalidArgument that names the missing argument; naming a tie_break_column picks the fact with the largest value in it.

pq.write_table(pa.table({"entity": ["q"], "as_of": [20]}),
               f"{work}/spine_dup.parquet")
pq.write_table(pa.table({"entity": ["q", "q"], "t": [20, 20], "val": [7, 8],
                         "revision": [1, 2]}),
               f"{work}/facts_dup.parquet")
db.add_source("spine_dup", url=f"file://{work}/spine_dup.parquet", format="parquet")
db.add_source("facts_dup", url=f"file://{work}/facts_dup.parquet", format="parquet")


def asof_dup(**tie_break):
    return db.asof_join("spine_dup", "facts_dup",
                        spine_by=["entity"], spine_time="as_of",
                        facts_by=["entity"], facts_time="t",
                        direction="backward", boundary="inclusive", project=["val"],
                        **tie_break)


try:
    asof_dup()
    refusal = None
except jammi.errors.InvalidArgument as e:
    refusal = str(e)
print(f"no tie-break → InvalidArgument: {refusal}")

resolved = asof_dup(tie_break_column="revision")
resolved_val = db.sql(f'SELECT val FROM "jammi.{resolved}"').column("val")[0].as_py()
print(f"tie_break_column='revision' → val = {resolved_val}  # the revision-2 fact")
no tie-break → InvalidArgument: as-of join: more than one fact at matched instant 20 in one group; name a tie_break_column to choose among them
tie_break_column='revision' → val = 8  # the revision-2 fact
claim("two facts at one instant are refused until a tie-break column orders them",
      refusal is not None and "tie_break_column" in refusal)
claim("ordered by revision, the later fact resolves", resolved_val == 8, f"val = {resolved_val}")
✓ two facts at one instant are refused until a tie-break column orders them
✓ ordered by revision, the later fact resolves (val = 8)

These are the same four knobs a backtester matching trades to prevailing quotes, or a clinical pipeline matching observations to the lab value in effect, reaches for — no domain vocabulary in the verb. Here they assemble a leakage-free labelled set.

38.3 The feature as a time series

Over the whole citation graph, the engine derives each paper’s in-degree as a time series in SQL — for each year a citation to it arrived, how many citations it had by then — and the label spine: every paper, with its horizon one year after publication.

import numpy as np
from jammi_cookbook import datasets, scale

SCALE = scale.current()
HORIZON = 1
arxiv = datasets.arxiv(db, SCALE)
PAPERS = f"{arxiv.papers}.public.{arxiv.papers}"
CITES = f"{arxiv.cites}.public.{arxiv.cites}"

series = db.sql(f"""
    SELECT paper_id, cited_at,
           SUM(n) OVER (PARTITION BY paper_id ORDER BY cited_at) AS in_degree
    FROM (SELECT c.dst AS paper_id, p.year AS cited_at, COUNT(*) AS n
          FROM {CITES} c JOIN {PAPERS} p ON c.src = p.paper_id
          GROUP BY c.dst, p.year)
""")
spine = db.sql(f"SELECT paper_id, year + {HORIZON} AS as_of FROM {PAPERS} ORDER BY paper_id")
pq.write_table(series, f"{work}/in_degree.parquet")
pq.write_table(spine, f"{work}/labels.parquet")
print(f"{series.num_rows} (paper, year) in-degree values; {spine.num_rows} labelled papers")
530 (paper, year) in-degree values; 400 labelled papers

38.4 The two pipelines

The naive pipeline joins each label to the current in-degree. The as-of pipeline asks asof_join for each paper’s in-degree at the latest time-series point at or before its horizon — backward, inclusive — and a paper with no citation known by then keeps a null, which is an in-degree of zero. The label is what happens after the horizon: whether any citation arrives later.

def as_of_in_degree(db) -> dict:
    """The one definition: each paper's in-degree as known at its horizon."""
    db.add_source("labels", url=f"{work}/labels.parquet", format="parquet")
    db.add_source("in_degree", url=f"{work}/in_degree.parquet", format="parquet")
    table = db.asof_join(
        "labels", "in_degree", spine_by=["paper_id"], spine_time="as_of",
        facts_by=["paper_id"], facts_time="cited_at",
        direction="backward", boundary="inclusive", project=["in_degree"],
    )
    rows = db.sql(f'SELECT paper_id, in_degree FROM "jammi.{table}" ORDER BY paper_id')
    return table, {r["paper_id"]: r["in_degree"] or 0 for r in rows.to_pylist()}


asof_table, known = as_of_in_degree(db)
current = {r["paper_id"]: r["n"] for r in db.sql(
    f"SELECT dst AS paper_id, COUNT(*) AS n FROM {CITES} GROUP BY dst").to_pylist()}
ids = sorted(known)
naive = np.array([current.get(p, 0) for p in ids], dtype=float)
asof = np.array([known[p] for p in ids], dtype=float)
label = (naive > asof).astype(int)  # cited again after the horizon
print(f"{int(label.sum())} of {len(ids)} papers are cited after their horizon")
print(f"in-degree the naive join counts that was unknowable at the horizon: "
      f"{int((naive - asof).sum())} of {int(naive.sum())} citations")
142 of 400 papers are cited after their horizon
in-degree the naive join counts that was unknowable at the horizon: 972 of 1577 citations

38.5 Leakage delta — measured

Both features score the same label on the same held-out papers. The leaky feature contains the answer — a paper cited after its horizon has a current in-degree larger than its as-of one by construction — so its AUC is inflated.

def auc(score: np.ndarray, y: np.ndarray) -> float:
    """Rank-based ROC AUC (Mann–Whitney), ties averaged."""
    order = np.argsort(score, kind="mergesort")
    ranks = np.empty(len(score))
    ranks[order] = np.arange(1, len(score) + 1)
    for value in np.unique(score):
        tied = score == value
        ranks[tied] = ranks[tied].mean()
    pos, neg = y.sum(), len(y) - y.sum()
    return float((ranks[y == 1].sum() - pos * (pos + 1) / 2) / (pos * neg))


rng = np.random.default_rng(0)
split = rng.permutation(len(ids))
train, cal, test = np.split(split, [len(ids) // 2, 3 * len(ids) // 4])
naive_auc, asof_auc = auc(naive[test], label[test]), auc(asof[test], label[test])
print(f"naive (leaky) AUC: {naive_auc:.3f}   as-of (honest) AUC: {asof_auc:.3f}   "
      f"leakage delta {naive_auc - asof_auc:+.3f}")
naive (leaky) AUC: 0.916   as-of (honest) AUC: 0.693   leakage delta +0.223
claim("the leaky feature's AUC is inflated by the answer it contains", naive_auc > asof_auc,
      f"{naive_auc:.3f} against {asof_auc:.3f}")
✓ the leaky feature's AUC is inflated by the answer it contains (0.916 against 0.693)

38.6 The conformal honesty result

A split-conformal classifier at nominal 90% coverage (Barber et al. 2023), built two ways. The leaky pipeline is fitted and calibrated on the current in-degree — the view the training table carried — but at serving time only the in-degree known at the horizon exists, so that is what it scores. The as-of pipeline is fitted, calibrated and served on the as-of in-degree throughout. The engine’s conformalize sets each pipeline’s quantile from its own calibration scores.

ALPHA = 0.10


def fitted(feature: np.ndarray):
    """A classifier from the empirical label rate at each feature value, fitted on the
    training papers; it scores a feature vector into two-class scores."""
    rate = {v: label[train][feature[train] == v].mean() for v in np.unique(feature[train])}
    base = label[train].mean()
    return lambda values: np.c_[1 - (p := np.array([rate.get(v, base) for v in values])), p]


coverage, width = {}, {}
for name, built_on in (("leaky", naive), ("as-of", asof)):
    model = fitted(built_on)
    sets = db.conformalize(model(built_on[cal]).tolist(), label[cal].tolist(),
                           model(asof[test]).tolist(), alpha=ALPHA, score="lac")
    coverage[name] = float(np.mean([y in s for y, s in zip(label[test], sets)]))
    width[name] = float(np.mean([len(s) for s in sets]))
    print(f"{name:<6} pipeline: coverage {coverage[name]:.3f} (nominal {1 - ALPHA:.2f}), "
          f"mean set size {width[name]:.2f}")
leaky  pipeline: coverage 0.840 (nominal 0.90), mean set size 1.32
as-of  pipeline: coverage 0.980 (nominal 0.90), mean set size 1.96
claim("the leaky pipeline under-covers at serving time", coverage["leaky"] < 1 - ALPHA,
      f"{coverage['leaky']:.3f} against a nominal {1 - ALPHA:.2f}")
claim("the as-of pipeline holds nominal, to within two points", 1 - ALPHA <= coverage["as-of"] + 0.02,
      f"{coverage['as-of']:.3f}")
✓ the leaky pipeline under-covers at serving time (0.840 against a nominal 0.90)
✓ the as-of pipeline holds nominal, to within two points (0.980)

The leaky pipeline’s calibration scores came from a feature that already knew the label, so they look easier than anything it meets at serving time; its quantile is too tight and its sets fall short of the promised coverage. The as-of pipeline calibrates on exactly the distribution it serves — exchangeable, so the guarantee holds (Barber et al. 2023). Its sets are honest about how little a known-at-the-horizon in-degree says about the future: where the feature is weak they grow, which is the price of a guarantee that holds.

38.7 Train == serve, by construction

The same as_of_in_degree definition, run against a live server over the same inputs, returns the same feature for every paper — one definition on both paths, so there is no skew to measure.

from jammi.testing import LiveServer

with LiveServer(tempfile.mkdtemp()) as server, jammi.connect(server.endpoint) as remote:
    _, served = as_of_in_degree(remote)
print(f"papers whose served feature differs from the trained one: "
      f"{sum(served[p] != known[p] for p in ids)}")
papers whose served feature differs from the trained one: 0
claim("the served feature equals the trained one for every paper", served == known)
✓ the served feature equals the trained one for every paper

38.8 The artifact knows what it is — the verdicts

verify_materialization recomputes a materialized table’s digest against its materialization manifest and returns a verdict. It is read-only — it attests, it never acts.

print(f"the as-of training set:        {db.verify_materialization(asof_table)['verdict']}")
print(f"  unpinned inputs named:       {db.verify_materialization(asof_table).get('unpinned')}")
the as-of training set:        match_with_unpinned_inputs
  unpinned inputs named:       ['labels', 'in_degree']

The as-of training set verifies as match_with_unpinned_inputs: its inputs are registered files, which have no version surface, so the engine can attest the artifact but not that re-running would read the same input bytes — and it names the inputs it cannot pin rather than claiming a guarantee it cannot keep.

A table whose every input is itself a result table verifies as a clean match: its inputs are anchored by their content digests. A neighbour graph built over an embedding table is one:

docs = tempfile.mkdtemp()
pq.write_table(pa.table({
    "_row_id": ["d0", "d1", "d2", "d3"],
    "text": ["graph signal processing", "node embeddings for citation networks",
             "spectral kernels and the laplacian", "conformal prediction under shift"],
}), f"{docs}/docs.parquet")
db.add_source("docs", url=f"{docs}/docs.parquet", format="parquet")
db.generate_embeddings(source="docs", model=fixtures.model("tiny_bert"), columns=["text"],
                       key="_row_id")
graph = db.build_neighbor_graph("docs", k=2, exact=True)
manifest = db.describe_table(graph)
verdicts = {
    "match": db.verify_materialization(graph)["verdict"],
    "match (expected definition)": db.verify_materialization(
        graph, expected_definition=manifest["definition_hash"])["verdict"],
    "mismatch (another definition)": db.verify_materialization(
        graph, expected_definition="0" * len(manifest["definition_hash"]))["verdict"],
}
for case, verdict in verdicts.items():
    print(f"{case:<32} {verdict}")
print(f"input anchors: {[a['kind'] for a in manifest['input_anchors']]}")
match                            match
match (expected definition)      match
mismatch (another definition)    mismatch
input anchors: ['result_digest']
2026-10-03T07:42:31.277502Z  WARN jammi_kernels::admission: fused-kernel domain check failed; falling back to the eager composition op="attention_block_fused" predicate="head_dim_is_attention_block_fixed_head_dim"
claim("verify_materialization tells a match from a mismatch",
      verdicts == {"match": "match", "match (expected definition)": "match",
                   "mismatch (another definition)": "mismatch"})
claim("and reports an as-of table whose inputs were not pinned",
      db.verify_materialization(asof_table)["verdict"] == "match_with_unpinned_inputs")
✓ verify_materialization tells a match from a mismatch
✓ and reports an as-of table whose inputs were not pinned

A mismatch says the served artifact is not the output of the expected definition — a stale copy, or a changed producing query, is detectable, and the verdict carries both hashes. And a table with no manifest at all verifies as missing_manifest, a truthful “unknown” rather than a fabricated match.

db.close()

38.9 The honest limit

This chapter shows the primitive composing into a leakage-free, skew-free training surface. It does not serve those features from a low-latency online tier behind auth with a live coverage SLA; carrying the materialization contract across that boundary so an online read can assert “what I serve matches what trained this, as of \(T\)” is a production online-serving concern, not something this engine cookbook covers. The seam — verify_materialization returning a verdict — is here; the boundary that acts on the verdict is the consumer’s to build.

Why the as-of join is the feature store. A plain JOIN federates current-state features (Orr et al. 2021) — the easy half, which the feature-store chapter covers. The hard half, the half that makes the result trustworthy, is matching each label to the feature value as it was known at the label’s instant (Snodgrass 1999). That is one verb, asof_join, and its leakage-free output is verifiable, by another, verify_materialization. The measured lesson: the leak is real (a strictly positive AUC inflation and a broken coverage guarantee), and the as-of join closes it — with zero train/serve skew, because one definition runs both paths. ```

Barber, Rina Foygel, Emmanuel J. Candès, Aaditya Ramdas, and Ryan J. Tibshirani. 2023. “Conformal Prediction Beyond Exchangeability.” The Annals of Statistics 51 (2): 816–45.
Kaufman, Shachar, Saharon Rosset, Claudia Perlich, and Ori Stitelman. 2012. “Leakage in Data Mining: Formulation, Detection, and Avoidance.” ACM Transactions on Knowledge Discovery from Data 6 (4): 1–21.
Orr, Laurel, Atindriyo Sanyal, Xiao Ling, Karan Goel, and Megan Leszczynski. 2021. “Managing ML Pipelines: Feature Stores and the Coming Wave of Embedding Ecosystems.” In Proceedings of the VLDB Endowment, 14:3178–81. 12.
Snodgrass, Richard T. 1999. Developing Time-Oriented Database Applications in SQL. The Morgan Kaufmann Series in Data Management Systems. Morgan Kaufmann.