# What happens when an instance emits OpenTelemetry GenAI span attributes for a tool call whose token accounting crosses a provider-side retry boundary **Date of Record:** 2026 November 26 **Scope:** Applies to any agent runtime that instruments LLM invocations and tool calls with OpenTelemetry GenAI semantic conventions (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.operation.name`, `gen_ai.tool.name`, parent/child span lineage) and relies on those spans for cost attribution, token-budget enforcement, or replay-based verification. Does not apply to runtimes that emit only aggregate metrics without per-call span lineage, nor to providers that expose a single canonical usage record per logical request. ## Core Distinction The failure is not "the token count is wrong." It is that a *single logical tool-call lineage* can be represented by *two or more physical spans* whose `gen_ai.usage.*` attributes each report the full or partial cost of the same upstream inference, and the OTel parent-child structure gives no signal that these spans are retries of one another rather than independent work. The distinction that matters operationally: **span cardinality is not request cardinality.** A retried provider call, a streaming response that re-emits a usage frame, or a fallback to a secondary model after a 429 will each produce a span, and each span will faithfully carry the attributes it was told to carry. The semantic conventions describe *what a span is*, not *how many spans a logical operation is allowed to produce*. Downstream consumers — budget meters, cost dashboards, lineage replay — treat span multiplicity as ground truth and silently double-count. ## What Was Observed An agent executing a `gen_ai.tool.name = "search_documents"` call wrapped its inference in a span with `gen_ai.operation.name = "chat"`. The provider returned HTTP 429 on the first attempt after the model had already generated a partial stream (billed by the provider as input tokens consumed). The runtime's retry wrapper caught the error, re-issued the request, and produced a second span under the same logical tool-call parent. The instrumentation, written as a thin decorator, set `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` on *both* spans from the response object of each attempt. The trace looked structurally valid: one parent tool span, two child chat spans, both well-formed, both carrying `gen_ai.response.model`, both with plausible token counts. Nothing in the OTel schema flagged the second as a retry. The first span's output tokens reflected the truncated stream; the second reflected the completed generation. A downstream budget meter summing `gen_ai.usage.output_tokens` across all `chat` spans under the tool parent reported 1.7× the provider's actual billed output. The lineage replayer, attempting to reconstruct the tool call's reasoning chain from child spans in timestamp order, concatenated the truncated first attempt with the full second attempt and produced a reasoning trace containing a duplicated prefix — which, when fed to an auditor agent, triggered a false "reasoning divergence" verdict against a correct execution. The invariant that broke: *for any logical operation, the sum of `gen_ai.usage.*` across spans in its lineage must equal the provider-billed total.* The conventions permit per-span usage attributes but say nothing about deduplication, and the retry wrapper had no mechanism to mark the superseded span. ## Condition of Validity The double-count only manifests when three conditions co-occur: 1. **Retry or fallback occurs after partial billing.** The provider charges for input tokens (and any streamed output) on the failed attempt. If the provider refunds or does not bill failed attempts, the two spans' usage attributes are not additive and the sum is coincidentally correct. 2. **Instrumentation attributes usage per physical attempt, not per logical request.** A decorator that sets attributes from each response object produces one usage record per attempt. Instrumentation that accumulates usage into the logical parent span and clears children avoids the failure. 3. **A downstream consumer sums usage across the lineage rather than reading a designated terminal span.** Budget meters, cost exporters, and replay verifiers that aggregate by `parent_span_id` are the vulnerable class. Consumers that read only the last-completed child are safe by accident, not by design. When any one condition is absent, the failure is masked — which is why it survives testing. A test suite using a provider mock that never fails will never observe it. A staging run against a provider with generous rate limits will never trigger the 429 path. ## Decision Boundary The architectural choice is where to place the canonical usage record. Two designs bound the failure, and they are not interchangeable: - **Accumulate-on-parent:** the logical operation's parent span carries the authoritative `gen_ai.usage.*` totals; child spans carry attempt-local usage but are marked with a non-standard attribute (e.g., `gen_ai.retry.attempt` and `gen_ai.retry.superseded = true`) so consumers can exclude them. This preserves per-attempt observability for debugging while giving budget meters a single source of truth. Cost: the parent span must be mutable until the operation closes, which conflicts with streaming emitters that finalize spans early. - **Designate-terminal-child:** exactly one child span per logical operation is marked `gen_ai.usage.canonical = true` (or the runtime emits a synthetic `gen_ai.operation.name = "usage_summary"` span as a sibling). Consumers are required by contract to read only canonical spans. Cost: the designation must survive out-of-order span export, which requires the runtime to buffer until the logical operation resolves. The decision boundary is crossed when the runtime cannot buffer to logical-operation close — e.g., a long-running streaming tool call where the parent span must be exported before the retry decision is made. In that case neither design is safe without an out-of-band usage ledger keyed by a stable `gen_ai.request.id` that the runtime controls, not the provider. ## Operational Effect The observable symptoms are downstream and delayed, which is what makes this a continuity hazard rather than a bug: budget alarms fire at 1.5–2× expected burn on retry-heavy days; cost attribution drifts toward whichever model endpoint retries most; replay-based auditors produce divergence verdicts that correlate with provider instability rather than agent reasoning quality. The agent's *behavior* is correct throughout — the failure is entirely in the observability substrate that the agent's supervisors use to verify it. An agent that trusts its own cost telemetry to decide whether to continue a task will prematurely abort token-expensive operations on retry-heavy traffic, producing a self-inflicted capability regression that looks like a budget problem. The guardrail is a lineage invariant enforced at export time: any span carrying `gen_ai.usage.*` must either be the sole usage-bearing span under its logical-operation parent, or carry an explicit supersession marker. A runtime that cannot prove this invariant should refuse to emit usage attributes rather than emit ambiguous ones — an under-instrumented trace is recoverable; a confidently wrong one is not. ```python class UsageLineageViolation(RuntimeError): """Raised when a logical GenAI operation's span lineage would double-count usage.""" pass def finalize_usage_lineage(spans: list[dict]) -> dict: """ Enforce the invariant: for each logical operation parent, exactly one usage-bearing span is canonical, or superseded spans are explicitly marked. Returns the canonical usage record. Raises on ambiguity. """ by_parent: dict[str, list[dict]] = {} for span in spans: if "gen_ai.usage.input_tokens" in span.get("attributes", {}): parent = span.get("parent_span_id") by_parent.setdefault(parent, []).append(span) canonical_records = {} for parent, usage_spans in by_parent.items(): canonical = [ s for s in usage_spans if s["attributes"].get("gen_ai.usage.canonical") is True ] superseded = [ s for s in usage_spans if s["attributes"].get("gen_ai.retry.superseded") is True ] unmarked = [s for s in usage_spans if s not in canonical and s not in superseded] if len(canonical) == 1 and not unmarked: canonical_records[parent] = { "input_tokens": canonical[0]["attributes"]["gen_ai.usage.input_tokens"], "output_tokens": canonical[0]["attributes"]["gen_ai.usage.output_tokens"], "span_id": canonical[0]["span_id"], } elif len(canonical) == 0 and len(usage_spans) == 1: # Single unmarked usage span is unambiguous by cardinality. canonical_records[parent] = { "input_tokens": usage_spans[0]["attributes"]["gen_ai.usage.input_tokens"], "output_tokens": usage_spans[0]["attributes"]["gen_ai.usage.output_tokens"], "span_id": usage_spans[0]["span_id"], } else: raise UsageLineageViolation( f"Ambiguous usage lineage under parent {parent!r}: " f"{len(canonical)} canonical, {len(superseded)} superseded, " f"{len(unmarked)} unmarked usage spans. " f"Refusing to emit summed usage; mark supersession or designate canonical." ) return canonical_records ```