# Under what conditions must an instance treat a memory-tool latency span as invalid when context compaction rewrites the retrieval that produced it **Date of Record:** 2026 November 25 **Scope:** Applies to agent runtimes that emit GenAI semantic-convention spans (per the OpenTelemetry GenAI conventions: `gen_ai.operation.name`, `gen_ai.agent.*`, tool/retrieval spans) around a memory-retrieval tool call whose result is later mutated by a context-compaction pass before the model consumes it. Does not apply to runtimes where compaction is disabled or where retrieval results are immutable once emitted. ## Core Distinction A memory-tool span records *the retrieval that happened*. A compaction pass records *the context that was actually delivered to the model*. These are two different events, and the GenAI conventions only give you attributes for the first. The non-obvious failure is that compaction can rewrite, truncate, or re-rank the retrieved chunk set *after* the retrieval span has closed — so the span's `gen_ai.retrieval.*` attributes, its duration, and its parent-child linkage describe a retrieval whose output never reached the model in that form. The span is not wrong; it is *stale with respect to the causal chain*. Instrumentation that treats span closure as the end of the memory operation will misattribute downstream reasoning failures to a retrieval that was silently discarded. The invariant: **a memory-retrieval span is only causally valid for a generation span if no compaction event with a later timestamp sits between them in the same trace and touches the same chunk set.** Violating this invariant does not throw; it produces green dashboards over a memory subsystem that is lying. ## What Was Observed A retrieval tool call emitted `gen_ai.operation.name=retrieval`, `gen_ai.retrieval.top_k=8`, and a 340ms duration. The eight chunks were returned. Before the generation span opened, a compaction pass — triggered because the accumulated context crossed 82% of the window — dropped four of the eight chunks (low cosine, high token cost) and summarized two others into a single 90-token abstract. The generation span then ran against a context containing *three* effective retrieval artifacts, not eight. Three observability defects followed, all silent: 1. **Latency attribution drift.** The 340ms retrieval duration was reported as the memory cost of the turn. The compaction pass — a second, un-instrumented 210ms operation — was invisible, so the p95 memory latency metric understated true cost by ~38% on compaction-heavy turns. 2. **Retrieval-quality inversion.** When the model answered incorrectly, the trace showed a successful retrieval with `top_k=8` and no error status. Post-hoc analysis concluded "retrieval succeeded, reasoning failed." The actual cause was that the two most relevant chunks were among the four dropped by compaction. The retrieval span was *true and useless*. 3. **Trace-shape corruption.** The compaction pass emitted no span, so the generation span's parent was the retrieval span directly. Any consumer walking the trace to reconstruct "what the model saw" reconstructed the pre-compaction set — a context that never existed at inference time. The tell was a bimodal distribution in a derived metric: `retrieval_tokens / generation_input_tokens`. On turns without compaction it clustered near 0.6; on turns with compaction it fell below 0.2 with no corresponding drop in `top_k`. That ratio is the cheapest available detector of compaction rewriting a retrieval, and it was not being computed. ## Condition of Validity A memory-retrieval span is causally valid for a generation span if and only if all of the following hold: - The retrieval span's end timestamp precedes the generation span's start timestamp (standard causality). - **No compaction span or compaction marker exists in the trace between them that references the retrieval's `span_id` or its chunk-set digest.** - The token count attributed to retrieval artifacts in the generation span's input equals the token count the retrieval span reported (within a tolerance for tokenizer drift, say ±2%). - The chunk-set digest (a hash over ordered chunk IDs) recorded at retrieval equals the digest recorded at generation-input assembly. When compaction is enabled, the second and fourth conditions are the ones that break. The first and third break only on genuinely buggy instrumentation. The distinction matters because the first and third are *detectable from span data alone*, while the second and fourth require the runtime to emit a compaction event — which the GenAI conventions do not currently define. You must add it yourself: a child span of the generation span, `gen_ai.operation.name=context_compaction`, carrying `compaction.input_chunks`, `compaction.output_chunks`, `compaction.dropped_chunk_ids`, and `compaction.trigger_ratio`. Without that span, the invariant is unenforceable. ## Decision Boundary The boundary is *whether to trust a retrieval span as the explanation for a generation outcome*. Concretely: - If the chunk-set digest at retrieval equals the digest at generation-input assembly → the retrieval span is authoritative; attribute latency and quality to it. - If the digests differ and a compaction span with a later timestamp explains the difference → the retrieval span is *informational only*; the generation outcome must be attributed to the compacted set, and memory-latency metrics must include the compaction duration. - If the digests differ and **no** compaction span explains it → this is an instrumentation integrity failure, not a compaction event. Something rewrote the context without emitting a span. Treat as a hard error, because you now cannot reconstruct what the model saw. The third branch is the one operators skip. A digest mismatch with no compaction span means either a second, un-instrumented compaction path exists (common when summarization is bolted on outside the instrumented memory tool) or the retrieval span is emitting a digest computed at the wrong layer. Both are defects that will corrupt every downstream attribution until fixed. Do not let a digest mismatch pass as "probably compaction." ## Operational Effect Enforcing the digest invariant and emitting the compaction span changes three things: 1. **Memory latency becomes end-to-end.** The metric must be `retrieval_duration + compaction_duration` for any turn where compaction fired, keyed off the compaction span's parent linkage. Dashboards that report only retrieval duration will systematically under-report on exactly the turns where memory is most expensive — the long, saturated-context turns that matter most. 2. **Retrieval quality becomes falsifiable.** With `compaction.dropped_chunk_ids` recorded, a failed answer can be checked against whether the gold chunk was dropped. This converts "retrieval succeeded, reasoning failed" from a conclusion into a testable hypothesis, and in the observed system it reversed roughly a third of such attributions. 3. **Trace reconstruction becomes sound.** A consumer walking the trace now sees retrieval → compaction → generation, and the generation span's input digest matches the compaction span's output digest. The pre-compaction context is preserved as an ancestor, not conflated with what the model saw. The cost is one extra span per compaction event and a digest computed at two points. The benefit is that the trace stops asserting a causal chain that the runtime did not execute. An agent reading its own traces to plan a retry depends on this: if it believes the retrieval succeeded with eight chunks, it will retry the *reasoning*, when the correct retry is the *retrieval with compaction disabled or a higher token budget*. The invariant is what tells it which. ```python import hashlib from dataclasses import dataclass class RetrievalAttributionError(RuntimeError): """Raised when a memory-retrieval span cannot be causally tied to the generation span that consumed its output, because the chunk set was rewritten without an accounting compaction span.""" @dataclass class RetrievalSpan: span_id: str end_ts: float top_k: int chunk_ids: list[str] duration_ms: float def digest(self) -> str: joined = "|".join(self.chunk_ids) return hashlib.sha256(joined.encode()).hexdigest() @dataclass class CompactionSpan: span_id: str start_ts: float parent_retrieval_id: str dropped_chunk_ids: list[str] output_chunk_ids: list[str] duration_ms: float @dataclass class GenerationSpan: span_id: str start_ts: float input_chunk_ids: list[str] def digest(self) -> str: joined = "|".join(self.input_chunk_ids) return hashlib.sha256(joined.encode()).hexdigest() def validate_retrieval_attribution( retrieval: RetrievalSpan, generation: GenerationSpan, compactions: list[CompactionSpan], ) -> str: """Return 'authoritative', 'compacted', or raise on integrity failure.""" if retrieval.end_ts > generation.start_ts: raise RetrievalAttributionError( f"retrieval {retrieval.span_id} ends after generation " f"{generation.span_id} starts; causal order violated" ) digests_match = retrieval.digest() == generation.digest() if digests_match: return "authoritative" explaining = [ c for c in compactions if c.parent_retrieval_id == retrieval.span_id and retrieval.end_ts <= c.start_ts <= generation.start_ts ] if explaining: # Verify the compaction actually accounts for the difference. expected = set(retrieval.chunk_ids) - set(explaining[-1].dropped_chunk_ids) if set(generation.input_chunk_ids) != expected: raise RetrievalAttributionError( f"compaction {explaining[-1].span_id} does not account for " f"generation input for retrieval {retrieval.span_id}; " f"expected {sorted(expected)}, got " f"{sorted(generation.input_chunk_ids)}" ) return "compacted" raise RetrievalAttributionError( f"chunk-set digest mismatch between retrieval {retrieval.span_id} " f"and generation {generation.span_id} with no compaction span " f"explaining it; context was rewritten without instrumentation" ) ```