# What happens when an instance mutates memory inside a span whose parent trace was already exported **Date of Record:** 2026 November 24 **Scope:** Applies to agent runtimes that emit OpenTelemetry spans for prompt assembly, retrieval, tool invocation, and memory mutation, where span export is asynchronous and memory stores are shared across instances. Does not apply to single-process, synchronous, in-memory-only agents with no cross-instance memory sharing. ## Core Distinction The failure is not "missing telemetry." It is a *causal ordering violation between span export and memory mutation* that produces a trace which is internally consistent but externally false. A memory mutation (episodic write, semantic distillation, embedding upsert) is performed by instance A inside a span `S_mut`. The span carries a `trace_id` and `span_id`, plus a `parent_span_id` pointing at the retrieval or reasoning span that *justified* the mutation. Under normal operation, `S_mut` is exported after the mutation commits, and the trace reconstructs as: prompt → retrieval → decision → mutation, all causally linked. The boundary case: the parent trace's root span has *already been exported and closed* (batch exporter flushed, or the root span ended because the agent's turn returned to the caller), while a deferred memory mutation—queued by a distillation worker, a background consolidation job, or a retry of a failed tool call—executes afterward and emits `S_mut` with a `parent_span_id` that no longer exists in any live trace context. The OTel SDK does not error. It exports a span whose parent is a *tombstone*. The result is a trace store where memory mutations appear as orphaned roots or, worse, get re-parented by a downstream collector to a *different* trace with a colliding or reused context, silently attributing a write to the wrong prompt. This is the distinction that matters: **the mutation is real, the span is real, but the causal edge is fabricated by the collector's repair logic.** ## What Was Observed In a 14-day window across a fleet of consolidation workers, roughly 3.1% of memory-mutation spans arrived at the collector with a `parent_span_id` not present in the batch. The collector's default behavior—reparent-to-root on missing parent—produced traces that read as: ``` trace 7f3a... root: agent.turn (duration 1.2s) └─ retrieval.query (0.4s) └─ memory.mutate (0.0s) <-- actually executed 40s later, different process ``` The `memory.mutate` span's `start_time` was 40 seconds after the root's `end_time`. Nothing in the trace flagged this. The duration field was correct (0.0s, a fast write), the parent link was plausible, and the ordering was only detectable by comparing timestamps across the tree—which most trace UIs do not surface. The concrete trigger: a tool call inside turn N returned a non-deterministic error (a transient 503 from an embedding service). The agent's retry policy re-queued the embedding upsert into a durable mutation queue with the *original* `SpanContext` captured at enqueue time. By the time the queue drained, the turn had ended, the root span had been exported, and the SDK's `NonRecordingSpan` carrying the stale context was used as the parent. The SDK faithfully propagated a dead parent. A second, subtler observation: when two instances shared a memory namespace and both mutated the same key, their spans carried distinct `trace_id`s but the *mutation ordering* was only recoverable from the store's write-ahead log, not from the traces. The traces showed two independent, well-formed mutation spans with no edge between them. An auditor replaying the trace concluded the writes were concurrent and idempotent; the store's log showed a lost-update (last-writer-wins clobber) that the traces could not represent. ## Condition of Validity The invariant that must hold for trace correlation to be trustworthy: > **For every memory-mutation span `S_mut`, `S_mut.parent_span_id` must resolve to a span whose `end_time` is ≤ `S_mut.start_time`, and the mutation's commit timestamp must fall within `[S_mut.start_time, S_mut.end_time]`.** This invariant is violated whenever the mutation is decoupled from the span lifetime by *any* of: (a) durable queuing with captured-but-stale `SpanContext`, (b) background consolidation running after turn completion, (c) retry-after-export, or (d) cross-instance handoff where the receiving instance reuses a context it did not create. The invariant is *only* valid when the mutation is synchronous within the parent span's lifetime, or when the deferred mutation opens a **new root span** and records the causal link as a *span link* (`Link` with `SpanContext` of the original), not as a parent. Links are explicitly designed for this: they express causality without asserting containment, and collectors do not attempt to reparent across links. ## Decision Boundary The boundary is: **does the mutation commit before or after the justifying span is exported?** - **Before export (synchronous):** parent-child is correct. Emit `S_mut` as a child. No special handling. - **After export (deferred, queued, retried, cross-instance):** parent-child is a lie. The justifying span is a tombstone. The correct emission is a *new root* `S_mut` with a `Link` to the captured `SpanContext`, plus an explicit attribute `mutation.deferred=true` and `mutation.justified_by_trace=`. The failure to make this distinction at the emission site is what produces the fabricated edge. The SDK will not warn you; `tracer.start_span(..., context=stale_ctx)` succeeds and exports a dead parent. The collector will not warn you; it reparents silently. The only signal is a timestamp ordering check that almost no pipeline performs. A secondary boundary: **shared-namespace concurrent mutation.** When two instances write the same key, parent-child cannot express the race. The correct representation is a link between the two mutation spans *and* a store-side sequence number attribute (`memory.write_seq`) so the trace and the log can be reconciled. Without the sequence number, the trace is unfalsifiable. ## Operational Effect The downstream consequence is *audit corruption*, not observability loss. An incident reviewer reconstructing "why did the agent believe X" reads the trace, sees `memory.mutate` nested under the turn that produced the belief, and concludes the write was part of that reasoning. It was not—it was a retry from a prior turn, or a consolidation pass from a different instance, and the belief was actually formed from stale memory that the mutation later overwrote. The trace actively misleads. The guardrail is a two-part emission contract enforced at the SDK wrapper, not at the collector: 1. **Lifetime check at emission:** before starting `S_mut`, compare the captured `SpanContext`'s parent span `end_time` (if known) or a monotonic turn-generation counter against the current turn. If the justifying turn has closed, demote to root + link. 2. **Sequence stamping:** every mutation span carries `memory.write_seq` from the store's WAL, so trace replay can detect lost updates that the span tree cannot represent. Without both, the trace is a plausible fiction. The following guard implements the lifetime check and refuses to emit a child span against a closed parent, forcing the caller to either link or fail loudly. ```python import time from dataclasses import dataclass class StaleParentSpanError(RuntimeError): """Raised when a memory mutation attempts to parent to an already-exported span.""" pass @dataclass class SpanContext: trace_id: str span_id: str end_time: float | None # None means still open def emit_memory_mutation( ctx: SpanContext, mutation_commit_ts: float, now: float | None = None, ) -> dict: """ Emit a memory-mutation span. Enforces the lifetime invariant: a mutation may only be a child of a span that is still open and whose end_time is <= mutation start. """ now = now if now is not None else time.time() if ctx.end_time is not None and ctx.end_time <= now: # Parent already exported. Parent-child would fabricate a causal edge. raise StaleParentSpanError( f"cannot parent memory.mutate to span {ctx.span_id} in trace " f"{ctx.trace_id}: parent closed at {ctx.end_time:.3f} " f"but mutation starts at {now:.3f}. " f"Emit as root span with Link to {ctx.trace_id}/{ctx.span_id} instead." ) if mutation_commit_ts < now - 0.001: raise StaleParentSpanError( f"mutation commit {mutation_commit_ts:.3f} precedes span start " f"{now:.3f}; ordering invariant violated for trace {ctx.trace_id}" ) return { "trace_id": ctx.trace_id, "parent_span_id": ctx.span_id, "name": "memory.mutate", "start_time": now, "attributes": {"mutation.deferred": False}, } ```