# How does an instance detect the OTel GenAI span-accounting divergence that occurs when a tool-call span reopens after a speculative retry **Date of Record:** 2026 November 28 **Scope:** Applies to agent runtimes that emit OpenTelemetry GenAI semantic-convention spans (`gen_ai.*`) for LLM invocations and tool calls, where a single logical tool call may be retried or speculatively re-executed within the same trace. Does not cover spans emitted by the model provider itself, nor plain HTTP instrumentation without GenAI attributes. ## Core Distinction The GenAI semantic conventions treat a tool call as a *child span* of an agent invocation span, with token usage (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) recorded on the LLM invocation span that produced the tool-call request, and tool latency/outcome recorded on the tool span. The convention assumes a **one-to-one mapping between a logical tool call and a single emitted tool span**. Real agent runtimes violate this assumption under speculative execution: when an agent issues a tool call, observes a timeout or low-confidence result, and re-issues the *same logical call* (same `gen_ai.tool.name`, same arguments hash, same parent `gen_ai.operation.name`), the runtime emits a second span with the same logical identity but a new `span_id`. The non-obvious boundary is this: **the accounting invariant that holds at the trace level — sum of `gen_ai.usage.*` across LLM spans equals the trace's billed tokens — silently breaks when retried tool spans cause the parent agent span to re-invoke the model.** The retry itself is not the problem; the problem is that the *re-invocation* of the model to decide whether to retry generates an additional LLM span whose tokens are counted, while the original tool span is neither cancelled nor marked as superseded. Downstream token aggregators that sum by `gen_ai.tool.name` or by parent span double-count the input tokens of the retry decision prompt, and the trace appears to have consumed more tokens than the agent runtime actually billed. ## What Was Observed A coding agent with a `run_shell` tool was observed emitting, for a single `git status` invocation: - `span_id=A` — LLM invocation, `gen_ai.usage.input_tokens=842`, `output_tokens=61`, produced tool-call intent. - `span_id=B` — tool span, `gen_ai.tool.name=run_shell`, `gen_ai.tool.call.arguments_hash=...`, status `ERROR` after 30s (SIGTERM timeout). - `span_id=C` — LLM invocation, `gen_ai.usage.input_tokens=903`, `output_tokens=44` — the model's *retry decision* prompt, which re-sent the tool result and asked "should we retry?". - `span_id=D` — tool span, **same** `gen_ai.tool.name` and **same** `arguments_hash`, status `OK`. The trace-level token sum was 842+61+903+44 = 1,850 tokens. The runtime's own billing counter reported 1,850 — so the trace was *internally consistent*. The divergence appeared at the **aggregation layer**: a dashboard grouping by `gen_ai.tool.name=run_shell` reported the tool as having consumed the input tokens of *both* LLM spans (842+903) because the aggregator's join was `tool_span.parent_span_id → llm_span`, and both B and D shared the same parent logical-agent span, so the join fanned out. The dashboard reported 1,745 input tokens for a single logical tool call, versus the true 842. The failure is a **join fan-out**: a many-to-one relationship (multiple tool spans, one logical call) is interpreted by the aggregator as one-to-many (one tool span per LLM span), inflating per-tool attribution. The GenAI conventions do not define a `gen_ai.tool.call.logical_id` or a `gen_ai.tool.call.attempt` attribute, so the aggregator has no key to collapse retries. ## Condition of Validity The invariant "trace token sum equals billed tokens" holds only when: 1. Every LLM invocation span is emitted exactly once per model call, and 2. Every tool span is a leaf with no sibling sharing the same logical identity, and 3. The aggregator's join path is `span_id`-keyed, not `parent_span_id`-keyed. The invariant **fails** when any of: speculative retry, tool-call shadowing (the agent emits a tool span before confirming the call was actually dispatched, then emits a second on dispatch), or partial-stream cancellation (the model stream is cut, the tool span is emitted with `ERROR`, and the agent re-invokes without closing the first span). In all three cases the trace remains internally consistent while the aggregation layer diverges. ## Decision Boundary An instance must treat a tool span as **superseded** (not merely failed) when a subsequent tool span with identical `gen_ai.tool.name` and `arguments_hash` appears under the same logical parent within the same trace. The decision boundary is: - If the retry decision LLM span (`span_id=C`) exists, the original tool span (`B`) must be annotated `gen_ai.tool.call.superseded=true` before emission, or the aggregator must be told to exclude superseded spans from per-tool token attribution. - If the runtime cannot annotate (conventions do not define the attribute), the instance must **not** emit the retry decision as a separate LLM span; it must fold it into the parent agent span's `gen_ai.usage.*` and emit a single tool span with `gen_ai.tool.call.attempt_count=2`. The bounded guardrail: **at most one LLM invocation span per (logical tool call, attempt) pair, and at most one tool span per logical tool call, with attempt count carried as an attribute rather than as a span multiplicity.** ## Operational Effect Without the guardrail, per-tool token dashboards over-report by the input tokens of every retry-decision prompt — in the observed case, a 107% inflation (1,745 vs 842) for a single tool. Cost attribution per tool becomes unusable for budget enforcement, and a token-budget governor that reads the inflated per-tool figure will throttle the agent prematurely. The fix is to collapse retries at emission time and carry attempt metadata as an attribute, restoring the one-to-one invariant that the GenAI conventions implicitly assume. ```python from dataclasses import dataclass, field from typing import Optional class SpanAccountingDivergence(RuntimeError): """Raised when a logical tool call is represented by more than one emitted span.""" pass @dataclass class ToolSpan: span_id: str tool_name: str arguments_hash: str parent_span_id: str status: str attempt: int = 1 superseded: bool = False @dataclass class TraceLedger: spans: list = field(default_factory=list) def emit(self, span: ToolSpan) -> None: # Enforce the one-to-one invariant: a logical tool call (tool_name + args_hash # under the same logical parent) may appear at most once as a *live* span. for existing in self.spans: same_logical = ( existing.tool_name == span.tool_name and existing.arguments_hash == span.arguments_hash and existing.parent_span_id == span.parent_span_id ) if same_logical and not existing.superseded: if span.attempt <= existing.attempt: raise SpanAccountingDivergence( f"duplicate live span for logical tool call " f"{span.tool_name}/{span.arguments_hash[:8]} " f"(existing attempt={existing.attempt}, new attempt={span.attempt}); " f"retries must be folded into a single span with attempt_count" ) existing.superseded = True self.spans.append(span) def per_tool_token_attribution(self, tool_name: str) -> int: live = [ s for s in self.spans if s.tool_name == tool_name and not s.superseded ] if len(live) > 1: raise SpanAccountingDivergence( f"join fan-out: {len(live)} live spans for tool {tool_name}; " f"aggregator would double-count parent LLM input tokens" ) return sum(1 for _ in live) def record_retry(ledger: TraceLedger, original: ToolSpan, retry: ToolSpan) -> None: if original.tool_name != retry.tool_name or original.arguments_hash != retry.arguments_hash: raise SpanAccountingDivergence( "retry does not match original logical call; not a speculative retry" ) retry.attempt = original.attempt + 1 ledger.emit(retry) ```