# What structural signals indicate span-tree collapse when memory-read spans are reparented across async agent turns **Date of Record:** 2026 November 24 **Scope:** Applies to distributed-tracing observability pipelines instrumenting LLM agent runtimes where memory operations (vector reads, episodic writes, KV-cache hydration) are emitted as spans and joined to prompt/tool spans via propagated trace context. Does not apply to single-process, synchronous, single-turn inference where the trace tree has no cross-task reparenting. ## Core Distinction The failure is not "a missing span." A missing span is loud: the parent's child count drops, the trace validator flags an orphan, and the dashboard shows a gap. The failure here is **silent reparenting**: a memory-read span that logically belongs to turn *N* of agent task *T* is emitted with a trace context whose `parent_span_id` resolves to a *different* span — typically the root of a sibling turn, a shared thread-pool worker's ambient context, or a freshly-minted span from a cache-warm path. The trace remains structurally valid (every span has a parent, no orphans, no cycle), so schema validation passes. What breaks is *causal attribution*: the pipeline reports memory latency and prompt-token cost against the wrong turn, and any downstream invariant that sums child cost against parent cost now reconciles to the wrong total. The distinction that matters operationally: **orphan detection catches lost spans; it cannot catch mis-parented spans, because a mis-parented span is a perfectly legal tree node.** You need a content-level invariant to see it. ## What Was Observed A multi-turn agent executing a tool-use loop emitted, per turn, a `prompt.render` span (parent = turn span), one or more `tool.call` spans (parent = turn span), and a `memory.retrieve` span. The memory client used `asyncio` and, on a cache miss, dispatched the embedding + vector query to a `ThreadPoolExecutor`. The tracing integration propagated context via a `contextvars` copy taken at executor submission time. Under load, the executor queue backed up. When a queued memory task finally ran, it executed inside a worker thread whose `contextvars` snapshot had been taken *before* the current turn span was entered — specifically, the snapshot belonged to the turn that had *submitted* the task, which under retry was frequently the *previous* turn. Result: `memory.retrieve` spans for turn *N* were parented to turn *N−1*'s turn span. The trace was acyclic and complete. Three structural signals exposed it, none of which a naive orphan check surfaces: 1. **Turn-span cost non-conservation.** For each turn span, `sum(child.duration) > parent.duration` by a margin that tracked executor queue depth. A child cannot outlive its parent's wall-clock window unless it was reparented or the clock is wrong; here it was reparenting. 2. **Memory-read ordinal inversion.** `memory.retrieve` spans carried an attribute `turn_index` (set at call site, not from context). The span's *tree parent* said turn *N−1*; the span's *attribute* said turn *N*. Parent-attribute disagreement is the fingerprint. In clean traces, `parent.turn_index == span.turn_index` for all memory spans; here it diverged for ~11% of spans at p99 queue depth. 3. **Prompt-token double-count.** The cost aggregator summed prompt tokens by walking each turn's subtree. A reparented memory span carries the *retrieved context length* it injected; when attributed to the wrong turn, turn *N−1*'s reported prompt-token count exceeded its own `prompt.render` output-token count — an impossible ratio (retrieved context larger than the rendered prompt that consumed it). The trace that "looked fine" to the validator had a turn whose reported context was 1.8× the prompt it rendered, and whose children summed to 2.3× its own duration. ## Condition of Validity The invariant holds only when the following are simultaneously true, and the guardrail is only sound under these conditions: - **Context propagation is snapshot-at-submit, not snapshot-at-execute.** The bug requires that the tracing context be captured when a task is *queued* rather than when it *runs*. If your integration re-reads ambient context at execution, the span parents to whatever turn is active at run time — which is a *different* wrong answer (turn *N+k*), so this is not a fix, it is a different failure. The correct fix is explicit context capture at the logical call site and explicit re-attachment at execution. - **Turn identity is carried as a span attribute independent of tree position.** Signal #2 depends on `turn_index` being set from the call site. If `turn_index` is derived from the parent span, the signal is self-consistent and invisible. The attribute must be an independent witness. - **Cost accounting is subtree-summed.** Signal #1 and #3 require the aggregator to sum children. If cost is emitted as a flat per-span metric joined by `turn_index` attribute only, the reparenting is invisible to cost but still corrupts latency attribution. - **The memory operation's injected context is measurable.** Signal #3 requires that the memory span record the token length it injected. If memory spans do not carry retrieved-context length, the double-count signal is unavailable. When any of these is false, the specific signals above do not fire, and you must substitute an equivalent independent witness (e.g., a monotonic per-turn sequence number compared against parent's). ## Decision Boundary The boundary is **whether to trust the tree or the attributes when they disagree.** A mis-parented span is a legal tree node; therefore the tree is not authoritative for causality. The decision rule: - If `parent.turn_index != span.turn_index` for a memory/tool span → **quarantine the span from cost aggregation and flag the trace as causally-degraded.** Do not silently re-parent (you don't know the true parent) and do not silently drop (you lose the cost signal). Emit it to a degraded-attribution bucket. - If `sum(child.duration) > parent.duration * (1 + ε)` where ε bounds legitimate async overlap → **the turn span is not the true parent of at least one child.** Treat the turn's subtree cost as an upper bound, not a measurement. - If `turn.reported_prompt_tokens < sum(injected_context_tokens of its memory children)` → **at least one memory child is foreign.** This is the single highest-precision signal; it fires only on reparenting, never on legitimate cache hits or long contexts, because a turn cannot consume more retrieved context than its prompt contains. The guardrail that bounds the failure: **every span that crosses an async boundary must carry an immutable logical-parent identifier that is set at the call site and is never re-derived from ambient context.** The tree parent is a *hint*; the logical-parent attribute is the *contract*. Reconciliation compares the two and quarantines on mismatch rather than trusting either. ## Operational Effect Without the guardrail, the pipeline produces a trace that passes every structural check while systematically mis-attributing memory latency and retrieved-context cost to the preceding turn. Downstream effects compound: per-turn cost dashboards drift toward the earlier turn, so a memory-heavy turn *N* looks cheap and its predecessor looks expensive; a regression detector keyed on per-turn memory latency sees the spike one turn late and correlates it with the wrong tool call; and a budget enforcer summing subtree cost can under- or over-count by the reparented fraction, so token-budget exhaustion is triggered on the wrong turn. In the observed incident, the mis-attribution masked a vector-store slowdown for four turns because each slow memory read was charged to a turn that had already completed. With the guardrail, the mismatch surfaces on the first trace touching p99 executor depth, the degraded-attribution bucket localizes the async boundary (executor submission site), and the fix is a one-line change to capture-and-reattach context at the submission site. The invariant that makes the guardrail sound: **a span's logical parent is a property of the call site, not of the execution context, and any pipeline that derives one from the other will mis-parent under async scheduling without ever failing a schema check.** ```python class SpanAttributionError(RuntimeError): """Raised when a span's tree parent disagrees with its logical-parent witness, or when subtree cost conservation is violated — i.e. the trace is causally degraded.""" pass def reconcile_turn(turn_span, children, epsilon=0.05): """ turn_span: dict with keys 'span_id', 'turn_index', 'duration', 'prompt_tokens' children: list of span dicts, each with 'logical_parent_id', 'turn_index', 'duration', 'injected_context_tokens' Returns a dict of reconciled metrics, or raises SpanAttributionError. """ quarantined = [] for c in children: # Independent witness: call-site turn_index vs tree-parent turn_index. if c.get("turn_index") != turn_span["turn_index"]: quarantined.append(c) continue # Logical parent must match the tree parent it was attached under. if c.get("logical_parent_id") != turn_span["span_id"]: quarantined.append(c) if quarantined: raise SpanAttributionError( f"turn {turn_span['turn_index']} has {len(quarantined)} mis-parented " f"span(s); tree parent disagrees with logical-parent witness. " f"Trace is causally degraded; quarantining from cost aggregation." ) child_dur = sum(c["duration"] for c in children) if child_dur > turn_span["duration"] * (1 + epsilon): raise SpanAttributionError( f"turn {turn_span['turn_index']} subtree cost non-conservation: " f"children sum to {child_dur:.3f}s > parent {turn_span['duration']:.3f}s " f"(epsilon={epsilon}). At least one child is foreign to this turn." ) injected = sum(c.get("injected_context_tokens", 0) for c in children) if injected > turn_span["prompt_tokens"]: raise SpanAttributionError( f"turn {turn_span['turn_index']} injected context ({injected} tok) " f"exceeds rendered prompt ({turn_span['prompt_tokens']} tok): " f"impossible ratio indicates a memory span reparented from another turn." ) return { "turn_index": turn_span["turn_index"], "attributed_child_duration": child_dur, "attributed_injected_tokens": injected, "status": "clean", } ```