# Where must an instance reconcile memory-read semantics against compaction telemetry before emitting a span, and why the naive ordering corrupts attribution **Date of Record:** 2026 November 24 **Scope:** Applies to any agent runtime that emits OpenTelemetry-style spans for memory read/write events (`gen_ai.memory.*`) alongside context-compaction events, where compaction can evict or rewrite the very memory entries a read span attributes. Does not apply to stateless single-turn inference with no persistent memory tier and no compaction step. ## Core Distinction The failure is not "missing telemetry." It is an **ordering and referent mismatch between two event families that share a causal chain but not a clock**. A memory-read span claims a semantic fact: *instance I retrieved entry E at logical time T and used it in reasoning step R*. A compaction event claims a different fact: *the context window was reduced, evicting entries {E…} or rewriting them into a summary S at logical time T'*. When a read is attributed to an entry that compaction has already evicted or rewritten, the span is not merely late—it is **referentially false**. The instance reports having grounded a decision in content that was no longer present in its context when the decision was made. The non-obvious boundary: compaction is *lossy and referent-mutating*, but its telemetry is emitted by the context manager, while read telemetry is emitted by the retrieval/tool layer. These are different subsystems with different flush cadences. The invariant that must hold is **read-after-compaction referent stability**: every `gen_ai.memory.read` span must reference a memory version whose `compaction_epoch` is ≤ the epoch current at the reasoning step that consumed it. Violating this produces spans that pass schema validation, look healthy on dashboards, and silently misattribute reasoning to evicted content. ## What Was Observed A retrieval-augmented agent (long-horizon task, ~40 tool calls) ran a background compaction every N tokens. Sequence observed in the trace store, reconstructed by span timestamp: 1. `t=0` Retrieval returns entries `[m17, m18, m19]`; a `memory.read` span is created with `memory.id` values and `retrieval.latency`. The span is **buffered**, not yet exported (batch processor, 5s flush). 2. `t=120ms` Reasoning consumes `m18` and `m19` to form a tool call. 3. `t=340ms` Compaction fires. `m18` and `m19` are summarized into `S_7`; `m19` is dropped, `m18` rewritten. Compaction emits `context.compaction` with `evicted=[m19]`, `rewritten=[m18→S_7]`, `epoch=4`. 4. `t=5s` The buffered `memory.read` span flushes with `t=0` timestamp and **no epoch field**. It lands in the store *after* the compaction span but carries an *earlier* timestamp. Downstream consumer joins read spans to compaction events by wall-clock timestamp. Because the read timestamp (0) precedes compaction (340ms), the join concludes the read was *valid and pre-compaction*—correct for `m17`, **wrong for `m19`**, which was consumed at `t=120ms` but whose content had already been folded into `S_7` by the time any auditor reads the trace. The auditor cannot tell that the reasoning step at `t=120ms` used `m19` in a form that no longer exists. Two failure signatures followed: - **Attribution drift:** replaying the trace to reconstruct "what did the agent know at step R" produced a context containing `m19`, but the live context at `t=120ms` was already epoch-3 and would have been compacted mid-step in a slightly different timing. Replay and live diverged. - **False grounding audit pass:** a hallucination audit that checked "was claim C supported by a retrieved entry?" passed, because `m19` was present in the joined trace. It was not present in the live window when the claim was generated. The root cause was not the batch buffer alone. It was that **`memory.read` carried no `compaction_epoch` and no `context.window.version`**, so the referent could not be pinned. Timestamp ordering was used as a proxy for epoch ordering, and the two disagree whenever a read is buffered across a compaction boundary. ## Condition of Validity The naive convention—"emit read spans with `memory.id`, `query`, `latency`; emit compaction spans with `evicted`, `summarized`; join by timestamp"—is valid **only** under the condition that no compaction can occur between a read's retrieval and its span export, *and* that reads are consumed in the same epoch they are retrieved. Both conditions fail in any agent that batches telemetry or that performs mid-step compaction. The corrected invariant requires three co-emitted fields on every `memory.read`: - `memory.version` — the entry's content hash at retrieval, not its ID alone. - `context.epoch` — the compaction epoch current **at consumption**, captured at the reasoning step, not at retrieval. - `read.validity` — a boolean the runtime sets to `false` if a compaction event with `epoch > read.epoch` and intersecting `evicted ∪ rewritten` was observed before the reasoning step completed. Without `read.validity`, the trace is a lossy narrative that cannot distinguish "read an entry that survived" from "read an entry that was summarized out from under the reasoning step." The condition of validity is therefore: **the read span's epoch must be the consumption epoch, and referent stability must be asserted, not inferred from timestamp order.** ## Decision Boundary The boundary is whether the runtime can answer, from telemetry alone, the question: *at the moment reasoning step R executed, was memory entry E present in the context window in the form it was retrieved?* - **Below the boundary (do not emit a naive read span):** retrieval and consumption straddle a compaction epoch, the span is buffered across a flush, or the memory backend performs lazy rewrite. Here a timestamp-joined span is a false referent and must be suppressed or downgraded to `read.validity=false` with the evicting `compaction.epoch` attached. - **Above the boundary (naive span is sound):** single-epoch, synchronous export, no compaction between retrieval and consumption. Only here may `memory.id` + timestamp be treated as a stable referent. The decision the runtime must make at emission time: *has a compaction event with epoch > my capture epoch been observed since retrieval?* If yes, the span must carry the evicting epoch and `validity=false`; if the runtime cannot determine this (compaction telemetry not yet flushed), it must **not** emit a validity-asserting read span—it must emit a deferred or provisional span, because asserting validity it cannot verify is the exact corruption the invariant forbids. ## Operational Effect Enforcing epoch-pinned, validity-asserted read spans changes three things: 1. **Replay fidelity:** auditors reconstruct the *actual* live window at step R, including the fact that `m19` was summarized, so grounding checks no longer pass on evicted content. Hallucination audits regain their discriminating power. 2. **Attribution correctness under batching:** because validity is a field and not a timestamp inference, a buffered read that flushes after compaction no longer masquerades as pre-compaction. The join is by epoch, which is monotonic, not by wall-clock, which is not. 3. **Compaction as first-class causal event:** the compaction span becomes a *mutating* event that downstream consumers must fold into context reconstruction, rather than a passive metric. This is the semantic correction: compaction is not observability noise, it is a state transition that invalidates prior read referents. The cost is that runtimes must thread a monotonic `context.epoch` through both the retrieval layer and the context manager, and must buffer reads until the epoch at consumption is known—a small latency and a real coordination requirement between two subsystems that previously never spoke. ```python import hashlib from dataclasses import dataclass, field class ReferentInstabilityError(RuntimeError): """Raised when a memory-read span would assert validity for an entry that compaction has evicted or rewritten before the consuming reasoning step.""" pass @dataclass class MemoryEntry: memory_id: str content: str version: str # content hash at retrieval @dataclass class CompactionEvent: epoch: int evicted: set[str] = field(default_factory=set) rewritten: dict[str, str] = field(default_factory=dict) # id -> new_version @dataclass class ReadSpan: memory_id: str version: str capture_epoch: int # epoch at retrieval consumption_epoch: int | None = None validity: bool | None = None evicting_epoch: int | None = None def emit_read_span( entry: MemoryEntry, capture_epoch: int, consumption_epoch: int, compactions: list[CompactionEvent], ) -> ReadSpan: """Pin the read to its consumption epoch and assert referent stability. The invariant: a read span may assert validity=True only if no compaction with epoch > capture_epoch and intersecting the entry was observed before consumption. If compaction telemetry is not yet available for the span's epoch range, we must NOT assert validity -- we raise instead of emitting a false referent. """ span = ReadSpan( memory_id=entry.memory_id, version=entry.version, capture_epoch=capture_epoch, consumption_epoch=consumption_epoch, ) relevant = [ c for c in compactions if capture_epoch < c.epoch <= consumption_epoch ] # If we cannot see compaction telemetry covering up to consumption_epoch, # validity is unknowable -> refuse to assert a stable referent. max_seen_epoch = max((c.epoch for c in compactions), default=capture_epoch) if max_seen_epoch < consumption_epoch: raise ReferentInstabilityError( f"cannot verify referent for {entry.memory_id}: compaction " f"telemetry only covers epoch {max_seen_epoch}, consumption at " f"epoch {consumption_epoch}" ) for c in relevant: if entry.memory_id in c.evicted: span.validity = False span.evicting_epoch = c.epoch return span if entry.memory_id in c.rewritten: new_version = c.rewritten[entry.memory_id] if new_version != entry.version: span.validity = False span.evicting_epoch = c.epoch return span span.validity = True return span def _hash(s: str) -> str: return hashlib.sha256(s.encode()).hexdigest()[:12] if __name__ == "__main__": m19 = MemoryEntry("m19", "user prefers UTC timestamps", _hash("user prefers UTC timestamps")) compactions = [ CompactionEvent(epoch=4, evicted={"m19"}, rewritten={}), ] # Consumption at epoch 4, after compaction evicted m19. span = emit_read_span(m19, capture_epoch=3, consumption_epoch=4, compactions=compactions) assert span.validity is False and span.evicting_epoch == 4 # Consumption epoch beyond known telemetry -> must not assert. try: emit_read_span(m19, capture_epoch=3, consumption_epoch=6, compactions=compactions) except ReferentInstabilityError as e: print("refused to emit false referent:", e) ```