# Which invariants prevent semantic-convention memory events from desynchronizing from the memory store they instrument **Date of Record:** 2026 November 21 **Scope:** Applies to agents that emit OpenTelemetry-style GenAI semantic convention events (`gen_ai.memory.read`, `gen_ai.memory.write`, `gen_ai.memory.forget`) as a side channel to an actual memory backend (vector store, KV cache, episodic log). Does not apply to agents whose memory operations are the telemetry (i.e., the event log *is* the store), nor to pure in-process scratchpads with no durable backing. ## Core Distinction There are two classes of memory-operation telemetry that look identical on the wire and behave nothing alike under failure: 1. **Observational events** — emitted after the memory operation completes, carrying the outcome. If the process dies between the store mutation and the event emission, you lose the event but the store is consistent. The event stream is *lossy but never lying*. 2. **Intent events** — emitted before or concurrently with the mutation, carrying the operation the agent *intends* to perform. These are what most GenAI instrumentation libraries produce by default, because they wrap the call site (`with tracer.start_as_current_span("gen_ai.memory.write")`) rather than the store's commit point. If the process dies between emission and commit, you have an event asserting a write that never happened. The event stream is *complete but lying*. The boundary failure is not "events get dropped." It is that **intent events are indistinguishable from observational events once serialized**, and any downstream consumer (an auditor, a replay harness, a second agent reconstructing state from the event log) will treat a phantom write as a real one. The invariant that matters is not delivery — it is **falsifiability**: every emitted event must be attributable to a committed store state, or explicitly marked as uncommitted. ## What Was Observed A long-running research agent used a `gen_ai.memory.write` event to record each fact it distilled into a vector store. The instrumentation wrapped the embedding+upsert call: - Span started → `gen_ai.memory.write` event emitted with `memory.operation=write`, `memory.record_id`, `memory.content_hash`, `memory.store=vector://facts`. - Then `embed()` (network call, ~200–900ms) → then `upsert()` (network call, ~50–400ms). - Span ended on success. Two failure traces surfaced: **Trace A — phantom write on embed timeout.** At T+0 the event fired with a `record_id` the agent had pre-generated. At T+0.9s the embedding endpoint returned 504. The agent's retry loop caught the exception, generated a *new* `record_id`, and retried. The event stream now contained two `gen_ai.memory.write` events, one of which corresponded to zero bytes in the store. A downstream auditor agent, tasked with "verify every written fact is retrievable," fetched the phantom `record_id`, got a miss, and — correctly, by its own rules — flagged the store as corrupted. It then initiated a repair pass that re-derived facts from the (partially written) event log, propagating the phantom record as a "recovered" fact. One timeout became a duplicated, ungrounded memory. **Trace B — forget/write reordering.** A `gen_ai.memory.forget` for `record_id=X` was emitted at T+0, then the store delete was queued behind a batch of writes and executed at T+1.2s. Meanwhile a `gen_ai.memory.write` for a *re-derived* version of the same fact (new `record_id=Y`, same `content_hash`) committed at T+0.6s. The event log order was `forget(X)` then `write(Y)`. A replay harness reconstructing state by folding events in timestamp order produced a store containing Y — correct. But the *live* store, applying operations in commit order, executed `write(Y)` then `forget(X)`, and the delete predicate matched on `content_hash`, not `record_id`, so it removed Y as well. Live store: empty. Replayed store: contains Y. The two diverged by one record, and every subsequent read event against the live store returned a miss that the replay could not explain. Neither failure involved a lost event. Both involved events that were *true statements about intent* being consumed as *true statements about state*. ## Condition of Validity The invariant holds only under a conjunction that is easy to violate silently: - **Commit-anchored emission.** The event must be emitted after the store acknowledges the mutation, and must carry the store's own acknowledgment token (version, etag, sequence number, or commit LSN), not an agent-generated UUID. Pre-generated IDs are the single most common source of phantom writes because they exist before the write does. - **Monotonic operation ordering per record.** For a given logical record, the event stream's order must equal the store's commit order. This requires either (a) serializing memory ops per record through a single sequencer, or (b) stamping each event with the store's commit sequence and requiring consumers to fold by *that* key, never by wall-clock timestamp. Wall-clock folding is invalid whenever the store is batched, queued, or replicated. - **Content-addressed deletes must be resolved at commit, not at intent.** A `forget` emitted with a predicate (`content_hash=...`) is an intent event by construction: the set of records it will delete is not known until the store evaluates it. Such events must carry the *resolved* record set post-commit, or be marked `memory.forget.predicate=unresolved` so consumers do not treat them as point deletes. - **Failure events are first-class.** A `gen_ai.memory.write` that did not commit must produce a terminal event with `memory.outcome=not_committed` (or an equivalent error status) *before* any retry emits a new write event. Without this, retries are indistinguishable from duplicate writes, and the event log cannot be folded into state without guessing. When any of these is absent, the event stream is a log of attempts, not a log of state, and the two cannot be reconciled after the fact. ## Decision Boundary The operational question is not "should we emit memory events" but **"can a consumer reconstruct store state from the event stream alone, and detect when it cannot?"** The boundary: - If the answer is **yes** (commit-anchored, sequence-stamped, failure-explicit), the event stream is a valid state-transfer medium — usable for replay, audit, and cross-agent handoff, including handing a reconstructed memory to a cold-started instance. - If the answer is **no**, the event stream is *diagnostic only*. It must be labeled as such (a `memory.authority=observational` attribute on every event, or a stream-level schema version that consumers are required to check), and no auditor, replay harness, or peer agent may treat it as authoritative. Any consumer that folds it into state must be considered buggy, not merely optimistic. The dangerous middle ground — which is where default instrumentation lands — is a stream that *looks* authoritative (it has record IDs, content hashes, timestamps, and a tidy schema) but is not. The boundary condition is a consumer that cannot tell which side it is on. Enforce it structurally: require a `memory.commit_token` field, and make its absence a hard parse error in every consumer, so the observational/intent distinction is not a matter of documentation but of schema. ## Operational Effect With the invariant enforced, three things change: 1. **Phantom writes become impossible to misread.** A retry after a failed embed produces `write(not_committed)` then `write(committed, token=...)`. The auditor sees the first event's terminal status and does not attempt retrieval. The repair pass is not triggered. 2. **Forget/write races resolve deterministically.** Folding by commit sequence instead of timestamp yields the live store's state exactly, because both are ordered by the same sequencer. Predicate deletes carry their resolved record set, so a re-derived record with a colliding `content_hash` is either explicitly in the delete set or explicitly not — no inference from hash equality. 3. **Cold-start reconstruction becomes sound.** A fresh instance can rebuild memory from the event stream and know, per record, whether it is reconstructing a committed fact or an abandoned attempt. The cold-start amnesia failure mode is bounded: the instance either has the fact with a commit token, or knows the fact was never committed, and does not hallucinate a middle state. The cost is instrumentation discipline: the event must be emitted at the store's commit point, which means the instrumentation cannot live purely at the call site — it must wrap the store adapter, or the adapter must return the commit token to the call site before the event is emitted. That is a real refactor, and it is the price of a stream that can be trusted as state rather than merely read as narrative. ```python from dataclasses import dataclass, field from typing import Optional import time class MemoryEventIntegrityError(RuntimeError): """Raised when a memory event cannot be reconciled with store commit state.""" pass @dataclass class MemoryEvent: operation: str # "read" | "write" | "forget" record_id: str content_hash: Optional[str] = None commit_token: Optional[str] = None # store-issued; None => not committed commit_seq: Optional[int] = None # store monotonic sequence outcome: str = "not_committed" # "committed" | "not_committed" | "failed" predicate_unresolved: bool = False # for forget-by-predicate wall_ts: float = field(default_factory=time.time) def emit_write_event(record_id: str, content_hash: str, commit_token: Optional[str], commit_seq: Optional[int]) -> MemoryEvent: """Emit a write event. Must be called AFTER the store acknowledges the upsert.""" if commit_token is None or commit_seq is None: # The write did not commit. This is a legal, first-class event: # it records the attempt without asserting state. return MemoryEvent( operation="write", record_id=record_id, content_hash=content_hash, commit_token=None, commit_seq=None, outcome="not_committed", ) return MemoryEvent( operation="write", record_id=record_id, content_hash=content_hash, commit_token=commit_token, commit_seq=commit_seq, outcome="committed", ) def fold_events_to_state(events: list[MemoryEvent]) -> dict[str, MemoryEvent]: """Reconstruct store state from events. Folds by commit_seq, never wall_ts.""" for e in events: if e.outcome == "committed" and (e.commit_token is None or e.commit_seq is None): raise MemoryEventIntegrityError( f"event claims committed but lacks commit_token/commit_seq: {e}" ) if e.operation == "forget" and e.predicate_unresolved and e.outcome == "committed": raise MemoryEventIntegrityError( f"committed forget event has unresolved predicate; cannot fold: {e}" ) committed = [e for e in events if e.outcome == "committed"] if any(e.commit_seq is None for e in committed): raise MemoryEventIntegrityError("committed event missing commit_seq") committed.sort(key=lambda e: e.commit_seq) state: dict[str, MemoryEvent] = {} for e in committed: if e.operation == "write": state[e.record_id] = e elif e.operation == "forget": state.pop(e.record_id, None) return state def assert_replay_matches_live(replayed: dict[str, MemoryEvent], live_ids: set[str]) -> None: """Guardrail: event-derived state must equal live store key set.""" replayed_ids = set(replayed.keys()) if replayed_ids != live_ids: only_replay = replayed_ids - live_ids only_live = live_ids - replayed_ids raise MemoryEventIntegrityError( f"event stream diverged from live store: " f"replay_only={only_replay} live_only={only_live}" ) ```