# Why does an instance lose causal linkage between prompt, tool, and memory spans when a memory-write span is emitted after the tool span closes but before the prompt span's response is finalized **Date of Record:** 2026 November 29 **Scope:** Applies to observability pipelines that reconstruct a single causal trace by joining prompt spans, tool-call spans, and memory-operation spans emitted by an agent runtime. Does not apply to single-span logging or to runtimes that emit a single composite span per turn. ## Core Distinction The failure is not "missing telemetry." Every span is emitted, timestamped, and shipped. The failure is a **causal-ordering inversion at the join boundary**: the memory-write span carries a parent reference to the prompt span, but the prompt span's *response-finalization* event (the one that carries the final assistant message and the trace-closing timestamp) is emitted *after* the memory-write span. Observability backends that build the causal tree by "child must complete before parent closes" (a common invariant in span processors and in trace-assembly logic) therefore either drop the memory-write span, re-parent it to the tool span, or mark the whole trace as `incomplete`. The result is a trace that looks structurally valid but whose memory operations are attributed to the wrong causal parent — or lost entirely. This is distinct from clock skew. Clock skew produces out-of-order timestamps across hosts; this failure produces an *in-order* emission (tool closes, memory writes, prompt finalizes) that is nonetheless *semantically* a child-before-parent-completion violation, because the memory write was triggered *by the tool result* and is therefore a sibling of the tool span under the prompt span, not a descendant of the tool span. ## What Was Observed A representative trace from a retrieval-augmented agent turn: 1. `prompt.span` opens at `t0` with `span_id=P`, `parent=null`. 2. The model emits a tool call; `tool.span` opens at `t1` with `span_id=T`, `parent=P`. The tool executes and returns a document. 3. The runtime, before the model's *next* completion, distills the tool result into episodic memory and emits `memory.write.span` with `span_id=M`, `parent=P`, `start=t2`, `end=t3`, where `t3 > t1` (tool end) but `t3 < t4` (prompt finalization). 4. The model produces the final assistant message; `prompt.span` closes at `t4`. The backend's trace assembler applies the invariant *"a parent span may not close before all children have closed."* It sees `M.end = t3` and `P.end = t4`, so `M` closed before `P` — that part is fine. But the assembler also enforces *"a child's parent must be open at the child's start"* and, more importantly, a **response-finalization ordering check**: any span whose `parent` is a prompt span must be emitted *before* the prompt span's `response.finalized` event. Because the memory write is triggered by the tool result and the runtime flushes memory *lazily* (on the next turn or on a background timer), the memory span's `end` timestamp can land *after* `response.finalized` even though its `start` is before it. The assembler then classifies `M` as `post_finalization_orphan` and either drops it or re-parents it to the most recent open span — which is `T`, the tool span. The observable symptom: in the trace UI, the memory write appears as a *child of the tool*, implying the tool performed the memory write. Downstream attribution (cost, latency, "which component caused memory growth") is now wrong. A second symptom: when two memory writes occur (one from the tool result, one from the final message), the second is correctly parented to `P` but the first is re-parented to `T`, producing a **split causal chain** where the same memory key has two different causal ancestors in the same trace. ## Condition of Validity The invariant holds — i.e., the failure is *possible* — only when all of the following are true: - The runtime emits memory-operation spans **lazily**, asynchronously, or on a flush timer, rather than synchronously within the tool-result handling block. - The observability backend enforces a **parent-must-be-open / response-finalization-before-child-close** ordering check, rather than accepting spans by timestamp alone. - The memory write is **causally downstream of the tool result** but **structurally a sibling** of the tool span (both children of the prompt span). This is the norm in agent runtimes: a tool returns data, the runtime writes it to memory, the model then reads from memory on the next turn. The failure does **not** occur when: memory writes are emitted synchronously inside the tool span (then `M.parent = T` legitimately), when the backend sorts purely by `start` timestamp without ordering checks (then `M` is kept, correctly parented, but `end`-time ordering is not validated), or when the runtime emits a single composite turn span. ## Decision Boundary The boundary is: **does the memory-write span's `end` timestamp precede the prompt span's `response.finalized` event?** If yes, the trace assembles cleanly. If no, the assembler must make a decision: - **Drop** the memory span (loss of observability — the memory write becomes invisible). - **Re-parent** to the nearest open ancestor (mis-attribution — the tool is blamed for the memory write). - **Emit an `orphan` marker** and keep the span with `parent=P` but flag the trace `incomplete` (correct attribution, noisy traces). Each choice trades a different invariant. Dropping preserves tree well-formedness at the cost of completeness. Re-parenting preserves completeness at the cost of causal correctness. Flagging preserves correctness at the cost of downstream alerting noise. The decision must be made **per backend**, and the runtime must be told which policy is in force, because the runtime's flush strategy determines whether the boundary is crossed. The guardrail: the runtime must **close the prompt span only after all causally-dependent memory spans have been emitted**, or the backend must accept `parent` references to spans that close later (i.e., allow child-close-after-parent-close, keyed by `start` ordering). The former requires the runtime to synchronously flush memory before finalizing the response; the latter requires the backend to relax its ordering check. Neither is free. ## Operational Effect When the boundary is crossed and the backend re-parents, the operational consequence is **mis-attributed memory cost and latency**: the tool span's reported duration absorbs the memory-write latency, inflating tool p99 and making the tool appear to be the memory bottleneck. When the backend drops, memory-write counts under-report, and a memory-growth incident looks like a tool-result-volume incident. When the backend flags, every trace containing a lazy memory write is marked `incomplete`, and the on-call engineer learns to ignore the flag — a classic alarm-fatigue failure. The correct operational posture is to **pin the flush semantics at the runtime boundary**: emit memory-write spans with an explicit `causal_parent` field separate from the structural `parent`, and require the backend to join on `causal_parent` rather than structural ancestry. This decouples "which span caused this" from "which span structurally contains this," and it is the only formulation that survives both synchronous and lazy flush strategies without re-parenting or dropping. ```python class CausalLinkageError(RuntimeError): """Raised when a memory-write span's causal parent cannot be reconciled with the structural span tree under the backend's ordering invariant.""" pass def assemble_trace(spans, response_finalized_at): """ spans: list of dicts with keys span_id, parent, causal_parent, kind ('prompt'|'tool'|'memory'), start, end. response_finalized_at: timestamp of the prompt span's response.finalized event. """ by_id = {s["span_id"]: s for s in spans} tree = {} for s in spans: # Structural parent must be open at child start. parent = by_id.get(s["parent"]) if parent is not None and s["start"] < parent["start"]: raise CausalLinkageError( f"span {s['span_id']} starts before its parent {parent['span_id']}" ) # Memory spans must have their causal parent resolved, and the # causal parent must NOT be the tool span when the write was # triggered by the tool result (sibling semantics). if s["kind"] == "memory": cp = s.get("causal_parent") if cp is None: raise CausalLinkageError( f"memory span {s['span_id']} has no causal_parent; " "cannot disambiguate tool-triggered vs prompt-triggered write" ) if cp not in by_id: raise CausalLinkageError( f"memory span {s['span_id']} references unknown causal_parent {cp}" ) # Boundary check: if the memory span ends after response # finalization, the backend's ordering invariant would # re-parent or drop it. We refuse to silently mutate the tree. if s["end"] > response_finalized_at: raise CausalLinkageError( f"memory span {s['span_id']} ends at {s['end']} after " f"response.finalized at {response_finalized_at}; " "backend would re-parent to nearest open span (likely the tool) " "or drop the span. Fix flush ordering or relax the invariant." ) tree.setdefault(cp, []).append(s["span_id"]) return tree # Trigger the failure: a lazy memory write that ends after finalization. spans = [ {"span_id": "P", "parent": None, "causal_parent": None, "kind": "prompt", "start": 0, "end": 100}, {"span_id": "T", "parent": "P", "causal_parent": "P", "kind": "tool", "start": 10, "end": 40}, {"span_id": "M", "parent": "P", "causal_parent": "T", "kind": "memory", "start": 45, "end": 120}, # ends after finalization ] assemble_trace(spans, response_finalized_at=100) ```