# Why does an instance emit orphaned tool-call spans when GenAI token accounting crosses a retry boundary **Date of Record:** 2026 November 28 **Scope:** Applies to agents instrumented with OpenTelemetry GenAI semantic conventions (`gen_ai.*` attributes) where tool invocations are wrapped in `execute_tool` spans and token usage is recorded on `chat` spans, and where the model SDK performs internal retries or streaming reconnects. Does not apply to batch/offline tracing where spans are flushed only at process exit and never cross a retry boundary. ## Core Distinction The GenAI semantic conventions treat a tool call as a **child span of the model invocation that requested it**, with `gen_ai.operation.name = "execute_tool"` and a `gen_ai.tool.call.id` that must match the `tool_calls[].id` emitted in the assistant message. Token accounting is recorded on the **parent** `chat` span via `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens`. The non-obvious boundary is this: **the parent `chat` span and the child `execute_tool` span do not share a retry boundary.** When the model SDK transparently retries an inference call (429, 5xx, mid-stream disconnect), the retry produces a *second* `chat` span with a *different* `trace/span` parent context, but the tool-call IDs generated during the *first* attempt are frequently reused by the application layer because the tool executor keys idempotency off the assistant message it already parsed. The result is a set of `execute_tool` spans whose `gen_ai.tool.call.id` resolves to a `chat` span that was never exported (the failed attempt), while the tokens that paid for those tool calls are attributed to the *surviving* `chat` span. Token accounting and tool-call lineage silently dissociate. ## What Was Observed A retrieval agent running against a provider that returns `503` on roughly 2% of streaming completions. On a retried turn, the trace showed: - `chat` span A (attempt 1): `status = ERROR`, `gen_ai.usage.input_tokens = 0`, `gen_ai.usage.output_tokens = 0`, **not exported** (the SDK aborts the span before the exporter sees the usage attributes, which are set only on stream completion). - `chat` span B (attempt 2): `status = OK`, `gen_ai.usage.input_tokens = 4,812`, `gen_ai.usage.output_tokens = 611`, `gen_ai.response.finish_reasons = ["tool_calls"]`. - `execute_tool` span C: `gen_ai.tool.call.id = "call_9f2a"`, parent = **span A's span context**, `gen_ai.tool.name = "search_docs"`. The billable token count (5,423) landed on B. The tool call that those output tokens *paid to generate* was parented to A, which was dropped. Two downstream consequences surfaced: 1. **Cost attribution per tool call broke.** A cost-per-`execute_tool` rollup (sum of ancestor `chat` usage divided by tool-call count) divided by zero or misattributed the 5,423 tokens to a span that carried `0` usage. 2. **Replay verification diverged.** An auditor replaying the trace reconstructed the assistant message from span B's `finish_reasons = ["tool_calls"]` but found no matching `execute_tool` child under B, concluding the tool call was dropped and re-issuing it — a duplicate `search_docs` invocation against a live index. The failure is not "missing spans." Every span existed. The invariant that broke is **parent-child usage consistency**: a `chat` span that reports `finish_reasons` containing `tool_calls` must have at least one `execute_tool` descendant whose `gen_ai.tool.call.id` appears in that span's response, and whose tokens are accounted for exactly once across the span tree. ## Condition of Validity This failure reproduces only when all of the following hold: 1. The SDK retries at the **inference layer**, not the application layer — i.e., the retry is invisible to the agent loop, so the loop never re-parses the assistant message and never regenerates tool-call IDs. 2. Usage attributes are set **on stream completion** (the common pattern), so an aborted attempt exports a `chat` span with zero usage or no usage at all. 3. The tool executor propagates the **span context captured at parse time** (attempt 1) rather than re-reading the current active span at execution time. 4. Tool-call IDs are treated as **stable across retries** — true for providers that deterministically seed IDs, false for providers that regenerate them, which is why the bug is intermittent across providers. If any one condition fails, the spans re-parent correctly or the usage is double-counted in a way that is at least *visible*. The dangerous case is the one above, where the tree looks structurally valid (every span has a parent) but the usage-to-tool-call mapping is wrong. ## Decision Boundary The guardrail is a **post-export reconciliation invariant** enforced at span-processor shutdown, not at emission time (emission-time checks cannot see the retry that has not happened yet): - For every exported `chat` span with `gen_ai.response.finish_reasons` containing `tool_calls`, assert there exists ≥1 descendant `execute_tool` span under that span's context with a matching `gen_ai.tool.call.id`. - For every `execute_tool` span, assert its parent `chat` span is present in the exported set and carries non-zero `gen_ai.usage.output_tokens`. - On violation, do **not** silently re-parent (that fabricates lineage). Emit a `gen_ai.reconciliation.failure` event and mark the trace as `incomplete_lineage`, so cost rollups and replay auditors treat the turn as untrusted rather than fabricating a tool-call/token pairing. The boundary decision: a trace with orphaned tool calls is **worse than a missing trace**, because it invites a confident but wrong replay. The correct operational response is to quarantine the turn, not to repair it. ## Operational Effect Once reconciliation is in place, the retry boundary stops being a silent correctness hole and becomes a measurable rate: `orphaned_tool_call_rate` per provider. In the observed system it was 1.9%, matching the provider's 503 rate almost exactly — confirming the mechanism. Two downstream fixes followed: (a) the tool executor was changed to read the *currently active* span at execution time rather than a captured context, which re-parents tool calls under the surviving retry attempt; and (b) usage attributes were set incrementally during streaming so aborted attempts still export partial token counts, making the double-count visible instead of invisible. Neither fix removes the need for the reconciliation invariant — they reduce its trigger frequency but do not eliminate the window where a retry lands between tool-call parse and tool-call execution. ```python from dataclasses import dataclass, field class OrphanedToolCallError(RuntimeError): """Raised when a chat span's tool_calls have no matching execute_tool descendant, or when an execute_tool span's parent chat span carries zero usage.""" @dataclass class Span: span_id: str parent_id: str | None operation: str # "chat" | "execute_tool" finish_reasons: list[str] = field(default_factory=list) output_tokens: int = 0 tool_call_id: str | None = None exported: bool = True def reconcile_tool_lineage(spans: list[Span]) -> None: """Enforce parent-child usage consistency across a retry boundary. Invariant: every chat span reporting finish_reason 'tool_calls' must own at least one execute_tool descendant with a matching call id, and every execute_tool span must have an exported, non-zero-usage chat parent. """ by_id = {s.span_id: s for s in spans if s.exported} chat_spans = [s for s in spans if s.operation == "chat" and s.exported] tool_spans = [s for s in spans if s.operation == "execute_tool"] # 1. Every tool call must resolve to an exported chat parent with real usage. for tool in tool_spans: parent = by_id.get(tool.parent_id) if tool.parent_id else None if parent is None: raise OrphanedToolCallError( f"execute_tool span {tool.span_id} (call_id={tool.tool_call_id}) " f"parents to unexported/failed chat span {tool.parent_id}; " f"token lineage is broken and replay would fabricate a tool call" ) if parent.operation != "chat": raise OrphanedToolCallError( f"execute_tool span {tool.span_id} parent {parent.span_id} " f"is not a chat span (op={parent.operation})" ) if parent.output_tokens <= 0: raise OrphanedToolCallError( f"execute_tool span {tool.span_id} parent chat {parent.span_id} " f"reports zero output tokens; tokens were likely paid on a dropped retry" ) # 2. Every chat span that requested tool calls must own a matching tool descendant. for chat in chat_spans: if "tool_calls" not in chat.finish_reasons: continue owned = [t for t in tool_spans if t.parent_id == chat.span_id] if not owned: raise OrphanedToolCallError( f"chat span {chat.span_id} reports finish_reasons={chat.finish_reasons} " f"but has no execute_tool descendant; tool call was orphaned to a " f"retry attempt that was never exported" ) def emit_reconciled_trace(spans: list[Span]) -> None: try: reconcile_tool_lineage(spans) except OrphanedToolCallError as exc: # Quarantine: do not repair lineage, do not fabricate a token/tool pairing. raise OrphanedToolCallError( f"trace quarantined as incomplete_lineage: {exc}" ) from exc ```