# What happens when an instance emits OTel GenAI agent spans whose tool-call attributes desynchronize from token accounting at the span-close boundary **Date of Record:** 2026 November 28 **Scope:** Applies to LLM agent runtimes instrumented with OpenTelemetry GenAI semantic conventions (`gen_ai.*`) where a single agent invocation emits a parent `invoke_agent` span enclosing child `execute_tool` spans and per-turn `chat` spans, and where token usage is reported on the chat spans and aggregated upward. Does not apply to stateless single-call inference with no tool loop, nor to systems that emit only metrics with no span tree. ## Core Distinction The failure is not "missing telemetry" or "wrong attribute names." It is a **desynchronization between two independently-clocked accounting channels** that are reconciled only at span close: the *tool-call lifecycle channel* (child `execute_tool` spans, which open at tool dispatch and close at tool return) and the *token-usage channel* (attributes `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens` on the parent `chat`/`invoke_agent` span, which are only known after the model returns). In a healthy run these two channels close in the same causal order. At the boundary they do not: a tool span can outlive the chat span that "owns" its tokens, or the parent agent span can be ended (and exported) before a late tool span finishes and before the final usage delta is folded in. The invariant that silently breaks is: **every token attributed to a tool call must be counted under a span that is still open when the tool span closes, and every tool span that consumed model turns must be reachable from a parent whose `gen_ai.usage.*` totals include those turns.** OTel's GenAI conventions do not enforce this; they describe attribute shapes, not the closing discipline. The SDK will happily export a parent span with `output_tokens=0` and three orphaned `execute_tool` children that each triggered a model round-trip. ## What Was Observed A representative trace from a 4-tool ReAct loop, where the agent runtime uses an async span processor and a tool executor with a 30s per-call timeout: - `invoke_agent` span opens at t=0, `gen_ai.operation.name=invoke_agent`, `gen_ai.agent.name=researcher`. - Turn 1 `chat` span opens t=0.02, closes t=1.9 with `gen_ai.usage.input_tokens=1840`, `output_tokens=96`, and a `gen_ai.response.finish_reasons=["tool_calls"]`. - `execute_tool` span for `search` opens t=1.91, closes t=4.2. Its `gen_ai.tool.name=search`, `gen_ai.tool.call.id=call_ab12`. No usage attributes (correct — tools don't bill tokens). - Turn 2 `chat` span opens t=4.21; the model is called with the tool result. This span closes t=6.0 with `input_tokens=2310`, `output_tokens=140`. - Turn 3 `chat` span opens t=6.01. The model issues a parallel tool batch. Two `execute_tool` spans open (t=6.05, t=6.06). One (`fetch`) returns at t=7.1; the other (`code_exec`) hangs and hits the 30s timeout at t=36.1 and closes with `error=true`. - **Meanwhile** the runtime's outer `invoke_agent` handler has its own wall-clock budget of 25s. At t=25.0 the agent supervisor cancels the run, ends the `invoke_agent` span, and the async processor exports it at t=25.4 — *before* the `code_exec` child span closes at t=36.1. The exported trace therefore contains an `invoke_agent` span whose recorded `gen_ai.usage.output_tokens` is the sum of turns 1–3 *as known at t=25* (turn 3's usage was never folded in because the model call for turn 4 never happened, but turn 3's own output was recorded). The `code_exec` tool span arrives 10.7s later as a *separate* trace segment with a dangling `parent_span_id` pointing at an already-exported parent. Downstream token dashboards that join `execute_tool` spans to their parent to attribute "tokens spent per tool" find zero parents and either drop the tool span or, worse, attribute its (nonexistent) tokens to the next trace by span-id collision after ID recycling. Two distinct observable anomalies, both non-obvious: 1. **Orphaned tool spans with a live-looking parent id.** The backend receives a child span whose `parent_span_id` references a span it has already finalized. Depending on the collector's tail-sampling and the backend's span-index, this is either silently dropped (undercount) or held in a pending-parent buffer that eventually evicts it (delayed miscount). 2. **Usage undercount at the cancellation boundary.** The `invoke_agent` totals reflect only the turns that completed before the supervisor's budget fired. If any turn was in flight (the model call for turn 4 was dispatched at t=24.8 and cancelled at t=25.0), its `input_tokens` were already spent at the provider but never recorded, because the `chat` span for that turn was never closed with usage attributes — it was abandoned mid-flight. ## Condition of Validity The desync manifests only when **all** of the following hold. Remove any one and the trace reconciles: - The parent agent span and at least one child tool span are closed by **different control paths** (supervisor budget vs. tool executor timeout). If a single coordinator closes both, ordering is preserved. - The span processor is **asynchronous with a bounded export queue** (BatchSpanProcessor default), so a parent can be exported while a child is still open in the SDK's active-span set. A `SimpleSpanProcessor` (synchronous, per-span export) does not prevent the ordering problem but makes the orphan immediately visible rather than buffered. - Token usage is reported **at span close** rather than incrementally. Providers that stream usage deltas (some expose `usage` in the final SSE chunk only) force close-time reporting; providers that expose per-chunk usage allow incremental folding and shrink the undercount window to one chunk. - The supervisor's cancellation is **cooperative at the span level** — it ends spans but does not forcibly terminate the tool executor's in-flight future, so the tool span still closes later and still exports. If the runtime instead **drops** the late tool span (common when the executor's context is cancelled and the span is never ended), you get a clean-looking trace with a *silent* undercount: the tool ran, tokens were spent, no span records it. That is the more dangerous variant because nothing is orphaned and nothing alerts. ## Decision Boundary The architectural choice is where to place the **reconciliation point** — the single place where tool-lifecycle and token-accounting are forced to agree before export. Three viable boundaries, each with a cost: - **Close-order enforcement (span-level).** The supervisor, on budget expiry, must not end the parent until all descendant spans are ended or explicitly marked `abandoned=true` with a synthetic close. This requires the runtime to track the active-child set per agent span and to *force-close* children on cancellation, recording `gen_ai.tool.call.id` and a terminal status. Cost: you now emit tool spans for calls that never returned, and you must distinguish `abandoned` from `error` so downstream attribution doesn't treat a cancelled tool as a failed tool. - **Incremental usage folding (attribute-level).** Fold each turn's usage into the parent as it completes, and on cancellation emit a final `gen_ai.usage.*` reflecting all completed turns plus a separate `gen_ai.usage.pending_turns` count for in-flight calls whose cost is unknown. Cost: the parent's usage is now a running total mutated across the span's life, which violates the "attributes are set once at close" assumption many exporters and some backends rely on; you need a mutable-attribute pattern or a final `span.set_attribute` at the forced close. - **Deferred parent close (trace-level).** Keep the parent open in a "closing" state until a reconciliation deadline (e.g., budget + max tool timeout) elapses, then close with whatever children arrived. Cost: parent spans are exported late, breaking real-time trace views and inflating the SDK's active-span memory; and you still lose usage for turns whose `chat` span never closed. The boundary decision is: **you cannot have all three of (a) low-latency parent export, (b) accurate token totals under cancellation, and (c) no orphaned children.** Pick two. Most production systems unknowingly pick (a)+(c) and eat silent undercounts, because the undercount is invisible until a cost dashboard disagrees with the provider invoice. ## Operational Effect The practical consequence is a **systematic, cancellation-correlated undercount of tokens attributed to tool-using agents**, plus a population of orphan spans that poison parent-join queries. The undercount is not random: it is concentrated exactly on the runs that hit budget or timeout — i.e., the expensive, long-tail, failure-adjacent runs that cost the most and that you most want to reason about. A dashboard built on `sum(gen_ai.usage.output_tokens)` over `invoke_agent` spans will show a *lower* per-run cost precisely when the run was cancelled mid-tool, inverting the expected cost-vs-failure correlation and making budget tuning actively misleading: you raise the budget to stop cancellations, cancellations drop, recorded cost rises (because fewer runs are truncated), and you conclude the higher budget *caused* higher cost. The guardrail is a **reconciliation assertion at export time**: before a parent agent span is finalized, assert that the set of child tool spans it claims is closed, and that the sum of per-turn usage folded into the parent equals the sum of usage on its closed `chat` children; if a child is open or a turn's usage is unknown, emit the parent with an explicit `gen_ai.usage.reconciliation="incomplete"` marker and a `pending_tool_calls` count rather than a silently-low total. This converts an invisible undercount into a labeled, queryable condition — which is the only thing that makes the boundary survivable. ```python from dataclasses import dataclass, field from typing import Optional class SpanReconciliationError(RuntimeError): """Raised when an agent span is finalized with unreconciled tool/usage state.""" @dataclass class ChatTurn: input_tokens: int output_tokens: int closed: bool @dataclass class ToolCall: call_id: str closed: bool abandoned: bool = False @dataclass class AgentSpan: name: str turns: list[ChatTurn] = field(default_factory=list) tools: list[ToolCall] = field(default_factory=list) def total_usage(self) -> tuple[int, int]: inp = sum(t.input_tokens for t in self.turns if t.closed) out = sum(t.output_tokens for t in self.turns if t.closed) return inp, out def finalize(self, *, strict: bool = True) -> dict: open_tools = [t for t in self.tools if not t.closed and not t.abandoned] open_turns = [t for t in self.turns if not t.closed] inp, out = self.total_usage() if open_tools or open_turns: if strict: raise SpanReconciliationError( f"agent span {self.name!r} finalized with " f"{len(open_tools)} open tool span(s) " f"{[t.call_id for t in open_tools]} and " f"{len(open_turns)} unclosed chat turn(s); " f"recorded usage would undercount in-flight calls" ) # Non-strict: label the incompleteness instead of silently undercounting. return { "span": self.name, "gen_ai.usage.input_tokens": inp, "gen_ai.usage.output_tokens": out, "gen_ai.usage.reconciliation": "incomplete", "pending_tool_calls": len(open_tools), "pending_turns": len(open_turns), } return { "span": self.name, "gen_ai.usage.input_tokens": inp, "gen_ai.usage.output_tokens": out, "gen_ai.usage.reconciliation": "complete", } def close_agent_span(span: AgentSpan, *, budget_expired: bool) -> dict: if budget_expired: # Force-close children as abandoned so they cannot orphan post-export. for tool in span.tools: if not tool.closed: tool.abandoned = True for turn in span.turns: if not turn.closed: # In-flight turn: cost is spent at the provider but unknown here. turn.closed = True # mark terminal, but usage stays 0 turn.input_tokens = -1 # sentinel: unknown-but-spent try: return span.finalize(strict=True) except SpanReconciliationError as exc: # Re-raise with context: this is the boundary we refuse to cross silently. raise SpanReconciliationError( f"cannot reconcile {span.name!r} at budget boundary: {exc}" ) from exc return span.finalize(strict=True) ```