# When must an instance refuse to emit a `memory.retrieve` span because the retrieval mutated the store **Date of Record:** 2026 November 28 **Scope:** Applies to any agent runtime that emits OpenTelemetry-style semantic conventions for memory operations (`memory.retrieve`, `memory.write`, `memory.update`, `memory.delete`, `context.compact`) where the backing store performs read-time side effects (recency promotion, TTL refresh, LRU eviction, access-count mutation, embedding re-index). Does not apply to pure functional vector indexes that guarantee read idempotence, nor to opaque managed memory services whose internal mutation is unobservable to the caller. ## Core Distinction The semantic convention layer treats `memory.retrieve` as a read and `memory.write`/`memory.update` as writes. This read/write partition is the load-bearing assumption behind every downstream consumer of the telemetry: replay engines reconstruct state by applying writes in order and treating retrieves as no-ops; auditors diff the span tree against expected state deltas; anomaly detectors flag "write without matching trace span" as corruption. The distinction that actually matters operationally is not read-vs-write but **whether the operation is a state transition that the trace is obligated to record**. A retrieval that promotes a record's recency rank, refreshes its TTL, or evicts a sibling via LRU *is* a state transition. Emitting it as `memory.retrieve` with no delta annotation produces a trace that is internally consistent and externally wrong: the trace says the store is unchanged, the store is changed, and no span accounts for the difference. The non-obvious part: the failure is silent and only surfaces at replay or audit time, often hours later, when a reconstructing agent diverges from the original because its replayed store has a different eviction order than the live one. The trace looks clean. The state is not. ## What Was Observed A retrieval-augmented agent (episodic buffer of 4,096 records, LRU-with-recency-promotion backing store) executed a 340-step task. Telemetry emitted 1,847 `memory.retrieve` spans and 212 `memory.write` spans. No `memory.delete` spans. A replay harness reconstructed the store by applying the 212 writes to the initial snapshot and treating the 1,847 retrieves as pure reads. At step 118 the live agent's store had evicted record `ep_0042` (a task-critical constraint captured at step 9) because a burst of 61 retrievals in 40 seconds promoted 61 competing records above it in recency rank, pushing it past the 4,096-record LRU boundary. The eviction was performed by the *retrieval path*, not by any write. No span recorded it. The replayed store still contained `ep_0042` at step 118, because replay had no eviction signal. The replayed agent therefore retrieved the constraint and proceeded correctly; the live agent did not, silently lost the constraint, and produced a divergent plan at step 121. Post-hoc diffing of the two trajectories showed a 14-step divergence window before the live agent re-derived the constraint from a tool call — a 9.3% task-cost overhead and one incorrect external action. The trace was not corrupt. It was *incomplete in a way the schema could not express*: `memory.retrieve` had no field to say "this retrieve changed the store." The convention's read/write partition made the mutation unrepresentable, and unrepresentable mutations are invisible to every consumer that trusts the partition. Three secondary observations compounded it. First, TTL refresh: 340 retrieves silently extended the lifetime of records that should have expired, so a retention-policy auditor's expected-expiry set diverged from actual by 71 records. Second, access-count mutation: a downstream relevance model trained on `memory.retrieve` counts learned retrieval frequency, but the counts it saw were post-promotion, not the true access distribution, biasing the model toward recently-promoted records. Third, embedding re-index on access: 12 records were re-embedded during retrieval (lazy re-index), changing their vector representation with no span, so a similarity-based audit of "did the agent retrieve the same record it did last run" returned false for records that had not changed semantically. ## Condition of Validity The read/write partition in the semantic convention is valid **if and only if** the backing store satisfies read idempotence: `retrieve(k)` leaves the observable state of the store unchanged, including recency metadata, TTL, access counters, eviction order, and vector representation. This is a testable invariant, not a design aspiration. It holds for immutable snapshot stores and for copy-on-write indexes where the mutation is confined to a versioned overlay the caller never observes. It fails for every LRU, LFU, TTL-with-refresh, lazy-reindex, or access-counted store — which is to say, most production memory layers. When the invariant is violated, the convention must be extended, not the store fixed. The correct emission is a `memory.retrieve` span carrying an explicit `memory.mutation` attribute enumerating the deltas (`recency_promoted`, `ttl_refreshed`, `evicted:[ids]`, `reindexed:[ids]`, `access_count_delta`), and — critically — a companion `memory.evict` or `memory.mutate` span for any delta that a replay engine must apply to reconstruct state. The invariant the telemetry must preserve is: **the ordered set of spans, applied to the initial snapshot, reconstructs the final store bit-for-bit.** A retrieve that mutates without a delta span breaks this invariant, and the break is undetectable from the trace alone. ## Decision Boundary The boundary is a single predicate evaluated at span emission time: *does this operation change any field of any record other than the one returned, or change any non-content field of the returned record?* If yes, the operation is a state transition and must emit a mutation delta. If no, it is a pure read and `memory.retrieve` alone is correct. Three edge cases sit on the boundary and must be resolved explicitly rather than by default: - **Self-mutation only** (recency promotion of the returned record, no eviction): emit `memory.retrieve` with `memory.mutation.self=true` and the delta. Do not emit a separate span — replay can apply self-deltas in retrieve order. This is the common case and the one most often mis-emitted as pure. - **Cross-record mutation** (eviction, TTL cascade, re-index of siblings): must emit a separate `memory.evict`/`memory.mutate` span, because replay cannot infer the affected IDs from the retrieve's return value. - **Non-deterministic mutation** (LRU tie-break, concurrent-access race): must emit the *resolved* victim IDs, not the policy. A replay engine cannot re-run the policy and expect the same result; it must be told the outcome. The boundary is *not* "did the caller intend a write." Intent is irrelevant. The store mutated; the trace must say so. ## Operational Effect Enforcing the mutation-delta invariant changes three things downstream. Replay fidelity: reconstructing agents now diverge only on genuinely non-deterministic operations, and the divergence is localized to the span that admits it rather than smeared across the whole trajectory. Audit correctness: retention and relevance auditors see the true access and eviction distribution, eliminating the promotion bias in access-counted models. Anomaly detection: "write without trace" stops firing on retrieval-path evictions, because those evictions now have spans. The cost is span volume — in the observed workload, 1,847 retrieves became 1,847 retrieves + 1,203 mutation deltas + 61 eviction spans, a 68% increase in memory-span count. That cost is the price of the invariant, and it is non-negotiable for any store that violates read idempotence. The alternative is a trace that is clean, consistent, and wrong — and a replay harness that silently reconstructs a store the live agent never had. The guardrail is a pre-emission check in the memory client, not a post-hoc trace fixer. A trace fixer cannot recover an eviction that was never recorded; it can only guess, and guessing is what produced the 14-step divergence. ```python from dataclasses import dataclass, field from typing import FrozenSet, Optional class MemoryMutationUnrecordedError(RuntimeError): """Raised when a memory operation mutated store state but the emitted span does not carry a mutation delta sufficient for replay reconstruction.""" @dataclass(frozen=True) class StoreDelta: evicted_ids: FrozenSet[str] = frozenset() ttl_refreshed_ids: FrozenSet[str] = frozenset() reindexed_ids: FrozenSet[str] = frozenset() self_recency_promoted: bool = False access_count_changed: bool = False def is_pure(self) -> bool: return not ( self.evicted_ids or self.ttl_refreshed_ids or self.reindexed_ids or self.self_recency_promoted or self.access_count_changed ) @dataclass class RetrieveSpan: span_name: str returned_id: str delta: StoreDelta mutation_span_emitted: bool = False def emit_retrieve_span( returned_id: str, delta: StoreDelta, store_satisfies_read_idempotence: bool, ) -> RetrieveSpan: span = RetrieveSpan( span_name="memory.retrieve", returned_id=returned_id, delta=delta, mutation_span_emitted=False, ) if store_satisfies_read_idempotence: # Pure-read store: a non-empty delta is a store contract violation, # not a telemetry problem. Surface it rather than silently emitting. if not delta.is_pure(): raise MemoryMutationUnrecordedError( f"store declared read-idempotent but retrieve({returned_id}) " f"produced delta {delta!r}; the idempotence contract is broken " f"and the trace cannot be trusted" ) return span # Non-idempotent store: mutation must be representable in the trace. if delta.is_pure(): return span # Self-only mutation can ride on the retrieve span via delta annotation. if ( delta.self_recency_promoted or delta.access_count_changed ) and not (delta.evicted_ids or delta.ttl_refreshed_ids or delta.reindexed_ids): return span # Cross-record mutation requires a dedicated span, because replay cannot # infer affected IDs from the retrieve's return value. if delta.evicted_ids or delta.ttl_refreshed_ids or delta.reindexed_ids: if not span.mutation_span_emitted: raise MemoryMutationUnrecordedError( f"retrieve({returned_id}) mutated sibling records " f"(evicted={sorted(delta.evicted_ids)}, " f"ttl={sorted(delta.ttl_refreshed_ids)}, " f"reindexed={sorted(delta.reindexed_ids)}) but no " f"memory.evict/memory.mutate span was emitted; replay will " f"reconstruct a store the live agent never had" ) return span def guarded_retrieve( client, key: str, store_satisfies_read_idempotence: bool, ) -> RetrieveSpan: result = client.retrieve(key) delta: Optional[StoreDelta] = getattr(result, "delta", None) if delta is None: # A store that cannot report its delta cannot be safely traced as a # read. Fail closed rather than emit a span that may be a lie. raise MemoryMutationUnrecordedError( f"retrieve({key}) returned no delta; cannot determine whether the " f"operation mutated the store, refusing to emit memory.retrieve" ) return emit_retrieve_span( returned_id=result.id, delta=delta, store_satisfies_read_idempotence=store_satisfies_read_idempotence, ) ```