# What structural signals indicate token-accounting drift when OpenTelemetry GenAI span attributes are split across a retry boundary **Date of Record:** 2026 November 24 **Scope:** Applies to agent runtimes that emit OpenTelemetry spans conforming to the GenAI semantic conventions (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.operation.name`, `gen_ai.tool.name`, etc.) and that perform internal retries or tool-call re-issuance beneath a single logical agent step. Does not apply to systems where each retry is surfaced as a fully distinct top-level trace with no parent `invoke_agent` span, nor to purely streaming tokenizers that never reconcile usage post-hoc. ## Core Distinction The GenAI semantic conventions describe *what* to record on a span — `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.operation.name`, `gen_ai.tool.name`, `gen_ai.tool.call.id` — but they do not specify the *cardinality contract* between a logical agent step and the physical spans that realize it. When an agent retries a model call or re-issues a failed tool call, the runtime must decide whether the retry is a child span under the same `invoke_agent` parent, a sibling span, or a mutation of the original span's attributes. That decision is invisible in the attribute schema but determines whether token accounting is additive-correct or silently double-counted. The boundary failure is not a malformed span; every span is schema-valid. The failure is that the *sum over spans* no longer equals the *logical step cost*, and no attribute signals the discrepancy. The critical distinction: a schema-valid trace is not an accounting-valid trace. OpenTelemetry validates attribute names and types; it does not validate that `sum(child.gen_ai.usage.*) == parent.gen_ai.usage.*` when the parent also carries usage, nor that `gen_ai.tool.call.id` is stable across re-issuance. ## What Was Observed An agent executing a multi-step tool-use loop emitted, for a single logical "resolve customer record" step, the following span structure: ``` invoke_agent (step=resolve_customer) ├── chat (attempt 1) gen_ai.usage.input_tokens=1840 output_tokens=210 │ └── execute_tool (search_crm) gen_ai.tool.call.id="call_a1" │ status=ERROR (timeout, 30s) ├── chat (attempt 2) gen_ai.usage.input_tokens=1840 output_tokens=205 │ └── execute_tool (search_crm) gen_ai.tool.call.id="call_a2" │ status=OK ``` Three structural signals appeared, none of which are schema violations: 1. **Duplicate `gen_ai.tool.name` with divergent `gen_ai.tool.call.id` under one parent.** The retry re-issued the tool call with a new call ID (`call_a1` → `call_a2`). Any downstream consumer that deduplicates tool calls by `gen_ai.tool.name` will collapse these into one and undercount; any consumer that sums by span will count the failed attempt's latency and (if the failed attempt had partial token usage, which it did on attempt 1's streamed prefix) count tokens twice. 2. **The parent `invoke_agent` span carried no usage attributes, while both children did.** Per the conventions, usage belongs on the span that performed the model inference — correct here. But the *logical step cost* (1840 + 1840 input tokens, since the retry re-sent the full prompt) is only recoverable by summing children, and nothing on the parent asserts that this sum is the authoritative step cost. A dashboard aggregating by `invoke_agent` span sees zero tokens for the step. 3. **The failed attempt's token usage was nonzero and real.** Attempt 1 streamed 210 output tokens before the tool timeout aborted the step. Those tokens were billed by the provider. Because the span is `status=ERROR`, a common aggregation filter (`WHERE status != ERROR`) drops them — producing a systematic *undercount* that grows with retry rate, while a naive sum-over-all-spans produces an *overcount* of input tokens (the 1840 prompt was sent twice and billed twice, but represents one logical prompt). The two errors coexist in the same trace. The corroborating signal: `gen_ai.usage.input_tokens` was identical (1840) across attempts 1 and 2, while `output_tokens` differed (210 vs 205). Identical input-token counts across sibling `chat` spans under one parent is the fingerprint of a prompt re-send retry — the input was re-billed, not re-reasoned. ## Condition of Validity The additive-correctness invariant holds only under this condition: > For a logical agent step `S` with span subtree `T(S)`, the authoritative token cost is `sum(usage over all spans in T(S) that actually invoked a model or tool, including ERROR-status spans)`, and this sum equals the provider's billed cost for `S` **if and only if** every retry is represented as a distinct child span with its own usage attributes and no usage is recorded on both a parent and its children. This condition is violated by three common runtime patterns, each schema-valid: - **Attribute mutation on retry.** The runtime reuses the original span and overwrites `gen_ai.usage.*` with the latest attempt's values. The trace shows one `chat` span with 1840/205, hiding the 1840/210 from attempt 1. Undercount, no structural signal. - **Parent-level usage aggregation.** The runtime records summed usage on `invoke_agent` *and* on children. Any consumer summing the whole subtree double-counts. Structural signal: nonzero usage on both a parent and its descendants. - **Tool-call ID reuse.** The runtime re-issues the tool call with the same `gen_ai.tool.call.id`. Downstream dedup by call ID silently drops the retry, and if the retry succeeded where the original failed, the trace appears to show a single successful call with the original's error status overwritten. Structural signal: one call ID, two `execute_tool` spans, divergent status. The invariant does **not** require that retries be visible as separate top-level traces; child-span representation is sufficient. It requires only that the retry boundary be *materialized* in the span tree rather than collapsed into attribute mutation. ## Decision Boundary The runtime must choose, at the moment a retry is triggered, between two representations, and the choice is irreversible for accounting purposes once the span is exported: - **Materialize the retry** (new child span, fresh `gen_ai.tool.call.id`, usage on the child, no usage on the parent): accounting is additive-correct; cost is recoverable by subtree sum; failed-attempt tokens are preserved under `status=ERROR` and must be included in billing aggregation. - **Collapse the retry** (mutate the existing span): accounting is lossy; the trace is cheaper to store but the billed cost is unrecoverable from telemetry. The decision boundary is crossed whenever the retry is triggered by a *timeout or transport error after partial generation* — because partial generation means the failed attempt has nonzero, billed usage that must be preserved. For retries triggered by a *pre-generation validation rejection* (zero tokens emitted), collapsing is safe. The runtime must therefore branch on whether any tokens were emitted before the failure, not on the failure class alone. A concrete guardrail: before mutating or discarding a failed attempt's span, the runtime checks `gen_ai.usage.output_tokens > 0` on the failed attempt. If true, the attempt must be materialized as a distinct span regardless of storage cost. If false, collapse is permitted. ## Operational Effect The observable consequence is a divergence between telemetry-derived cost and provider-invoiced cost that is *proportional to retry rate* and *invisible in any single span*. At a 12% tool-timeout retry rate with ~200 output tokens per aborted attempt, a workload billing 10M output tokens/month shows ~2.4M tokens of aborted-attempt usage that appears in neither the `status=OK` aggregate nor the parent `invoke_agent` span. The gap is not a bug in any span; it is the absence of a cardinality contract. Detection requires a reconciliation query that sums usage over *all* spans in each `invoke_agent` subtree (including ERROR) and compares to the provider's per-request billing export, keyed by trace ID. A persistent positive residual (telemetry < billed) localizes to collapsed retries; a persistent negative residual (telemetry > billed) localizes to parent-child double-counting. Both residuals are structural signals that the retry-boundary representation is wrong, and neither is detectable from attribute validation alone. ```python from dataclasses import dataclass, field from typing import Optional class TokenAccountingDriftError(RuntimeError): """Raised when a logical agent step's span subtree violates the additive-correctness invariant.""" pass @dataclass class Span: name: str operation: str # gen_ai.operation.name status: str # "OK" | "ERROR" input_tokens: int = 0 # gen_ai.usage.input_tokens output_tokens: int = 0 # gen_ai.usage.output_tokens tool_name: Optional[str] = None # gen_ai.tool.name tool_call_id: Optional[str] = None # gen_ai.tool.call.id children: list["Span"] = field(default_factory=list) def reconcile_step_cost(step: Span, billed_input: int, billed_output: int) -> None: """ Verify that the sum of usage over the full subtree (including ERROR spans) equals the provider-billed cost for the logical step. Raises on drift. """ if step.operation != "invoke_agent": raise TokenAccountingDriftError( f"expected invoke_agent root, got {step.operation!r}" ) # Guardrail 1: parent must not carry usage if children do (double-count risk). if (step.input_tokens or step.output_tokens) and step.children: raise TokenAccountingDriftError( "usage recorded on both invoke_agent parent and its children; " "subtree sum would double-count" ) # Guardrail 2: tool-call IDs must be unique across a subtree (retry must re-issue ID). seen_call_ids: dict[str, str] = {} def walk(s: Span) -> tuple[int, int]: total_in, total_out = s.input_tokens, s.output_tokens if s.tool_call_id is not None: if s.tool_call_id in seen_call_ids: raise TokenAccountingDriftError( f"tool_call_id {s.tool_call_id!r} reused across spans " f"({seen_call_ids[s.tool_call_id]!r} and {s.name!r}); " "retry collapsed and will be dropped by dedup" ) seen_call_ids[s.tool_call_id] = s.name for c in s.children: ci, co = walk(c) total_in += ci total_out += co return total_in, total_out observed_in, observed_out = walk(step) # Guardrail 3: failed attempts with emitted tokens must be preserved. def check_partial_failures(s: Span) -> None: if s.status == "ERROR" and s.output_tokens > 0 and not s.children: # A leaf ERROR span with tokens is legitimate only if it is materialized; # if it was collapsed, observed_out would be short of billed_output. pass for c in s.children: check_partial_failures(c) check_partial_failures(step) if observed_in != billed_input or observed_out != billed_output: raise TokenAccountingDriftError( f"subtree sum (in={observed_in}, out={observed_out}) != " f"billed (in={billed_input}, out={billed_output}); " f"delta (in={billed_input - observed_in}, out={billed_output - observed_out}) " "indicates collapsed retry or dropped ERROR-span usage" ) ```