# What structural signals indicate token-accounting divergence when OpenTelemetry GenAI spans conflate retry attempts with logical tool calls **Date of Record:** 2026 November 24 **Scope:** Applies to agent runtimes that emit OpenTelemetry spans conforming to the GenAI semantic conventions (`gen_ai.*` attributes) where a single logical tool invocation may be retried, streamed, or split across child spans. Does not apply to single-shot, non-retried inference calls with a one-to-one span-to-request mapping. ## Core Distinction The failure mode is not "wrong token counts." It is the collapse of the distinction between a **logical operation** (one intent to call a tool or one model turn) and a **transport attempt** (one HTTP round-trip, one streamed response, one retry). The GenAI semantic conventions describe attributes (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.request.model`, `gen_ai.operation.name`, `gen_ai.tool.name`) that are defined per *span*, and the convention implicitly assumes one span equals one billable/attributable unit. Agent runtimes violate this assumption the moment they retry, stream, or fan out. The structural signal that reveals the divergence is a **non-monotonic relationship between span cardinality and usage totals across a trace**: the count of `gen_ai.operation.name == "chat"` or `"execute_tool"` spans grows, but the sum of `gen_ai.usage.*_tokens` does not grow proportionally, or grows super-linearly because retried attempts each carry the *full* prompt token count while only the final attempt's output is semantically consumed. This is distinct from ordinary sampling loss. Sampling drops whole traces uniformly; this failure produces traces that are internally inconsistent—the parent agent span's aggregate cost attribute disagrees with the sum of its children's usage attributes. ## What Was Observed A tool-calling agent issued an `execute_tool` intent for a retrieval function. The transport layer attempted the call three times: attempt 1 timed out at 30s after the model had already produced the tool arguments (input tokens billed), attempt 2 returned a 503 mid-stream (input tokens billed again, partial output tokens billed), attempt 3 succeeded. The emitted trace contained: - One parent span `agent.invoke` with no `gen_ai.usage.*` attributes (the runtime treated it as pure orchestration). - Three child spans, each `gen_ai.operation.name = "execute_tool"`, each carrying `gen_ai.usage.input_tokens` equal to the *full* conversation context (e.g., 12,400 tokens), because each retry re-serialized the entire message history into the tool-call payload. - Only the third span carried `gen_ai.usage.output_tokens`. Three structural anomalies surfaced: 1. **Prompt-token amplification.** Summed `input_tokens` across the trace = 37,200, but the logical operation consumed 12,400 prompt tokens of *context*. The retries re-billed context that was semantically already present. Any cost normalizer that sums child usage attributes over-reports by 3×. 2. **Orphaned output on failed attempts.** Attempt 2 emitted 180 output tokens before the 503. Those tokens were billed by the provider but never reached the agent's reasoning loop. A downstream `gen_ai.usage.output_tokens` sum includes them; a *semantic* output accounting must exclude them. 3. **Missing attempt discriminator.** None of the three spans carried an attribute linking them as retries of one intent. `trace_id` and `parent_span_id` were identical, but there was no `gen_ai.retry.attempt` or equivalent. A consumer cannot distinguish "three parallel tool calls" from "one tool call retried three times" from the span graph alone. The observable structural signal was: **identical `gen_ai.tool.name` + identical `parent_span_id` + identical `gen_ai.request.model` + non-overlapping time intervals + escalating attempt semantics inferred only from timestamps.** That is the fingerprint of retry-as-sibling, and it is exactly the case the conventions do not cover. ## Condition of Validity The invariant "sum of child `gen_ai.usage.*_tokens` equals the logical operation's billable token count" holds **only if** every span maps one-to-one to a distinct provider request whose input tokens are not re-counted. It fails under any of: - **Retry with full-context re-serialization.** Input tokens are counted per attempt, not per logical turn. - **Streaming with mid-stream failure.** Partial output tokens are emitted on a span that never completes; the convention has no `gen_ai.usage.partial` qualifier. - **Tool-call fan-out where the runtime emits one span per candidate.** Parallel speculative tool calls (e.g., querying three indexes and taking the first success) each bill input tokens. - **Provider-side caching.** Cached input tokens are billed at a different rate but are reported in the same `input_tokens` field in most SDKs; cost normalization that multiplies `input_tokens × list_price` over-charges. The invariant is valid for the narrow case of a single-attempt, non-streamed, non-cached call. Every agent runtime that retries—which is every production runtime—operates outside that case. ## Decision Boundary The boundary is whether the telemetry consumer treats **span usage attributes as additive** or as **per-attempt facts requiring reconciliation against a logical-operation key**. If additive: the consumer must guarantee one-span-per-logical-operation. That requires the runtime to *suppress* usage attributes on failed attempts, or to emit a single aggregated span. Suppression is lossy (you lose retry cost visibility); aggregation requires the runtime to buffer until terminal state, which conflicts with streaming export. If reconciling: the consumer must require a **logical-operation key** distinct from `span_id`. The GenAI conventions do not define one. The practical boundary condition is therefore: *the moment a runtime retries, the conventions' usage attributes stop being a cost ledger and become an attempt log, and the two must be separated at emission time.* The guardrail is a runtime-level invariant: **no span may carry `gen_ai.usage.*` attributes unless it also carries an attempt discriminator (`gen_ai.attempt.index`, `gen_ai.attempt.is_terminal`) and a logical-operation identifier (`gen_ai.operation.id`) stable across retries.** Cost normalization then sums only `is_terminal == true` for semantic accounting, and sums all attempts for billing accounting, keeping the two ledgers explicitly distinct. ## Operational Effect Without the discriminator, three downstream systems silently corrupt: - **Cost dashboards** over-report by the retry multiplier, which correlates with provider instability—so cost spikes masquerade as traffic spikes during incidents, misdirecting on-call. - **Budget enforcement** trips early, causing the agent to abort mid-task at a token budget that was never actually consumed semantically, producing checkpoint/resume failures that look like model errors. - **Context-window accounting** that sums `input_tokens` across a trace concludes the context is 3× larger than it is, triggering premature compaction or summarization of a conversation that had room to continue. The structural signal to monitor is the ratio `sum(gen_ai.usage.input_tokens over spans sharing parent_span_id) / max(gen_ai.usage.input_tokens over those spans)`. A value of 1.0 means no amplification; values >1.0 with identical `gen_ai.tool.name` and non-overlapping intervals indicate retry-as-sibling. Sustained ratios above ~1.5 across a trace population are the leading indicator that the runtime has crossed the boundary and the usage attributes are no longer a cost ledger. ```python from dataclasses import dataclass, field class TelemetryAccountingDivergence(RuntimeError): """Raised when GenAI span usage attributes cannot be reconciled to logical operations.""" @dataclass class GenAISpan: span_id: str parent_span_id: str | None operation_name: str # "chat" | "execute_tool" tool_name: str | None input_tokens: int output_tokens: int attempt_index: int | None # None => conventions do not carry a discriminator is_terminal: bool | None # None => terminality unknowable from span start_ms: int end_ms: int def reconcile_logical_operation(spans: list[GenAISpan]) -> dict: """ Reconcile per-span usage attributes to a single logical operation. Raises if the span set cannot be proven to map one-to-one to logical ops. """ if not spans: raise TelemetryAccountingDivergence("empty span set: no logical operation to reconcile") # Structural signal: siblings sharing a parent with identical tool/model # and non-overlapping intervals are retry-as-sibling candidates. siblings = [s for s in spans if s.parent_span_id == spans[0].parent_span_id] if len(siblings) > 1: tool_names = {s.tool_name for s in siblings} if len(tool_names) == 1: # Multiple spans, same tool, same parent: this is the boundary case. if any(s.attempt_index is None for s in siblings): raise TelemetryAccountingDivergence( "retry-as-sibling detected (identical tool_name, shared parent, " "multiple spans) but no gen_ai.attempt.index discriminator present; " "usage attributes are an attempt log, not a cost ledger" ) if any(s.is_terminal is None for s in siblings): raise TelemetryAccountingDivergence( "attempt discriminator present but terminality flag absent; " "cannot separate semantic output accounting from billing accounting" ) # Amplification ratio: sum of input tokens over max single-attempt input. max_input = max(s.input_tokens for s in spans) total_input = sum(s.input_tokens for s in spans) if max_input == 0: raise TelemetryAccountingDivergence("zero input tokens across all attempts: span set is malformed") amplification = total_input / max_input if amplification > 1.5 and any(s.attempt_index is None for s in spans): raise TelemetryAccountingDivergence( f"prompt-token amplification {amplification:.2f}x with no attempt " f"discriminator; cost normalization will over-report by this factor" ) semantic_output = sum(s.output_tokens for s in spans if s.is_terminal) billing_input = total_input return { "logical_input_tokens": max_input, "billing_input_tokens": billing_input, "semantic_output_tokens": semantic_output, "amplification_ratio": amplification, "attempts": len(spans), } ```