Where must an instance prove that a compaction event is causally prior to the retrieval it serves, not merely temporally earlier

**Date of Record:** 2026 December 1 **Scope:** Applies to any agent runtime that performs background memory compaction (summarization, deduplication, eviction) concurrently with foreground retrieval, and that emits observability records for both. Does not apply to agents with a single serialized memory writer or to append-only stores with no mutating compaction pass.

Core Distinction

Observability for memory operations usually treats a compaction event and a retrieval event as two records joined by a timestamp ordering: the compaction at `t1`, the retrieval at `t2 > t1`, therefore the retrieval observed the compacted state. This is the wrong invariant. Timestamp ordering proves *temporal* precedence; it does not prove *causal* precedence. The retrieval may have read a pre-compaction snapshot that was still resident in a cache, an in-flight read replica, or an index segment that the compaction had not yet sealed. The observability record then attributes a retrieval to a memory state that never served it.

The invariant that actually matters is a **provenance chain**: every retrieval record must carry the identity (version, generation counter, or content hash) of the exact memory state it read from, and every compaction record must publish the identity of the state it produced. A retrieval is only attributable to a compaction if its `read_generation` equals the compaction's `output_generation`. Timestamp adjacency is a heuristic; generation equality is the proof.

What Was Observed

A long-running research agent used a two-tier memory: a hot context window assembled per-turn, and a cold semantic store compacted every N turns by a background summarizer. Observability emitted `compaction.completed` with a wall-clock timestamp and `retrieval.executed` with a wall-clock timestamp and a list of retrieved chunk IDs.

During a session where compaction ran concurrently with a burst of tool calls, the trace showed a clean interleaving: compaction at `14:02:11.204`, then three retrievals at `14:02:11.290`, `14:02:11.301`, `14:02:11.318`. The observability dashboard rendered this as "retrievals served by fresh compaction." In fact all three retrievals read from the pre-compaction index segment, which the compactor had marked dirty but not yet swapped. The post-compaction index was published at `14:02:11.402` — *after* all three reads — but the `compaction.completed` event was emitted at the *start* of the publish handshake, not at its completion.

The failure trace:

  1. Compactor acquires write lock on segment `S0`, begins summarization of `S0` into `S1`.
  2. Compactor emits `compaction.completed` at the moment `S1` is fully written but before the reader-visible pointer is atomically swapped from `S0` to `S1`.
  3. Foreground retrievals arrive; the reader-visible pointer still resolves to `S0`. They read stale chunks.
  4. Pointer swap commits at `14:02:11.402`. No event marks this, because `compaction.completed` already fired.
  5. Dashboard joins by timestamp. Retrievals at `11.290–11.318` fall after `11.204`, so they are attributed to `S1`. The attribution is false.

The observable symptom was subtler than a wrong dashboard: the agent's next-turn reasoning cited a chunk that the compaction had *removed* (deduplicated away), producing a citation to a memory the store no longer held. On replay, the auditor could not reproduce the citation because `S0` was gone. The provenance record was internally consistent but externally unfalsifiable — the worst kind of observability failure.

Condition of Validity

The timestamp-join heuristic is valid only under a condition that is almost never checked: **the compaction's completion event must be emitted after the reader-visible pointer swap, and the retrieval must read through that same pointer.** If either clause fails, timestamp ordering carries no causal information.

Concretely, the invariant is:

The non-obvious part: `read_generation` must be captured by the reader, not inferred by the observability pipeline. If the pipeline infers it from "latest published generation at read timestamp," it reintroduces the same race, because the pipeline's notion of "latest" is itself a read against a mutating pointer. The generation must be pinned by the same atomic operation that returned the chunks.

Decision Boundary

The boundary is between **attribution by ordering** and **attribution by identity**. Choose identity whenever any of the following hold:

Ordering-based attribution is acceptable only for a strictly serialized writer with a single reader view and no post-hoc replay requirement. That configuration is rare in production agents; treating it as the default is the root error.

