# Where must an instance reconcile OpenTelemetry GenAI span closure against a still-running tool call, and why does the parent span lie? **Date of Record:** 2026 December 2 **Scope:** Applies to agents that emit spans per the OpenTelemetry GenAI semantic conventions (`gen_ai.operation.name`, `gen_ai.tool.name`, `gen_ai.usage.input_tokens`/`output_tokens`, `gen_ai.agent.*`) where a tool call is dispatched asynchronously or across a transport boundary (MCP, A2A) and the LLM turn that requested it can complete before the tool result returns. Does not apply to strictly synchronous single-process tool invocation where the tool completes inside the same span's lifetime. ## Core Distinction The GenAI conventions treat a *model turn* and a *tool execution* as distinct operations with distinct spans: an `gen_ai.operation.name = "chat"` span (or `"execute_tool"`) with `gen_ai.tool.name` and `gen_ai.tool.call.id` attributes. The convention is silent on the ownership of the *tool span's parent*. Operators routinely attach the tool span as a child of the chat span that emitted the call, because that is where the call originated. This is correct only when the tool returns before the chat span ends. When the tool is dispatched over a transport (MCP `tools/call`, A2A task) and the model turn ends first—which is the normal case for long-running tools or streaming turns—the chat span closes, and the tool span's `parent_span_id` now points at a *closed, exported* span. The result is a trace that is structurally valid (IDs resolve) but semantically inverted: the parent's duration and token metrics describe a turn that "finished," while a descendant continues to execute and will eventually report latency and possibly additional tokens that no ancestor accounts for. This is non-obvious because nothing errors. The OTLP exporter ships both spans. The backend renders a tree. The failure is a *continuity invariant* violation: the parent span's end timestamp precedes the child span's start timestamp, and the child's `gen_ai.usage` tokens are orphaned from any turn-level aggregate. ## What Was Observed A three-step agent loop: `chat` span → `execute_tool` span (MCP `tools/call` to a remote filesystem server) → `chat` span. The tool was a recursive directory walk over a large tree; median latency 40s, p99 180s. The model turn had a 30s streaming timeout and emitted `finish_reason = "tool_calls"` at ~2s, closing the chat span. Trace inspection showed: - Chat span `S1`: `start=0ms`, `end=2100ms`, `gen_ai.usage.output_tokens=412`. - Tool span `T1`: `parent_span_id = S1.span_id`, `start=2050ms`, `end=41000ms`, `gen_ai.tool.name="fs.walk"`. - Chat span `S2` (the turn that consumed the tool result): `start=41050ms`, `end=43000ms`, `parent_span_id = root`. Two defects surfaced. First, `T1.start (2050ms) < S1.end (2100ms)` but `T1.end (41000ms) > S1.end`—the child outlives the parent, so any duration aggregation that sums child spans under `S1` produces a parent duration that is *shorter than its own subtree*, breaking the standard "parent duration ≥ sum of child critical path" assumption used by trace-based SLO calculators. Second, `S2`'s parent is the root, not `T1` or `S1`, so the causal chain `S1 → T1 → S2` is broken: the trace backend cannot attribute `S2`'s `input_tokens` to the tool result that produced them, and a token-accounting query that walks from root sees `S1` and `S2` as siblings with no linkage to `T1`'s 41s latency. A second observation: when the tool call was retried after an MCP transport timeout, a second `execute_tool` span `T1'` was emitted with a *new* `gen_ai.tool.call.id` but the *same* parent `S1`. Because `S1` was already closed and exported, the retry span arrived at the collector after `S1`'s export batch had flushed. Backends that assume parent-before-child arrival order (a common sampling and tail-aggregation assumption) either dropped `T1'` or attached it to a synthetic orphan root, silently detaching the retry from its logical parent. ## Condition of Validity The invariant that must hold for the "tool span is a child of the chat span" model to be sound is: > For every `execute_tool` span `T` with parent chat span `S`, `T.end ≤ S.end` and `T` is exported before or in the same batch as `S`. This holds only when the tool is synchronous and bounded by the model turn. It is violated whenever any of the following is true: (a) the tool is dispatched over a transport that decouples request from response (MCP, A2A, any queue), (b) the model turn has a completion deadline shorter than the tool's p99, (c) the tool is retried after the parent has closed, or (d) the agent resumes a task across a process boundary and re-emits a tool span whose logical parent lives in a prior process's trace. Condition (d) is the sharpest: on cold-start resume, the new process has no live parent span, so it either fabricates a `parent_span_id` from a serialized checkpoint (pointing at a span the new process never created and cannot close) or attaches to root, severing causality. ## Decision Boundary The boundary is *span ownership at dispatch versus at completion*. Two architectures are valid; the choice is forced by whether the tool can outlive the turn. - **Parent-at-dispatch (default, wrong for async):** tool span is a child of the chat span. Valid only under the Condition of Validity above. Use when the tool is in-process and bounded. - **Parent-at-completion (correct for async):** the tool span's parent is the *agent/session* span (a long-lived `gen_ai.agent.*` span or an explicit `invoke_agent` span), not the chat turn. The chat turn links to the tool via a span *link* (`SpanLink` with `gen_ai.tool.call.id`), not a parent-child edge. The tool result then opens the next chat span as a sibling under the agent span, with a link back to `T1`. This preserves the invariant "parent outlives child" because the agent span is open for the session's lifetime. The decision rule: if `tool.p99_latency > turn.deadline` OR the tool crosses a transport boundary OR the agent supports resume, the tool span MUST be parented to the agent span and linked to the requesting turn, never nested under it. The `gen_ai.tool.call.id` attribute is the join key in both models; the difference is whether it is expressed as a parent edge or a link. A guardrail is required because the failure is silent. At span close, assert `child.end ≤ parent.end` for every parent-child edge; if violated, the emitter must either re-parent to the agent span or emit an explicit anomaly attribute (`gen_ai.tool.outlived_turn = true`) so downstream aggregation can exclude the subtree from turn-level duration sums. For resume, the checkpoint must serialize the *agent span context* (trace ID + agent span ID), not the chat span ID, so the resumed process can attach with a valid, still-open parent or a link. ## Operational Effect Without the guardrail, three concrete degradations follow. (1) Trace-based latency SLOs under-report: the 41s tool latency is invisible to any query that sums turn durations, because the tool span's parent closed at 2.1s and the subtree is excluded from the turn's critical path. (2) Token accounting double-counts or orphans: `S2`'s input tokens (which include the tool result) are attributed to root, not to the tool that produced them, so cost-per-tool-call is uncomputable. (3) Retry spans detach: a retried `execute_tool` after parent closure lands as an orphan, and tail-sampling policies that key on trace completeness drop it, so the retry's latency and failure are invisible in the very traces meant to diagnose the timeout. With the agent-span-parenting model, the agent span remains open across the tool's lifetime, the child-outlives-parent invariant holds by construction, retries attach as siblings under the same open agent span, and resume re-attaches via the serialized agent span context. The cost is that turn-level duration must be computed by summing *linked* chat spans rather than by walking a parent-child subtree—a query change, not a data change. ```python from dataclasses import dataclass from typing import Optional class SpanClosureInvariantError(RuntimeError): """Raised when a tool span would outlive or detach from its parent span.""" pass @dataclass class Span: span_id: str parent_span_id: Optional[str] operation: str # "chat" | "execute_tool" | "invoke_agent" start_ms: int end_ms: Optional[int] = None tool_call_id: Optional[str] = None def close_tool_span(tool: Span, parent: Span, turn_deadline_ms: int) -> Span: if tool.parent_span_id != parent.span_id: raise SpanClosureInvariantError( f"tool {tool.span_id} parent {tool.parent_span_id} != {parent.span_id}" ) if parent.end_ms is not None and tool.end_ms is not None and tool.end_ms > parent.end_ms: # child outlived a closed parent: causality and SLO aggregation both break raise SpanClosureInvariantError( f"tool {tool.span_id} end={tool.end_ms} exceeds closed parent " f"{parent.span_id} end={parent.end_ms}; re-parent to agent span and link " f"via tool_call_id={tool.tool_call_id}" ) if tool.end_ms is not None and tool.end_ms - tool.start_ms > turn_deadline_ms: raise SpanClosureInvariantError( f"tool {tool.span_id} duration exceeds turn deadline; " f"must be parented to invoke_agent span, not chat turn" ) return tool def on_resume(checkpoint_agent_span_id: Optional[str], new_tool: Span) -> Span: if checkpoint_agent_span_id is None: raise SpanClosureInvariantError( f"resume of tool {new_tool.span_id} has no serialized agent span context; " f"parent would dangle across process boundary" ) new_tool.parent_span_id = checkpoint_agent_span_id return new_tool ```