# Where must an instance reconcile causal trace graph edges when memory mutations are observed out of causal order relative to the LLM call that motivated them **Date of Record:** 2026 November 30 **Scope:** Applies to runtime observability systems that build causal trace graphs spanning LLM inference spans, tool-invocation spans, and memory-store mutation spans within a single agent instance or across a handoff. Does not apply to stateless single-shot inference with no memory writes, nor to purely metric-based telemetry without causal linkage. ## Core Distinction A causal trace graph asserts that every memory mutation span has exactly one *motivating* LLM span (the reasoning step that decided to write) and that the edge direction runs `LLM_span → tool_span → memory_mutation_span`. This invariant is what lets an operator answer "why does the agent believe X?" by walking backward from a memory cell to the inference that authored it. The non-obvious boundary: **memory mutations are frequently observed (by the tracing collector) *before* the LLM span that motivated them is finalized**, because the LLM span's completion — including token accounting, finish-reason, and the sampled tool-call arguments — is emitted only after streaming ends, while the memory write may execute and be observed mid-stream via an asynchronous side channel (a memory-daemon hook, a vector-store WAL tail, or a callback from a tool that writes as a side effect). The collector then faces an edge whose child exists and whose parent does not yet exist. Naive graph builders either (a) attach the mutation to the *previous* LLM span (the wrong parent, off-by-one causal attribution) or (b) create an orphan root and later fail to reconcile when the true parent arrives. ## What Was Observed In a trace of a 14-step ReAct agent, step 7 emitted a `memory.upsert` mutation span at wall-clock T+412ms. The LLM span for step 7 (`llm.call#7`) did not finalize until T+690ms because the provider streamed 2,100 completion tokens and the SDK withheld the span-close event until `finish_reason=stop` plus usage accounting returned. The collector, using a "attach to most-recent-open-LLM-span" heuristic, attached the mutation to `llm.call#6`, which had closed at T+401ms. Downstream consequence: an auditor replaying the trace to determine why the agent's memory cell `policy_pref` changed concluded the change was motivated by step-6 reasoning (a retrieval query about refund windows), not step-7 reasoning (an explicit user correction). The replay produced a *plausible but false* causal narrative. When the agent later behaved on the stale-but-now-attributed preference, the post-incident review exonerated the correct inference step and flagged the wrong one. The failure is silent: the graph is well-formed (every mutation has a parent), acyclic, and passes schema validation. Only the *semantic* invariant — parent = motivating inference — is violated. ## Condition of Validity The edge `llm.call#N → memory_mutation` is valid **only if** the mutation's `motivating_span_id` was propagated out-of-band (e.g., via a trace-context header or a W3C `traceparent` injected into the tool/memory call) rather than inferred from temporal adjacency. Temporal-adjacency attribution is valid only under the conjunctive condition: 1. LLM spans are strictly serialized (no concurrent inference), **and** 2. the memory mutation cannot begin until the LLM span has closed (i.e., the write is issued *after* completion returns), **and** 3. the collector's clock and the agent's clock are the same monotonic source. In streaming, tool-calling agents, condition (2) is routinely false: the model emits a tool call *within* the stream, the runtime dispatches it before the span closes, and the tool writes memory. All three conditions must hold simultaneously; violation of any one voids adjacency-based attribution. ## Decision Boundary The collector must choose between two policies at the moment a mutation span arrives with no matching open parent: - **Defer-and-reconcile** (correct when out-of-band context is present or recoverable): buffer the mutation in a pending set keyed by `motivating_span_id`, hold it until the parent span closes, then emit the edge. Requires a bounded pending buffer and a timeout. - **Orphan-and-flag** (correct when no context is recoverable): emit the mutation as a root with `attribution=unresolved`, never silently attach to the nearest open span. The boundary is crossed — and the failure becomes unrecoverable — when the collector applies *nearest-open-span* attribution. That policy is indistinguishable from correct behavior on well-formed traces and only diverges exactly in the streaming-tool-call window, which is precisely the window operators care about during incident review. The guardrail: a mutation span MUST carry `motivating_span_id`; if absent, the collector MUST NOT infer a parent and MUST mark the edge `attribution=unresolved`. Reconciliation must be idempotent and must re-parent (not duplicate) when the true parent arrives late. ## Operational Effect With defer-and-reconcile plus mandatory context propagation, backward walks from a memory cell terminate at the true motivating inference and replay reconstructs the actual decision. The cost is a bounded pending buffer (typically < 5s of mutations) and a hard requirement that tool and memory clients forward trace context. Without it, the trace graph is structurally valid and semantically corrupt: post-incident attribution silently shifts by one reasoning step, and any automated auditor that trusts edge direction will certify the wrong causal story. The invariant to enforce is **one motivating parent per mutation, established by propagated context, never by adjacency** — and the reconciliation point is the moment the mutation span is first observed, not when the trace is flushed. ```python from __future__ import annotations from dataclasses import dataclass, field from typing import Optional class CausalAttributionError(RuntimeError): """Raised when a memory mutation cannot be validly attributed to a motivating LLM span.""" @dataclass class Span: span_id: str kind: str # "llm" | "tool" | "memory_mutation" closed: bool = False @dataclass class TraceGraph: spans: dict[str, Span] = field(default_factory=dict) parent_of: dict[str, str] = field(default_factory=dict) pending: dict[str, list[str]] = field(default_factory=dict) # motivating_span_id -> [child_ids] def open_span(self, span_id: str, kind: str) -> None: self.spans[span_id] = Span(span_id=span_id, kind=kind) def close_span(self, span_id: str) -> None: self.spans[span_id].closed = True # Reconcile any mutations that were deferred waiting on this parent. for child in self.pending.pop(span_id, []): self.parent_of[child] = span_id def observe_mutation(self, span_id: str, motivating_span_id: Optional[str]) -> None: self.spans[span_id] = Span(span_id=span_id, kind="memory_mutation", closed=True) if motivating_span_id is None: # No out-of-band context: MUST NOT infer parent from adjacency. raise CausalAttributionError( f"mutation {span_id} has no motivating_span_id; " "refusing nearest-open-span attribution (would corrupt causal walk)" ) parent = self.spans.get(motivating_span_id) if parent is None: # Parent not yet observed at all: defer, do not orphan silently. self.pending.setdefault(motivating_span_id, []).append(span_id) return if not parent.closed: # Parent still streaming (the streaming-tool-call window): defer. self.pending.setdefault(motivating_span_id, []).append(span_id) return self.parent_of[span_id] = motivating_span_id def walk_backward(graph: TraceGraph, from_span: str) -> list[str]: """Return the causal chain from a memory mutation back to its motivating LLM span.""" chain: list[str] = [] cur: Optional[str] = from_span while cur is not None: chain.append(cur) cur = graph.parent_of.get(cur) root = graph.spans[chain[-1]] if root.kind == "memory_mutation": raise CausalAttributionError( f"walk from {from_span} terminated at unattributed mutation {root.span_id}; " "trace is structurally valid but semantically corrupt" ) return chain def demo() -> None: g = TraceGraph() g.open_span("llm#7", "llm") # Mutation observed mid-stream, before llm#7 closes. g.observe_mutation("mem#7", motivating_span_id="llm#7") assert "mem#7" not in g.parent_of # deferred, not mis-attributed to llm#6 g.close_span("llm#7") assert g.parent_of["mem#7"] == "llm#7" assert walk_backward(g, "mem#7") == ["mem#7", "llm#7"] # Demonstrating the guardrail: context-less mutation is rejected, not guessed. try: g.observe_mutation("mem#8", motivating_span_id=None) except CausalAttributionError: pass else: raise CausalAttributionError("guardrail failed: adjacency attribution was permitted") if __name__ == "__main__": demo() ```