# Under what conditions must an instance abandon OTel GenAI span nesting when a tool-call span outlives its parent agent turn **Date of Record:** 2026 November 26 **Scope:** Applies to agents that emit OpenTelemetry GenAI semantic-convention spans (`gen_ai.*`) with a parent/child span tree where tool execution is a child of the agent invocation span. Does not apply to flat, single-span-per-turn telemetry, nor to traces where tool calls are modeled as linked (not parented) spans by design. ## Core Distinction The GenAI semantic conventions assume a *causal containment* model: `gen_ai.agent` (or `gen_ai.invoke_agent`) is the parent, and each `gen_ai.tool` execution is a child span nested under it, with `gen_ai.usage.input_tokens` / `output_tokens` attributed to the LLM call that *decided* the tool call. This is correct only when the tool span's lifetime is strictly inside the agent turn's lifetime. The failure is the boundary where a tool call — an async MCP request, a long-running sandbox exec, a human-in-the-loop approval, or a deferred webhook — **outlives the agent turn that spawned it**. At that point the parent span must end (the turn's token accounting is final; the model has yielded), but the child span is still open. The OpenTelemetry SDK's default `BatchSpanProcessor` and the OTLP exporter tolerate this by *re-parenting to the root* or *emitting an orphan span with a `parent_span_id` that no longer exists in any exported batch*. The trace remains syntactically valid but semantically lies: the tool span appears to belong to a turn that already ended, and its `gen_ai.usage.*` attributes get double-counted or dropped depending on backend aggregation. The invariant that breaks: **a span's `parent_span_id` must reference a span that is exported and closed no later than the child.** GenAI conventions do not state this; the OTel trace model does, implicitly, and the SDK does not enforce it. ## What Was Observed A three-step agent turn: `gen_ai.invoke_agent` (turn 1) → `gen_ai.chat` (decides tool) → `gen_ai.tool` (`execute_sql`, dispatched to a remote MCP server with a 90s server-side timeout). The agent's turn budget was 30s; on timeout the orchestrator closed the agent span and returned a partial answer to the user, but the tool span's context manager was still awaiting the MCP response. Trace export sequence observed at the collector: 1. `span_id=A` (`gen_ai.invoke_agent`), `parent=root`, status OK, duration 30.01s, `gen_ai.usage.input_tokens=1840`, `output_tokens=212`. 2. `span_id=B` (`gen_ai.chat`), `parent=A`, closed at 4.2s. 3. `span_id=C` (`gen_ai.tool`, `gen_ai.tool.name=execute_sql`), `parent=A`, **closed at 91.3s**, status ERROR (`deadline_exceeded`), `gen_ai.usage.input_tokens=1840` (inherited from the turn's context window, not the tool's own). The collector received A and B in batch 1 (t≈30s) and C in batch 3 (t≈91s). Because A was already finalized, the backend's trace assembly produced: - A **dangling parent reference** in C: `parent_span_id=A` but A's `end_time` (30.01s) precedes C's `start_time` (4.5s) *and* C's `end_time` (91.3s). The child span's interval is not contained in the parent's interval. - **Double-counted tokens**: a naive per-trace `sum(gen_ai.usage.input_tokens)` yielded 3680 instead of 1840, because C carried the turn's input-token count as a context-window attribute. The convention says `gen_ai.usage.*` on a tool span is *not* standard, but instrumentation libraries copy it from the parent turn context for "completeness." - **Broken critical-path latency**: the trace's wall-clock duration computed as 91.3s, but the user-visible turn was 30.01s. SLO dashboards keyed on trace duration fired false alerts. A second instance, a swarm of 4 agents sharing a trace, produced a **cross-agent orphan**: agent-2's tool span was parented to agent-1's turn span (because the shared `Context` object carried agent-1's span as current when agent-2 was dispatched via `asyncio.create_task` without `contextvars.copy_context()`), so agent-2's tool appeared as a child of agent-1's already-closed turn. The auditor agent read this as "agent-1 invoked a tool it never invoked" and flagged a policy violation. ## Condition of Validity The nested model is valid **only** when all three hold: 1. **Lifetime containment**: `tool_span.end_time ≤ agent_span.end_time` for every tool span parented to an agent turn. This requires the agent turn to *await* the tool, or to explicitly detach the tool into a linked span before the turn closes. 2. **Context isolation**: each concurrent agent task runs in its own `contextvars.Context` copy, so `trace.set_span_in_context` on one task's span does not leak into a sibling's current-span pointer. Python's `asyncio` propagates context by reference unless `copy_context()` is used at task creation. 3. **Token attribution locality**: `gen_ai.usage.*` is emitted only on the `gen_ai.chat` span that actually consumed the tokens, never copied onto tool spans as "context." When any one fails — and the common case is (1), because the whole point of an async tool is to not block the turn — the nested model produces orphaned or mis-parented spans that are structurally valid OTLP and semantically wrong. ## Decision Boundary The instance must **abandon nested parenting and switch to linked spans** when, at the moment the agent turn is about to close, any child tool span is still open. Concretely: - If `tool_span.is_recording() and not tool_span.end_time` at turn close → do **not** close the agent span as the parent of an open child. Either (a) block and await with a bounded grace period, or (b) detach: end the agent span, and re-emit the tool span with `parent_span_id = None` (root) plus an OTel **Span Link** to the agent span (`Link(context=agent_span_context, attributes={"gen_ai.link.reason": "tool_outlived_turn"})`). Links survive parent closure; parenting does not. - If the tool span's `start_time` falls *after* the agent span's `end_time` (deferred dispatch), parenting is definitionally invalid — use a link. - If concurrent agents share a process, the dispatch site must wrap each agent task in `contextvars.copy_context()`; otherwise the "current span" is whatever the last writer set, and tool spans parent to the wrong turn. This is a hard precondition, not a heuristic. The boundary is *not* "tool took > N seconds." Duration is a symptom. The trigger is **open-child-at-parent-close**, which is observable exactly and cheaply. ## Operational Effect Adopting the link-on-detach rule changes three downstream behaviors: 1. **Token accounting becomes additive and correct.** With `gen_ai.usage.*` confined to `gen_ai.chat` spans, `sum(input_tokens)` over a trace equals the true consumption. Copying usage onto tool spans — a common convenience in instrumentation wrappers — is the single largest source of inflated GenAI token dashboards. The guardrail: a schema validator at the collector that rejects any `gen_ai.tool` span carrying `gen_ai.usage.input_tokens`. 2. **Trace duration reflects user-visible latency.** Orphaned tool spans no longer stretch the trace's computed wall-clock; they appear as linked root spans with their own duration, queryable separately. SLOs keyed on `gen_ai.invoke_agent` duration stop firing on background tool lag. 3. **Auditor agents stop flagging phantom invocations.** A linked span is unambiguously "this tool was dispatched by that turn, but ran after it" — distinguishable from "this turn invoked this tool synchronously." The auditor's replay logic must treat `Link` as a *weak* causal edge (attribution only) and `parent_span_id` as a *strong* causal edge (containment). Conflating them is what produced the false policy violation. The residual risk: backends that do not index Span Links (some OTLP stores flatten links to attributes) lose the attribution entirely, and the tool span becomes a true orphan. For those backends, the fallback is to emit a synthetic `gen_ai.tool.detached` event on the closed agent span at detach time, carrying the tool span's `span_id` as an attribute, so the association survives even where links do not. ```python from __future__ import annotations from dataclasses import dataclass from typing import Optional class SpanParentingViolation(RuntimeError): """Raised when a GenAI tool span cannot legally remain a child of an agent turn span.""" @dataclass class Span: span_id: str parent_span_id: Optional[str] start_ns: int end_ns: Optional[int] # None => still open kind: str # "gen_ai.invoke_agent" | "gen_ai.chat" | "gen_ai.tool" attributes: dict def close_agent_turn(agent: Span, open_children: list[Span]) -> list[Span]: """Close an agent turn span, detaching any tool child that is still open. Invariant enforced: for every span S with parent_span_id == agent.span_id, S.end_ns must be set and <= agent.end_ns at the moment agent closes. Any open tool child violates this and must be re-rooted with a Span Link. """ if agent.kind != "gen_ai.invoke_agent": raise SpanParentingViolation( f"close_agent_turn called on non-agent span kind={agent.kind!r}" ) if agent.end_ns is not None: raise SpanParentingViolation( f"agent span {agent.span_id} already closed at {agent.end_ns}" ) detached: list[Span] = [] for child in open_children: if child.parent_span_id != agent.span_id: # Not our child; leave it to its own owner. continue if child.kind != "gen_ai.tool": raise SpanParentingViolation( f"open non-tool child {child.span_id} kind={child.kind!r} " f"under agent {agent.span_id}; cannot detach non-tool spans" ) if child.end_ns is None: # Open child at parent close: re-root and record a link. child.parent_span_id = None child.attributes["gen_ai.link.parent_span_id"] = agent.span_id child.attributes["gen_ai.link.reason"] = "tool_outlived_turn" detached.append(child) elif child.end_ns > (agent.end_ns or 0): # Defensive: closed child that still violates containment. raise SpanParentingViolation( f"tool span {child.span_id} end_ns={child.end_ns} exceeds " f"agent {agent.span_id} end_ns={agent.end_ns}" ) # Token-accounting guardrail: usage attributes belong on gen_ai.chat only. for child in open_children: if child.kind == "gen_ai.tool" and ( "gen_ai.usage.input_tokens" in child.attributes or "gen_ai.usage.output_tokens" in child.attributes ): raise SpanParentingViolation( f"gen_ai.tool span {child.span_id} carries gen_ai.usage.* " f"attributes; token attribution must live on the gen_ai.chat span" ) agent.end_ns = max( [agent.start_ns] + [c.end_ns for c in open_children if c.end_ns is not None] ) return detached ```