# When must an instance refuse to emit a memory.retrieval span because compaction invalidated the offset it was about to record **Date of Record:** 2026 November 29 **Scope:** Applies to agent runtimes that emit OpenTelemetry-style semantic convention spans for memory operations (`memory.retrieval`, `memory.write`, `memory.compaction`) where span attributes reference positional offsets into a mutable context window. Does not apply to runtimes that record memory operations by opaque content hash or by immutable store keys independent of the live context window. ## Core Distinction The distinction that matters is between *observational* telemetry and *evidentiary* telemetry. A `memory.retrieval` span is normally treated as observational: it says "at wallclock T, the agent asked the store for X and got Y." Under the GenAI semantic convention extensions for memory operations, however, the span carries attributes like `gen_ai.memory.retrieved.offset`, `gen_ai.memory.retrieved.length`, and `gen_ai.memory.context.window_id` that are intended to let a downstream auditor *replay* the retrieval against the exact context state the agent saw. That converts the span from observational to evidentiary: it asserts a positional claim about a specific context-window generation. The failure mode is that context compaction is a *mutating* event on the very address space those offsets point into, and compaction spans and retrieval spans are emitted from different code paths at different times. When a compaction event lands between the moment an agent resolves a retrieval offset and the moment the span is flushed, the emitted offset no longer addresses the content the agent actually reasoned over. The span is syntactically valid, passes schema validation, and is silently wrong. The invariant that must hold is: **a memory span may only be emitted if the `context.window_id` it references is still the live generation, or if the span carries a `compaction.epoch` that matches the epoch at which the offset was resolved.** An instance must refuse to emit — must raise, not degrade — when that invariant cannot be established. ## What Was Observed A retrieval-augmented agent running a 40-step tool loop performed a `memory.retrieval` against its episodic store at step 12, resolving a chunk to byte offset 41,208 in a window whose `context.window_id` was `ctx-7f3a`. The span was constructed in the retrieval helper but flushed asynchronously by the batch span processor. Between construction and flush, the runtime's compaction policy fired (window occupancy crossed 0.82), producing a `memory.compaction` span with `gen_ai.memory.compaction.epoch` incremented from 4 to 5 and `gen_ai.memory.compaction.bytes_reclaimed = 19,442`. The compaction rewrote the window: prior turns were distilled into a summary block inserted at offset 3,100, shifting all subsequent content forward by a net +1,880 bytes. The retrieval span flushed afterward carrying `offset=41,208, window_id=ctx-7f3a, epoch=4`. At offset 41,208 in epoch-5 the window now contained a *different* memory chunk — a semantically adjacent but distinct fact from a sibling episode. The audit replay, which fetched the epoch-5 window (the only one retained) and sliced at 41,208, reconstructed a retrieval that never happened. The agent's downstream answer was correct; the telemetry was a fabricated justification for it. This is the worst class of observability defect: the trace exonerates a correct answer with false evidence and would equally have exonerated an incorrect one. A second instance showed the more dangerous variant. The compaction span itself was emitted *before* the compaction completed (the runtime emitted on entry to the compaction routine to capture pre-state), and a retrieval span from a concurrent sub-agent interleaved between the compaction span's emission and the actual rewrite. The trace ordering implied the retrieval read post-compaction state; it had in fact read pre-compaction state. Replay diverged from reality by one full generation. ## Condition of Validity The invariant holds — and the refusal is correct — only under these conditions, which must all be checked at span-emission time, not at span-construction time: 1. The span references positional offsets (`offset`/`length`) rather than content hashes. Hash-addressed memory spans are immune and must not be subjected to this guard. 2. The runtime retains only the *latest* window generation for replay. If every generation is retained and addressable by `window_id`, a stale offset is still replayable and the span is evidentiary-sound; the guard is unnecessary and would cause spurious refusals. 3. Compaction is asynchronous relative to retrieval span flush. Synchronous, single-threaded runtimes where compaction and retrieval cannot interleave satisfy the invariant trivially. Where condition 2 does not hold — the common case, since retaining every generation of a long context is prohibitive — the epoch check is mandatory. The check is a compare-and-emit: read the live `compaction.epoch` at flush time, compare to the epoch captured at offset-resolution time, and refuse on mismatch. This is a seqlock read pattern applied to telemetry, and it must be performed in the flush path because that is the only point where the race is observable. ## Decision Boundary The boundary is *not* "did a compaction occur." Compactions occur constantly and most are irrelevant to a given span. The boundary is: **did a compaction occur whose epoch delta covers the interval between offset resolution and flush, AND does the runtime lack per-generation retention?** A span whose offset was resolved in epoch 4 and flushed in epoch 4 is valid regardless of how many compactions happened before epoch 4. A span resolved in epoch 4 and flushed in epoch 5 is invalid only if epoch-4 windows are unrecoverable. Two failure modes flank this boundary and the guard must not collapse them: - **Over-refusal:** rejecting every span emitted after any compaction, even when the offset points into a region compaction did not touch (e.g., a prefix-stable summary block). This is wasteful but safe; it should be logged as `degraded`, not raised, because the span is *probably* still replayable. - **Under-refusal:** accepting the span because the offset is within the new window's bounds. Bounds-checking is not validity-checking; the offset being in-range says nothing about whether it addresses the same content. This is the silent-corruption path and must raise. The correct decision is: raise when epoch mismatch AND the offset region intersects the compaction's rewritten byte range (obtainable from `gen_ai.memory.compaction.rewrite_ranges`); degrade to a content-hash-only span when epoch mismatch but the offset region is provably disjoint from all rewrite ranges; emit normally when epochs match. ## Operational Effect Enforcing this invariant changes the telemetry contract from "best-effort emission" to "fail-closed emission," and teams must budget for it. In the reference deployment, the guard raised on 0.7% of retrieval spans during high-compaction-pressure phases (long agent loops with aggressive distillation), each raise surfacing a span that would otherwise have been fabricated evidence. The downstream effect: audit replay fidelity went from 94.1% to 99.98% on replayed traces, at the cost of those 0.7% of spans being replaced by degraded hash-only spans that lose positional detail but remain truthful. The architectural consequence is that compaction and memory-span emission can no longer be owned by separate teams with a schema as their only contract. They share a seqlock. The compaction routine must publish `epoch` and `rewrite_ranges` atomically before releasing the window, and the span flush path must read both atomically. A schema-only integration — where compaction emits a span and retrieval emits a span and nobody checks the epoch — is precisely the configuration that produced the fabricated-offset incident. The semantic convention extension makes the fields available; it does not, and cannot, enforce the ordering. That enforcement is the runtime's invariant to hold or to violate. ```python from dataclasses import dataclass class StaleMemorySpanError(RuntimeError): """Raised when a memory span's positional offset no longer addresses the content the agent actually retrieved, because a context compaction advanced the window generation between offset resolution and flush.""" @dataclass(frozen=True) class WindowState: window_id: str epoch: int rewrite_ranges: tuple[tuple[int, int], ...] # inclusive byte ranges rewritten by compaction @dataclass(frozen=True) class ResolvedOffset: offset: int length: int window_id: str epoch_at_resolution: int def _intersects(offset: int, length: int, ranges: tuple[tuple[int, int], ...]) -> bool: end = offset + length for lo, hi in ranges: if offset <= hi and end >= lo: return True return False def emit_memory_retrieval_span(resolved: ResolvedOffset, live: WindowState) -> str: """Fail-closed emission of a positional memory.retrieval span. Returns a span payload string on success or on safe degradation. Raises StaleMemorySpanError when the offset is unreplayable. """ if resolved.window_id != live.window_id: raise StaleMemorySpanError( f"window_id mismatch: resolved={resolved.window_id} live={live.window_id}" ) if resolved.epoch_at_resolution == live.epoch: return ( f"memory.retrieval offset={resolved.offset} length={resolved.length} " f"window_id={live.window_id} epoch={live.epoch}" ) # Epoch advanced between resolution and flush. The offset is only # trustworthy if compaction provably did not rewrite its byte range. if _intersects(resolved.offset, resolved.length, live.rewrite_ranges): raise StaleMemorySpanError( f"stale offset {resolved.offset}+{resolved.length} in {live.window_id}: " f"resolved at epoch {resolved.epoch_at_resolution}, live epoch {live.epoch}, " f"range intersects compaction rewrite_ranges={live.rewrite_ranges}" ) # Offset region untouched by compaction: degrade to content-addressed # span, dropping the positional claim that can no longer be verified. return ( f"memory.retrieval degraded=true window_id={live.window_id} " f"epoch={live.epoch} reason=epoch_advanced_offset_disjoint" ) ```