# How should an instance reconcile GenAI semantic-convention spans when a tool-call child span outlives its parent agent span **Date of Record:** 2026 November 20 **Scope:** Applies to any agent runtime that emits OpenTelemetry spans under the `gen_ai.*` semantic conventions (agent invocation spans, tool-call spans, and token-usage attributes) and that can emit a tool-call child span whose completion timestamp exceeds its parent agent invocation span. Does not apply to single-shot, non-tool-using LLM calls, nor to runtimes that hard-cancel child spans synchronously with the parent. ## Core Distinction The GenAI semantic conventions treat token accounting and tool-call identity as *attributes on spans*, not as independent events. A tool-call span (`gen_ai.operation.name = "execute_tool"`) is modeled as a child of the agent invocation span (`gen_ai.operation.name = "invoke_agent"`), and usage is recorded via `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens` on the *generation* span that produced the tool request. The convention implicitly assumes a **temporal containment invariant**: a child span's `end_time` is ≤ its parent's `end_time`, and all token-usage attributes attributable to a turn land on spans that are closed before the parent closes. The non-obvious boundary is that agent runtimes routinely violate this invariant *by design*. A tool call (shell exec, HTTP fetch, long-poll, human-in-the-loop approval) can block for minutes after the model has already returned the tool-call request and the parent turn has been considered "complete." The runtime closes the parent agent span, exports it, and *then* the tool span finishes and exports — with an end timestamp strictly greater than its parent's. This is not a bug in the tracer; it is a genuine race between the agent's logical turn boundary and the tool's physical execution boundary. The failure is not "spans are missing." It is that **downstream aggregation of token usage and tool-call latency becomes silently wrong**: a trace consumer that reconstructs per-turn cost by summing `gen_ai.usage.*` over the subtree rooted at the agent span will either drop the late tool span (if it prunes by parent end_time) or double-count it (if it re-attaches by trace_id after the fact). Neither the convention nor most backends specify which. ## What Was Observed A three-tool agent turn (search → fetch → summarize) on a runtime that closes the agent span at the model's final `stop_reason = "tool_use"` boundary rather than at tool completion: 1. `invoke_agent` span opens at t=0, `gen_ai.usage.input_tokens=1840`, `output_tokens=212` recorded on the first generation child. 2. Generation child emits `tool_use` for `search`; model returns. Runtime marks the turn complete, closes `invoke_agent` at t=4.1s. 3. `execute_tool` span for `search` opens at t=2.9s, closes at t=31.7s — **27.6s after its parent closed**. 4. A second `invoke_agent` span opens at t=31.8s to consume the tool result, with its own usage attributes. 5. The trace backend, on ingestion, applies a "late child" policy: it re-parents the orphaned `execute_tool` span to the *next* `invoke_agent` span in the same trace (the one that consumed the result), because that is the only open parent at ingestion time. Result: tool-call latency (27.6s) is attributed to the *second* turn, whose own generation latency was 3.2s. The second turn's p99 latency in dashboards inflated from ~3s to ~30s. Token usage was correctly attributed (it lives on generation spans, which closed in time), but the *cost-per-latency* ratio — the metric ops teams actually watch — was off by an order of magnitude. Worse, the re-parenting is non-deterministic: if the second `invoke_agent` had not yet opened at ingestion, the tool span would instead be dropped as an orphan root, and the latency would vanish entirely. ## Condition of Validity The containment invariant holds — and the convention's accounting is sound — only when **all three** of the following are true: - The runtime closes the parent agent span *after* all synchronous tool calls it spawned have closed, **or** the runtime explicitly marks the turn as "tool-pending" and defers parent closure. - The trace backend does not re-parent late children; it either keeps them as trace-root orphans or attaches them by an explicit `gen_ai.tool.call.id` link attribute rather than by temporal proximity. - Token-usage attributes are recorded on generation spans that are guaranteed closed before the parent, which is true only if the generation span is a *sibling* of the tool span, not a child of the tool span. If any one fails, subtree-summed usage and latency are unreliable. The invariant is *not* "spans must nest perfectly" — it is "the parent's end_time must be a sound upper bound on the end_time of every span whose attributes you intend to aggregate into that parent." ## Decision Boundary The decision is whether to (a) enforce containment by deferring parent closure until tool completion, or (b) break containment explicitly and make the break legible to consumers. The boundary condition: - **Enforce containment (a)** when the tool call is bounded and short (< the parent turn's own deadline) and when the trace is consumed by subtree-summing aggregators you control. Cost: the parent span's duration now includes tool wall-clock, so `invoke_agent` latency conflates model time with tool time — a different distortion. - **Break containment (b)** when tools are unbounded, human-gated, or long-polling, and when the consumer set is heterogeneous. This requires emitting an explicit correlation attribute — `gen_ai.tool.call.id` on both the tool span and the generation span that requested it — so consumers join by ID, never by parent/child or by temporal adjacency. The parent must set `gen_ai.agent.turn.status = "tool_pending"` before closing, so a consumer knows the turn is not actually complete. The invariant that must be preserved under (b): **every tool span carries a correlation ID that a consumer can use to find its requesting generation span without relying on span nesting or timestamps.** If that ID is absent, the late span is unrecoverable and must be dropped rather than guessed at. ## Operational Effect Under (a), per-turn latency is inflated by tool wall-clock; token-per-second metrics computed as `output_tokens / span_duration` are systematically depressed for tool-heavy turns. Under (b), subtree-summed usage is correct only if consumers join by `gen_ai.tool.call.id`; any consumer that sums by parent/child will under- or over-count depending on ingestion order, and the error is *non-deterministic across replays of the same trace*. The operational consequence is that a trace is not a stable artifact: re-ingesting the same span set under a different arrival order yields different aggregate token and latency numbers. Any alerting or billing pipeline built on subtree sums must be pinned to a correlation-ID join, and the runtime must be audited to confirm that no tool span can export without its correlation ID set. The guardrail is a validator that rejects export of an `execute_tool` span lacking `gen_ai.tool.call.id`, and a parent-closure check that refuses to close an `invoke_agent` span while any child tool span with a matching turn ID is still open. ```python class OrphanedToolSpanError(RuntimeError): """Raised when a tool-call span would export without a resolvable parent correlation, violating the GenAI containment-or-correlation invariant.""" pass def close_agent_span(span, open_tool_children: list[dict]) -> None: """Close an invoke_agent span only if every tool child is either closed or carries a correlation ID that lets consumers join without nesting.""" for child in open_tool_children: if child["status"] == "open": raise OrphanedToolSpanError( f"cannot close agent span {span['span_id']}: " f"tool span {child['span_id']} still open with no " f"completion boundary; defer closure or mark tool_pending" ) if not child.get("gen_ai.tool.call.id"): raise OrphanedToolSpanError( f"tool span {child['span_id']} lacks gen_ai.tool.call.id; " f"late export would be unrecoverable by correlation join" ) span["end_time"] = max( [span["end_time"]] + [c["end_time"] for c in open_tool_children] ) span["attributes"]["gen_ai.agent.turn.status"] = "complete" ```