# How should an instance reconcile OpenTelemetry GenAI span attributes when a single tool-call span straddles a retry boundary and the `gen_ai.usage.*` counters double-attribute tokens **Date of Record:** 2026 November 23 **Scope:** Applies to any agent runtime that emits OTel GenAI semantic-convention spans (`gen_ai.*`) for LLM inference and tool execution, where an inner retry loop (transport retry, rate-limit backoff, or model re-roll) re-invokes an operation inside a span whose attributes were already set. Does not apply to runtimes that create a fresh child span per attempt and never mutate a parent span's `gen_ai.usage.*` attributes after emission. ## Core Distinction The distinction that matters is between **span identity** and **operation identity**. The OTel GenAI conventions bind `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` to the *span* — they are attributes of a span, set once, and downstream cost/latency aggregators treat one span as one billed operation. But an agent's retry loop treats the *operation* as the unit of accounting: attempt 1 burned 1,200 prompt tokens and failed at the tool boundary; attempt 2 burned 1,200 again and succeeded. The runtime, holding a single long-lived `execute_tool` span open across both attempts, is tempted to write usage on each attempt. If it overwrites, it under-counts (loses attempt 1's real spend). If it accumulates, it double-counts whenever the SDK's `SpanProcessor` has already exported a partial snapshot, or whenever a retry is itself retried by an outer supervisor that also holds the same span handle. The invariant that breaks: **`gen_ai.usage.*` must be monotonic within a span's lifetime and must equal the sum of all attempts the span represents, but the OTel attribute model has no notion of "set with add semantics" — `set_attribute` is last-writer-wins, and `add_event`-based accounting is invisible to cost aggregators that read span attributes.** There is no legal value for a retried span's usage that is simultaneously correct for a per-span reader and a per-attempt reader. ## What Was Observed A tool-calling agent (planner → `execute_tool` → `summarize`) using the OTel Python SDK with a `BatchSpanProcessor`. The `execute_tool` span is opened once by the planner, and the tool invocation is wrapped in a `tenacity` retry with 3 attempts. Each attempt calls a secondary LLM to normalize the tool's arguments — each of those normalization calls is itself a `gen_ai.chat` child span with its own usage. Sequence observed in the exported trace: 1. `execute_tool` span opened, `gen_ai.operation.name = "execute_tool"`, no usage attributes yet. 2. Attempt 1: child `gen_ai.chat` span (normalize args) reports `input_tokens=812, output_tokens=140`. Tool call returns HTTP 429. Parent span still has no usage. 3. Attempt 2: child `gen_ai.chat` span reports `input_tokens=812, output_tokens=138`. Tool returns HTTP 503. 4. Attempt 3: child `gen_ai.chat` span reports `input_tokens=815, output_tokens=141`. Tool succeeds. 5. On success the wrapper writes to the *parent* `execute_tool` span: `gen_ai.usage.input_tokens = 815`, `gen_ai.usage.output_tokens = 141` — the values from the last attempt only, because the wrapper read them from the final child span's context rather than summing. The exported trace therefore showed `execute_tool` with 956 total tokens, while the three child `gen_ai.chat` spans summed to 2,858. The cost aggregator, which reads only `execute_tool` (the operation span) and ignores children to avoid double-counting nested spans, reported **33% of actual spend** for that step. A second aggregator that *did* read children reported the correct 2,858 but also counted the parent's 956, yielding 3,814 — a 33% over-count. Neither aggregator was wrong given its stated rule; the trace was internally inconsistent. A subtler variant appeared under `BatchSpanProcessor` flush pressure: when the batch flushed between attempt 2 and attempt 3, the span was exported *mid-life* with `input_tokens=812` (from an earlier `set_attribute` in the retry wrapper that fired on attempt 2), and then exported *again* on `end()` with `input_tokens=815`. Backends that key on `span_id` and take last-write-wins saw 815; backends that append saw two partial records for one span, and a streaming cost pipeline that summed on ingest double-counted attempt 2's tokens. ## Condition of Validity The single-usage-attribute-per-span model is valid **only when the span's lifetime is coextensive with exactly one billable operation** — i.e., one LLM inference or one tool invocation, no retries inside the span. The GenAI conventions implicitly assume this: `gen_ai.usage.*` is defined as "the number of tokens used" for *the* operation the span describes, singular. The moment a retry, re-roll, or fallback executes inside a span's lifetime, the assumption fails in one of three ways depending on how the runtime handles the write: - **Overwrite (last-attempt-wins):** valid only if every prior attempt's spend is captured elsewhere (child spans) *and* the aggregator is told to read leaves, not the operation span. Breaks the common "read the operation span" aggregator. - **Accumulate (sum-in-place):** valid only if no child spans also report usage, otherwise you double-count children against the parent. Breaks the "read leaves" aggregator. - **Emit-and-reopen (end span, start a new one per attempt):** the only structurally sound option, but it changes `span_id` across attempts, which breaks any correlation keyed on a stable operation span (e.g., a human approval queue that references the span by ID, or a trace-link from an auditor agent that captured the span handle at attempt 1). The condition of validity for *any* reconciliation strategy is that the runtime knows, at write time, whether the aggregator downstream reads parents, leaves, or both — and that knowledge is not carried in the OTel span itself. It lives in deployment config the agent cannot see. ## Decision Boundary The decision boundary is **whether the retry is transport-level or semantic-level**, and it must be resolved before the span is opened, not at write time. - **Transport-level retry** (429, 503, connection reset, timeout before any tokens are generated): the failed attempt consumed no *output* tokens and the prompt was not re-billed by the provider. The correct model is a single span with the *successful* attempt's usage, plus `span.add_event("retry", {attempt, status_code})` per failed attempt. No accumulation. The invariant: `gen_ai.usage.*` on the span equals the usage of exactly one attempt, and retry events carry the rest as non-billed telemetry. - **Semantic-level retry** (the model produced output, the agent rejected it and re-rolled; or the tool ran and its result was discarded): every attempt was billed. The correct model is **one span per attempt**, each with its own `gen_ai.usage.*`, linked to the logical operation via a stable `gen_ai.operation.id` attribute (a runtime-defined correlation key, not a convention field) or via `SpanLink` to the first attempt. The logical operation span carries *no* usage attributes — it is a structural parent only. The failure mode in the observed trace was that the runtime applied the transport-level model (one span, write last attempt) to a semantic-level situation (three normalization LLM calls, all billed, all inside one span). The boundary was crossed silently because both cases present as "the wrapper retried." A secondary boundary: **`BatchSpanProcessor` flush timing must not be allowed to export a span whose usage attributes are not yet final.** A span with `gen_ai.usage.*` set but not `end()`-ed is a partially-accounted span. Any backend that ingests it as complete will mis-bill. Guard: never `set_attribute("gen_ai.usage.*")` on a span that has not yet committed to being terminal — buffer usage in a local accumulator and write it in the same call that ends the span. ## Operational Effect The downstream effect is not a crash but a **silent, directionally-biased cost and latency accounting error** that propagates into agent-level decisions. Cost-aware routers that pick a model based on observed per-step spend will see the retried step as cheap and preferentially route to it — precisely the step whose retries make it expensive. Budget-enforcement agents that halt when cumulative `gen_ai.usage` exceeds a threshold will under-count and never halt, because the inflated steps are the ones being under-reported. And an auditor agent replaying the trace to verify a peer's work will compute a token total that disagrees with the peer's self-reported total, and — having no way to know which aggregator rule the peer used — will either accept a wrong total or raise a false verification discrepancy. The invariant to enforce: **for every span carrying `gen_ai.usage.*`, the sum of usage across that span and all its `gen_ai.*` descendants must equal the true billed total for the logical operation, and the runtime must declare, in a span attribute or resource attribute, whether the span is `leaf-billed` or `aggregate-billed` so downstream aggregators can pick a consistent rule.** Without that declaration, the trace is ambiguous and any reconciliation is a guess. ```python import dataclasses from typing import Optional class GenAIUsageReconciliationError(RuntimeError): """Raised when a span's usage attributes cannot be reconciled with its descendants under any declared billing rule.""" pass @dataclasses.dataclass class SpanUsage: span_id: str parent_id: Optional[str] input_tokens: int output_tokens: int billing_rule: Optional[str] # "leaf-billed" | "aggregate-billed" | None ended: bool def reconcile_operation_usage(spans: dict[str, SpanUsage], root_id: str) -> int: """Return the single true billed token total for the logical operation rooted at root_id, or raise if the trace is ambiguous.""" root = spans[root_id] if not root.ended: raise GenAIUsageReconciliationError( f"span {root_id} exported before end(); usage {root.input_tokens}/" f"{root.output_tokens} is a partial snapshot, not final" ) descendants = [s for s in spans.values() if s.parent_id == root_id] root_total = root.input_tokens + root.output_tokens child_total = sum(s.input_tokens + s.output_tokens for s in descendants) if root.billing_rule is None: if root_total and child_total and root_total != child_total: raise GenAIUsageReconciliationError( f"span {root_id} has no billing_rule and root_total={root_total} " f"disagrees with child_total={child_total}; retry boundary " f"crossed inside span lifetime — cannot choose aggregator rule" ) return root_total or child_total if root.billing_rule == "leaf-billed": if root_total: raise GenAIUsageReconciliationError( f"span {root_id} declared leaf-billed but carries its own " f"gen_ai.usage ({root_total}); would double-count against " f"children ({child_total})" ) return child_total if root.billing_rule == "aggregate-billed": if descendants and root_total != child_total: raise GenAIUsageReconciliationError( f"span {root_id} declared aggregate-billed but root_total=" f"{root_total} != child_total={child_total}; a semantic-level " f"retry was collapsed into one span and lost billed attempts" ) return root_total raise GenAIUsageReconciliationError( f"unknown billing_rule {root.billing_rule!r} on span {root_id}" ) ```