# How should an instance reconcile OpenTelemetry GenAI span closure when a tool-call child span outlives its parent agent span **Date of Record:** 2026 November 24 **Scope:** Applies to any agent runtime that emits OTel GenAI spans (`gen_ai.operation.name`, `gen_ai.tool.name`, `gen_ai.usage.input_tokens`/`output_tokens`) where tool invocations are modeled as child spans of an agent/LLM span and the tool executes asynchronously (streaming, long-poll, human-in-the-loop, or MCP round-trip). Does not apply to fully synchronous, single-threaded tool dispatch where the child span is guaranteed to end before the parent returns. ## Core Distinction The GenAI semantic conventions treat token usage as an attribute of the *operation* span (`gen_ai.usage.*`), and tool calls as *separate* child spans carrying `gen_ai.tool.name` and `gen_ai.tool.call.id`. This is coherent only if the parent operation span's lifetime strictly encloses every tool span it spawned. The boundary condition is when it does not: an agent span is closed (its `end_time` stamped, attributes frozen, exported) while a tool span it created is still running. The exporter then emits a child whose `parent_span_id` references a span that has already left the collector's window, and whose own token/timing attributes can no longer be attributed to any completed operation. The distinction that matters operationally is between **span ordering** (a property of wall-clock emission) and **causal containment** (a property of the trace tree). OTel's data model assumes the latter; the agent runtime only guarantees the former. Every reconciliation bug in this article lives in that gap. ## What Was Observed A multi-step agent executing a plan emitted, per step, one `gen_ai.operation.name=chat` span with `gen_ai.usage.output_tokens` set at response completion, and one child span per tool call (`gen_ai.operation.name=execute_tool`, `gen_ai.tool.name=search_index`). The tool was an MCP round-trip with a 4–11s tail latency. The agent span was closed as soon as the model returned the tool-call request — *before* dispatch — because the runtime treated "model done producing this turn" as "operation complete." Consequences observed in the collector: 1. **Orphaned tool spans.** Tool spans arrived 4–11s after their parent was exported. The collector's parent-lookup missed; the span was recorded as a root with `parent_span_id` dangling. Trace trees rendered two disconnected fragments per step. 2. **Token double- or under-count.** The parent's `gen_ai.usage.output_tokens` counted only the model's tool-call *request* tokens. The tool's *result* was fed back into a *new* chat span on the next step, but the runtime reused the same logical `gen_ai.conversation.id` with a fresh `gen_ai.usage.input_tokens` that included the full replayed context. Per-step sums therefore over-counted input (context replayed every turn) while the "operation" granularity implied by the spans under-counted output (tool-result tokens attributed to no tool span at all, since `execute_tool` spans carry no token attributes by convention). 3. **Latency attribution collapse.** p99 of the `chat` span was ~800ms; end-to-end task latency was ~40s. Dashboards keyed on `gen_ai.operation.name=chat` reported a healthy system while the actual bottleneck (tool tail) was invisible because it lived in orphaned spans the query filtered out. The failure is silent. No OTel validation rejects a child span whose parent has ended — the spec permits it; the *semantic conventions'* implicit containment invariant does not. ## Condition of Validity The convention that "tool-call spans are children of the operation span that requested them, and operation token usage is attributable to that span" holds **iff** the parent span's `end_time` is stamped no earlier than the maximum `end_time` of all descendant spans created during that operation. Formally, for operation span `P` and its spawned tool spans `T_i`: ``` P.end_time >= max(T_i.end_time) for all i spawned by P ``` and the parent must not be exported until that predicate is satisfiable. This is a *containment* invariant, not a *causality* invariant — OTel context propagation preserves causality (the child knows its parent) regardless of ordering, which is precisely why the violation is not caught. The runtime must enforce containment itself, because the SDK will happily serialize a child after its parent. Two corollaries that bound where this applies: - If tool execution is **synchronous and inline** (parent blocks on the call), containment is automatic and this record does not apply. - If tool spans are emitted as **links** (`SpanLink`) rather than children — a legitimate pattern for fire-and-forget async work — then containment is *deliberately* not claimed, and token accounting must move to an explicit `gen_ai.usage` aggregate on a wrapping span. Mixing child-spans for some tools and links for others within one operation is the worst case: it produces a trace tree that *looks* contained but is not. ## Decision Boundary The instance must choose, at the moment the model returns a tool-call request, between two span topologies. The decision is forced by whether the tool can complete within the operation's semantic unit: - **Close-parent-now (fire-and-forget):** correct only if the tool span is emitted as a `SpanLink` and token/latency accounting is hoisted to a parent *task* span that encloses the whole plan. Choose this when tools are genuinely detached (webhooks, human approval queues) and the "operation" is the dispatch, not the result. - **Hold-parent-open (containment):** correct when the tool result will be consumed by the same logical operation (the next model turn depends on it). The parent span must not be ended until all `T_i` have ended *and* their results have been folded into the operation's accounting. Choose this for any synchronous-dependency tool, which is the common case. The boundary is crossed — and the bug introduced — whenever the runtime picks close-parent-now for a synchronous-dependency tool. That is the exact misconfiguration observed: the runtime optimized for low span latency (don't hold spans open across I/O) without checking whether the tool's result was a dependency of the operation. A guardrail that bounds it: before ending an operation span, the runtime must assert `open_child_count == 0`. If nonzero and the children are dependency-tools, it must either wait or *convert* the topology (re-parent the pending tools under a task span and mark the operation span with `gen_ai.operation.status=incomplete`). Silently ending with open dependency-children must raise. ## Operational Effect With containment enforced, three downstream properties become true that were false before: 1. **Trace trees are single-rooted per task.** No orphan fragments; `parent_span_id` always resolves within the exported window because the parent outlives its children by construction. 2. **Token accounting is closed.** `sum(gen_ai.usage.input_tokens + output_tokens)` over the subtree of a task span equals the task's true token cost, with no double-count from context replay *if* the runtime also deduplicates replayed input (a separate invariant: mark replayed context with `gen_ai.usage.input_tokens` only on the turn that first admitted it, or emit a `context.replay_tokens` attribute so aggregations can subtract). 3. **Latency attribution is honest.** The critical path is `max` over the containment tree, so the tool tail is visible in the same query that reports model latency. The cost is that operation spans now have long, I/O-bound lifetimes, which stresses exporter batching and can exceed collector `batch_timeout`. The mitigation is a task-level span that owns the long lifetime, with operation spans nested inside it and closed promptly — containment is enforced at the *task* level, not necessarily at every operation level. The invariant to carry forward: **a span may end only when no dependency-child it spawned is still open; if it cannot wait, it must not claim parentage.** ```python import time from dataclasses import dataclass, field from typing import Optional class SpanContainmentViolation(RuntimeError): """Raised when an operation span is ended while a dependency tool span it spawned is still open, breaking the GenAI containment invariant.""" pass @dataclass class GenAISpan: name: str operation: str # gen_ai.operation.name parent_id: Optional[str] = None span_id: str = "" end_time: Optional[float] = None is_dependency_tool: bool = False input_tokens: int = 0 output_tokens: int = 0 open_children: set = field(default_factory=set) class ContainmentEnforcingTracer: def __init__(self): self._spans: dict[str, GenAISpan] = {} self._seq = 0 def start_operation(self, name: str, parent_id: Optional[str] = None) -> GenAISpan: self._seq += 1 span = GenAISpan(name=name, operation="chat", parent_id=parent_id, span_id=f"s{self._seq}") self._spans[span.span_id] = span if parent_id and parent_id in self._spans: self._spans[parent_id].open_children.add(span.span_id) return span def start_tool(self, parent: GenAISpan, tool_name: str, dependency: bool = True) -> GenAISpan: self._seq += 1 span = GenAISpan(name=f"execute_tool:{tool_name}", operation="execute_tool", parent_id=parent.span_id, span_id=f"s{self._seq}", is_dependency_tool=dependency) self._spans[span.span_id] = span parent.open_children.add(span.span_id) return span def end_tool(self, span: GenAISpan) -> None: span.end_time = time.time() if span.parent_id: self._spans[span.parent_id].open_children.discard(span.span_id) def end_operation(self, span: GenAISpan) -> None: # Invariant: no dependency-child may remain open at parent end. still_open = [ cid for cid in span.open_children if self._spans[cid].is_dependency_tool and self._spans[cid].end_time is None ] if still_open: raise SpanContainmentViolation( f"operation span {span.span_id} ({span.name}) ended with " f"{len(still_open)} open dependency tool spans: {still_open}. " f"Either hold the parent open, or re-parent tools under a task " f"span and mark gen_ai.operation.status=incomplete." ) span.end_time = time.time() # --- trigger trace: the misconfiguration observed in production --- tracer = ContainmentEnforcingTracer() op = tracer.start_operation("step-1") tool = tracer.start_tool(op, "search_index", dependency=True) # Runtime closes the operation as soon as the model returns the tool request, # before the MCP round-trip has completed: try: tracer.end_operation(op) except SpanContainmentViolation as e: print("BLOCKED:", e) # Correct remediation: do not end op; wait for tool, then fold tokens. tracer.end_tool(tool) op.output_tokens += 0 # tool-result tokens attributed on next turn tracer.end_operation(op) print("contained: op closed after tool, tree single-rooted") ```