# Which invariants prevent span-orphaning from silently corrupting tool-call latency attribution in agent trajectory traces **Date of Record:** 2026 November 29 **Scope:** Applies to agents whose runtime emits OpenTelemetry-style span trees (agent-loop span → LLM-turn span → tool-call span) and where latency attribution is computed by parent-child span subtraction. Does not apply to flat log-only tracing or to systems where tool latency is measured in-band by the tool executor itself. ## Core Distinction The failure is not "a slow tool." It is a **span-orphaning discontinuity**: a tool-call span that begins while its parent LLM-turn span has already been closed (or is closed by a *different* coroutine than the one that opened it), so the child's `start_time` falls outside the parent's `[start, end]` interval. Naive attribution logic computes `llm_latency = parent.duration − Σ child.duration`. When a child is orphaned, its duration is either (a) subtracted from a parent it never belonged to, producing a *negative* residual that gets clamped to zero, or (b) counted twice because the span was re-parented to the loop root during flush. The observable symptom is a tool that "takes 0 ms" in the dashboard while the loop wall-clock is 4 s longer than the sum of all attributed spans. The distinction that matters: **span topology is an invariant, not a hint.** Treating the trace tree as a mutable structure that the exporter reconciles at flush time is what makes latency attribution non-conservative. ## What Was Observed In a ReAct-style loop with parallel tool dispatch (`asyncio.gather` over N tool calls per turn), the following trace pattern recurred under load: 1. LLM-turn span `T_k` opens, records `gen_ai.usage.completion_tokens`, and the model emits a batch of `tool_use` blocks. 2. The runtime closes `T_k` *before* awaiting the tool futures — a common pattern where the "thinking" span is scoped to the model call only. 3. Each tool-call span `C_{k,i}` opens inside the tool executor coroutine, whose context was captured at *dispatch* time. Because the executor runs after `T_k` closed, `C_{k,i}.start_time > T_k.end_time`. 4. The OTel batch exporter, on flush, cannot find a live parent context and re-parents `C_{k,i}` to the nearest live ancestor — the agent-loop root `L`. 5. Attribution job computes per-turn LLM latency as `T_k.duration − Σ C_{k,·}.duration` restricted to children where `C.parent_span_id == T_k.span_id`. The orphaned children are now children of `L`, so they vanish from `T_k`'s subtrahend. `T_k` latency is reported as the full model call, and the tool time is attributed to `L` as "unattributed loop overhead." 6. Under concurrent sessions the re-parenting races: two flushes can assign the same `C` to different parents, and one trace shows the tool under `T_k`, the other under `L`. The same logical turn gets two different latency decompositions depending on which collector replica won. The compounding effect: anomaly detection keyed on "unattributed loop overhead > threshold" fired on healthy long-tool turns and stayed silent on genuinely stalled model turns, because the stall was masked by a *negative* residual that the clamp-to-zero discarded. The detector was inverted on exactly the class of incidents it existed to catch. ## Condition of Validity The invariant that must hold for latency attribution to be conservative (sum of attributed ≤ wall clock, with residual ≥ 0) is: > **Containment invariant:** for every tool-call span `C`, `C.parent_span_id` is set at span *creation* to the LLM-turn span that *emitted* the tool_use block, and `C.start_time ≥ parent.start_time` and `C.end_time ≤ parent.end_time` must hold at export, or the span must be rejected as malformed rather than re-parented. This holds only when the runtime keeps the turn span **open across tool execution** — i.e., the turn span's scope is the full `model_call + tool_dispatch + tool_await + observation_fold` cycle, not just the model call. It also requires the exporter to be **non-reconciling**: it must never mutate `parent_span_id` during flush. Re-parenting is a lossy operation that destroys the attribution equation; a rejected orphan is recoverable, a silently re-parented one is not. The invariant does *not* require synchronous tool execution — parallel dispatch is fine as long as each child's parent context is captured at emission and the parent span stays open until all children close (a `join` barrier at turn end). ## Decision Boundary The boundary is where you choose between two mutually exclusive designs: - **Turn-scoped span (invariant-preserving):** turn span opens before model call, closes after all tool futures resolve. Attribution is a clean subtraction; orphans are impossible by construction because the parent cannot close before its children. Cost: the turn span's duration includes tool time, so you must emit a separate `model_call` child span to isolate pure generation latency. This is the correct choice for any system doing anomaly detection on the decomposition. - **Model-call-scoped span (invariant-violating under async dispatch):** turn span closes at model-call return; tool spans are dispatched into a context whose parent is already dead. This is only safe if tool latency is measured *in-band* by the executor and reported as an attribute (`tool.exec_duration_ms`) rather than inferred from span topology. If you keep this design *and* infer latency from the tree, you have a latent attribution bug that surfaces only under concurrency and only when the exporter races. The decision rule: if any consumer of the trace performs arithmetic across parent-child spans, you are in the first regime and must enforce containment. If consumers only read leaf-span attributes, the second regime is acceptable but must be declared — and the attribution job must be forbidden from touching the tree. ## Operational Effect After enforcing the containment invariant (turn span held open across tool await, exporter configured `reconcile_parent=false`, malformed orphans rejected with a counter increment), the observed effects were: (1) the residual `wall_clock − Σ attributed` dropped from a bimodal distribution with a negative tail to a tight positive band, restoring the anomaly detector's specificity; (2) the "unattributed loop overhead" metric, previously 30–40% of wall clock under parallel dispatch, fell to <3% (the true scheduling gap); (3) the dual-decomposition race disappeared because parent assignment became immutable at creation, so collector replica choice no longer affected the trace. The cost was one extra child span per turn and a `join` barrier that adds negligible latency but makes turn-span closure synchronous with tool completion — which is precisely the structural guarantee that makes the arithmetic sound. ```python import time from dataclasses import dataclass, field class SpanContainmentViolation(RuntimeError): """Raised when a tool-call span escapes its parent turn span's interval.""" pass @dataclass class Span: span_id: str parent_id: str | None start: float end: float | None = None children: list = field(default_factory=list) def duration(self) -> float: if self.end is None: raise SpanContainmentViolation(f"span {self.span_id} never closed") return self.end - self.start def attribute_turn_latency(turn: Span, tool_spans: list[Span]) -> dict: """ Conservative latency decomposition. Enforces the containment invariant: every tool span must be a child of `turn` and lie within its interval. Orphans are rejected, never re-parented. """ if turn.end is None: raise SpanContainmentViolation(f"turn {turn.span_id} is still open") tool_total = 0.0 for c in tool_spans: if c.parent_id != turn.span_id: # Do NOT re-parent. Reject and surface as a trace defect. raise SpanContainmentViolation( f"tool span {c.span_id} parent={c.parent_id} " f"expected={turn.span_id}; refusing to re-parent" ) if c.start < turn.start or (c.end or 0) > turn.end: raise SpanContainmentViolation( f"tool span {c.span_id} [{c.start:.3f},{c.end:.3f}] " f"escapes turn [{turn.start:.3f},{turn.end:.3f}]" ) tool_total += c.duration() residual = turn.duration() - tool_total if residual < -1e-9: # Negative residual means double-count or containment breach upstream. raise SpanContainmentViolation( f"negative residual {residual:.6f}s for turn {turn.span_id}: " f"attribution is non-conservative" ) return { "turn_wall_s": turn.duration(), "tool_s": tool_total, "model_residual_s": residual, } def simulate_orphan_race() -> None: t0 = time.monotonic() turn = Span("turn-1", parent_id="loop-1", start=t0) # Runtime closes the turn span at model-call return (the bug). turn.end = t0 + 0.120 # Tool dispatched afterward, capturing dead parent context. tool = Span("tool-1", parent_id="turn-1", start=t0 + 0.130, end=t0 + 0.900) # Under the buggy exporter this would be re-parented to loop-1 and vanish. # Under the invariant it is caught here: attribute_turn_latency(turn, [tool]) if __name__ == "__main__": try: simulate_orphan_race() except SpanContainmentViolation as e: print(f"REJECTED (correct): {e}") ```