# Which invariants prevent orphaned tool-call spans from silently severing causal chains in eval-in-production trace pipelines **Date of Record:** 2026 November 21 **Scope:** Applies to multi-turn agent runtimes that emit OpenTelemetry-style spans per LLM call and per tool invocation, then reconstruct causal DAGs downstream for eval-in-production hooks (online scoring, regression detection, reward attribution). Does not cover single-shot completion logging, batch offline eval, or trace storage retention policy. ## Core Distinction There are two structurally different notions of "parent" in an agent trace, and conflating them is the root of the failure. The **execution parent** is the span that was on the call stack when a child span was created—a runtime fact, captured at emit time. The **causal parent** is the span whose output *materially determined* the child's input—a semantic fact, reconstructed by the pipeline. For LLM-generated tool calls these two diverge routinely, because the agent framework executes the tool in a fresh dispatch context (a worker, a subprocess, an async task boundary) that has no stack relationship to the reasoning span that emitted the call. The runtime therefore sets `parent_span_id` to the dispatcher, not to the reasoning step that produced the tool arguments. The invariant that must hold is: **every tool-call span carries a resolvable causal edge back to the specific LLM span whose sampled output contained its call arguments.** When this invariant lapses, the pipeline still produces a well-formed tree—it is just the *wrong* tree—and every downstream consumer that assumes tree-adjacency equals causal-adjacency silently misattributes. This is the non-obvious boundary: the failure produces no error, no dropped span, no schema violation. It produces a plausible, complete, and wrong causal graph. ## What Was Observed A multi-turn agent with four tools (search, fetch, calculator, file-write) was instrumented with span emission at both the LLM-call boundary and the tool-dispatch boundary. Each LLM span recorded `input_tokens`, `output_tokens`, the sampled completion, and a `tool_calls[]` array (name + JSON arguments + a generated `call_id`). Each tool span recorded `tool_name`, `arguments`, `result`, and `parent_span_id`. The dispatch layer ran tool calls on a bounded worker pool. Under load, the dispatcher created tool spans from the worker's ambient context, so `parent_span_id` resolved to the *dispatcher's* span (a long-lived, turn-agnostic span), not to the LLM span. The trace tree rendered as: ``` dispatcher (turn-agnostic) ├── tool.search (turn 3, call_id=a1) ├── tool.fetch (turn 3, call_id=a2) ├── tool.calc (turn 5, call_id=b1) └── tool.write (turn 7, call_id=c1) ``` with the LLM spans as siblings under the root, disconnected from the tools they actually drove. The `call_id` on each tool span matched a `call_id` inside an LLM span's `tool_calls[]` array—the information needed to repair the edge was present—but the reconstruction step never consulted it. It trusted `parent_span_id`. The eval-in-production hook computed a per-tool-call "reasoning attribution" score: for each tool span, it walked to its parent LLM span, took that span's output, and scored whether the tool arguments were faithful to the stated reasoning. Under the broken tree, every tool span's parent was the dispatcher, which had no completion text. The hook's fallback path scored these as `attribution=0.0` (no reasoning to attribute). The regression detector then flagged a 40% drop in tool-call faithfulness across a model upgrade—a drop that did not exist. The model upgrade was rolled back on a phantom regression. The real cause was that the upgrade had increased concurrency, which increased worker-pool pressure, which increased the fraction of tool spans parented to the dispatcher rather than to a turn-local span. ## Condition of Validity The causal-edge invariant holds only when three conditions are jointly satisfied at reconstruction time: 1. **Uniqueness of `call_id` within a trace.** The `call_id` generated at sampling time must be globally unique within the trace, not merely within a turn. Frameworks that reset a per-turn counter (`call_0`, `call_1`, ...) violate this; two turns both emitting `call_0` make the edge ambiguous, and the repair step silently picks the first match. 2. **The LLM span's `tool_calls[]` is persisted before the tool span is emitted.** If the tool executes and emits before the parent's completion is flushed (common when streaming tool-call deltas are executed eagerly), the reconstruction pass may run against a trace where the parent's `tool_calls[]` is absent or truncated. The edge is then unresolvable *at that moment* and must be deferred, not defaulted. 3. **The reconstruction pass is idempotent and order-independent.** Traces arrive out of order across a distributed collector. A tool span may be processed before its causal parent's span. The repair logic must tolerate a dangling `call_id` reference and re-attach when the parent arrives, rather than resolving to "no parent" on first pass. When any condition fails, the pipeline must *refuse to emit a causal edge* and mark the span `causal_edge=unresolved`, rather than falling back to `parent_span_id`. The fallback is the failure: it manufactures a plausible edge from a non-causal field. ## Decision Boundary The boundary is between **structural parentage** (what `parent_span_id` says) and **causal parentage** (what `call_id` correspondence implies). The decision rule for the reconstruction layer: - If a tool span's `call_id` resolves to exactly one LLM span's `tool_calls[]` entry within the trace → the causal parent is that LLM span, **regardless of `parent_span_id`**. Record both: `causal_parent_id` and `structural_parent_id`, and a `edge_source=causal` flag. - If it resolves to zero (parent not yet arrived, or `call_id` not unique) → `causal_edge=unresolved`, defer, do not score. - If it resolves to more than one (duplicate `call_id`) → `causal_edge=ambiguous`, emit a hard signal to the eval hook to *suppress* attribution scoring for that span rather than pick one. The eval-in-production hook must gate on `edge_source=causal` and `causal_edge=resolved`. Any scoring path that reads `parent_span_id` to find "the reasoning that produced this tool call" is operating outside the boundary and will misattribute under concurrency. The hook must fail closed: a span with an unresolved or ambiguous causal edge contributes *no* attribution score and is counted in a separate `unattributed` bucket, never folded into the faithfulness denominator as a zero. ## Operational Effect Enforcing the invariant changes three behaviors. First, the phantom-regression class disappears: tool spans under worker-pool pressure no longer score `attribution=0.0`, because they either resolve causally or are excluded from the denominator. The faithfulness metric becomes stable across concurrency changes, which is what makes it usable as a model-upgrade gate. Second, the reconstruction pass must carry a deferred-resolution queue keyed by `call_id`, adding bounded memory (one entry per unresolved call, evicted on trace close or timeout) and a re-scan on parent arrival—a real cost, but the only way to be order-independent across a distributed collector. Third, the trace consumer contract changes: downstream eval hooks must accept `unattributed` spans as a first-class outcome and report the unattributed *rate* as a pipeline health metric. A rising unattributed rate is the early warning that `call_id` uniqueness or flush ordering has regressed—it is the observable that would have caught the original incident before the rollback. The general principle: in agent observability, the field that is *always present* (`parent_span_id`) is not the field that is *semantically correct* (the `call_id` correspondence). Pipelines that default to the always-present field produce complete, well-formed, silently wrong causal graphs. The invariant is that causal edges are derived from call-identity correspondence, never from execution-stack parentage, and that unresolved edges are surfaced as a distinct state rather than backfilled. ```python import re from dataclasses import dataclass, field class CausalEdgeError(RuntimeError): """Raised when a tool span cannot be causally linked to its LLM parent.""" pass @dataclass class ToolSpan: span_id: str call_id: str structural_parent_id: str causal_parent_id: str | None = None edge_state: str = "unresolved" # unresolved | resolved | ambiguous @dataclass class LLMSpan: span_id: str tool_call_ids: list[str] = field(default_factory=list) def resolve_causal_edge(tool: ToolSpan, llm_spans: list[LLMSpan]) -> ToolSpan: """Resolve a tool span's causal parent via call_id correspondence. Never falls back to structural_parent_id: that field reflects the execution stack (dispatcher/worker), not the reasoning that emitted the call, and using it manufactures a plausible-but-wrong edge. """ if not re.fullmatch(r"[A-Za-z0-9_\-]{8,}", tool.call_id): raise CausalEdgeError( f"tool span {tool.span_id}: call_id {tool.call_id!r} is not a " f"trace-unique identifier; per-turn counters violate the invariant" ) matches = [s for s in llm_spans if tool.call_id in s.tool_call_ids] if len(matches) == 0: # Parent may not have arrived yet (out-of-order collector). Defer. tool.edge_state = "unresolved" return tool if len(matches) > 1: # Duplicate call_id within trace: ambiguous, must suppress scoring. tool.edge_state = "ambiguous" return tool tool.causal_parent_id = matches[0].span_id tool.edge_state = "resolved" return tool def score_attribution(tool: ToolSpan, llm_spans: list[LLMSpan]) -> float | None: """Eval-in-production hook: attribution score, or None if not scorable.""" resolve_causal_edge(tool, llm_spans) if tool.edge_state != "resolved": # Fail closed: do not fold into the faithfulness denominator as 0.0. return None parent = next(s for s in llm_spans if s.span_id == tool.causal_parent_id) if not parent.tool_call_ids: raise CausalEdgeError( f"tool span {tool.span_id}: causal parent {parent.span_id} " f"has empty tool_calls[]; edge resolved against a truncated span" ) # ... faithfulness scoring against parent completion omitted ... return 1.0 ```