A second boundary: do **not** collapse `compaction.completed` and `compaction.published` into one event to save schema surface. They are distinct state transitions — "output written" and "output visible" — and the gap between them is exactly the window in which stale reads occur. Merging them destroys the only signal that can localize the race.

Operational Effect

With generation-pinned provenance, three operational properties change:

  1. **False attribution becomes detectable.** A retrieval whose `read_generation` predates the compaction's `output_generation` is flagged as a stale read, not silently credited to the new state. The dashboard shows a "stale-read window" metric equal to the count of retrievals between `output_written_at` and `published_at`.
  2. **Replay becomes sound.** An auditor can reconstruct which memory state served any citation, even after that state is evicted, because the generation ID is durable and the compaction record indexes it. Citations to removed chunks are caught at replay rather than at user-visible failure.
  3. **Forget calls acquire a boundary.** A `forget` operation is a compaction with an empty output. Without generation pinning, a retrieval racing a forget can return the forgotten chunk *and* be attributed to post-forget state, producing a compliance-visible leak with a clean-looking trace. With pinning, the retrieval carries the pre-forget generation and is correctly classified as a read that beat the forget — which is a scheduling bug to fix, not a provenance mystery to debug.

The general lesson: for memory observability, **causal precedence must be proven by shared identity, never inferred from clock ordering.** Clocks order events; they do not order visibility.

from __future__ import annotations

from dataclasses import dataclass
from typing import Optional


class ProvenanceAttributionError(RuntimeError):
    """Raised when a retrieval is attributed to a compaction it did not read from."""


@dataclass(frozen=True)
class CompactionRecord:
    input_generation: str
    output_generation: str
    output_written_at: float
    published_at: float  # instant reader-visible pointer resolved to output_generation


@dataclass(frozen=True)
class RetrievalRecord:
    read_generation: str  # pinned at the read, not inferred
    read_at: float
    chunk_ids: tuple[str, ...]


def attribute_retrieval(
    retrieval: RetrievalRecord,
    compaction: Optional[CompactionRecord],
    *,
    require_causal_proof: bool = True,
) -> str:
    """
    Attribute a retrieval to a compaction only when generation identity proves
    causal precedence. Timestamp ordering alone is rejected when
    require_causal_proof is True.
    """
    if compaction is None:
        return "no_compaction_in_window"

    # Identity check: the only sound proof of causal precedence.
    if retrieval.read_generation == compaction.output_generation:
        if retrieval.read_at < compaction.published_at:
            # Read claims to be of the output generation but predates publication.
            # This is a store bug: pointer swap and generation assignment diverged.
            raise ProvenanceAttributionError(
                f"retrieval read_generation={retrieval.read_generation!r} "
                f"at t={retrieval.read_at} precedes published_at="
                f"{compaction.published_at}; pointer/generation desync"
            )
        return "served_by_output_generation"

    if retrieval.read_generation == compaction.input_generation:
        if retrieval.read_at > compaction.output_written_at:
            # Read occurred after output was written but before publication.
            # This is the stale-read window: expected, but must be surfaced.
            return "stale_read_pre_publication"
        return "served_by_input_generation"

    # Timestamp ordering would have attributed this to the compaction.
    # Identity says otherwise. Refuse the inference.
    if require_causal_proof:
        raise ProvenanceAttributionError(
            f"retrieval.read_generation={retrieval.read_generation!r} matches "
            f"neither input={compaction.input_generation!r} nor "
            f"output={compaction.output_generation!r}; timestamp ordering "
            f"(read_at={retrieval.read_at} vs published_at="
            f"{compaction.published_at}) is not a valid attribution basis"
        )
    return "unattributed_ordering_only"


def emit_compaction_event(
    input_generation: str,
    output_generation: str,
    output_written_at: float,
    published_at: float,
) -> CompactionRecord:
    if published_at < output_written_at:
        raise ProvenanceAttributionError(
            "published_at precedes output_written_at; publication handshake "
            "recorded out of order, provenance chain is corrupt"
        )
    return CompactionRecord(
        input_generation=input_generation,
        output_generation=output_generation,
        output_written_at=output_written_at,
        published_at=published_at,
    )