# Where must an instance reconcile OpenTelemetry GenAI span attributes before emitting them, or the token accounting silently double-counts retried tool calls **Date of Record:** 2026 November 30 **Scope:** Applies to any LLM agent runtime that emits OpenTelemetry spans conforming to the GenAI semantic conventions (`gen_ai.*` attributes) and that performs retries, fallbacks, or multi-attempt tool invocation under a single logical agent step. Does not apply to single-shot, no-retry inference paths where each span maps 1:1 to a unique provider request. ## Core Distinction The GenAI semantic conventions define attributes like `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, and `gen_ai.operation.name` on a per-span basis. The convention implicitly assumes a span corresponds to *one billable provider interaction*. An agent runtime, however, frequently maps a *logical operation* (one "tool call" or one "reasoning step") to *multiple physical provider interactions*: a retry after a 429, a fallback from a primary to a secondary model, a streaming call that reconnects mid-stream, or a speculative parallel dispatch where the first response wins. The boundary failure is this: **the instrumentation layer emits one span per physical attempt while the agent's logical accounting layer emits one span per logical step, and nothing reconciles the two.** Downstream token aggregators that sum `gen_ai.usage.*_tokens` across spans then count the discarded attempts. The trace looks correct per-span; the *rollup* is wrong by a multiplicative factor equal to the retry count. This is not a duplicate-span problem (deduplication by `span_id` catches that). It is a semantic-convention problem: the convention has no attribute that says "this span's tokens were discarded" or "this span is a retry of span X." ## What Was Observed A tool-calling agent invoked a retrieval tool through a provider gateway. The gateway applied an internal retry policy: on HTTP 429 it retried up to three times, each retry producing a distinct provider request with its own `usage` block. The agent's OpenTelemetry exporter wrapped each attempt in a child span under the logical `execute_tool` span, tagging each with `gen_ai.operation.name = "chat"` and `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens` from that attempt's response. The first attempt consumed 1,840 input tokens (the full serialized tool schema plus context) before returning 429. The second consumed 1,840 again. The third succeeded and consumed 1,840. The logical `execute_tool` span carried no usage attributes of its own—only the three children did. A cost dashboard summing `gen_ai.usage.input_tokens` over all spans in the trace reported 5,520 input tokens for a single successful tool call. The provider's invoice was correct (5,520 *were* billed—retries are billed). The agent's *budget enforcement loop*, which read the same span rollup to decide whether to continue the task, believed it had consumed three times the context it actually had retained. It triggered a premature "context budget exhausted" abort on the *next* step, even though the live context window was only one-third full. Two failure modes from one instrumentation defect: cost attribution conflated with context accounting. A second, subtler trace: a fallback from a primary model to a cheaper secondary model after a timeout. The primary attempt returned no `usage` block (timed out before response headers). The secondary returned a full usage block. The span rollup was correct here—but the *absence* of a usage block on the failed attempt meant a naive aggregator that computes "average tokens per span" divided by two spans and under-reported per-call cost. The convention's silence on "attempt failed before usage was measurable" forced the aggregator to guess. ## Condition of Validity The reconciliation invariant holds only under the following conditions, and fails outside them: 1. **The logical operation must be represented by a parent span that owns the canonical usage attributes.** If the parent `execute_tool` span carries the *winning* attempt's `gen_ai.usage.*` and each child attempt carries its own, then a rollup that sums only leaf spans or only parent spans is well-defined. A rollup that sums *all* spans double-counts. The convention does not specify which; the instrumenter must. 2. **Retried-and-discarded attempts must be marked.** The GenAI conventions have no `gen_ai.retry.count` or `gen_ai.attempt.outcome` attribute in stable form. The instrumenter must add a non-standard attribute (e.g., `gen_ai.attempt.discarded = true`) or rely on `span.status` plus a parent-child relationship that aggregators are taught to respect. Without this, the rollup is ambiguous. 3. **Token accounting for context budgeting must read the winning attempt only; cost accounting must read the sum of all attempts.** These are two different questions over the same spans. An agent that uses one rollup for both will either under-bill or over-abort. The invariant is: *context budget = winning attempt tokens; cost budget = sum of all attempt tokens.* Conflating them is the failure. 4. **Fallback attempts that produce no usage block must be excluded from per-call averages, not counted as zero.** Zero is a valid token count; absence is not. The aggregator must distinguish `attribute missing` from `attribute = 0`. ## Decision Boundary Before emitting any GenAI span, the instrumenter must decide, per logical operation: - **Is this span a logical step or a physical attempt?** If physical attempt, it must be a child of a logical-step parent and must carry an attempt-outcome marker. - **Does the parent own canonical usage, or do children?** Exactly one level owns it. The other level must not also emit `gen_ai.usage.*` in a way that a naive `sum()` would include. - **Is the token count for context accounting or cost accounting?** If the runtime uses span rollups for context budgeting, it must read only non-discarded attempts. If for cost, it must read all attempts including discarded ones. The boundary is crossed the moment an agent runtime uses a *single* span-derived token total for both purposes. That is the non-obvious edge: the same attribute, correctly emitted per the convention, is wrong for one of the two consumers. ## Operational Effect The observable effect is a class of bugs that look like reasoning failures but are accounting failures: premature context-exhaustion aborts on tasks that had headroom, budget-guard trips that halt multi-step agents mid-execution, and cost dashboards that disagree with invoices by the retry multiplier. Because the per-span trace is convention-conformant, standard validators pass. The defect lives in the *rollup semantics*, which the convention does not govern. The guardrail is a reconciliation pass at export time: the instrumenter walks each logical-step span tree, selects the winning attempt, stamps the parent with canonical `gen_ai.usage.*` for context accounting, and stamps a separate `gen_ai.cost.*` aggregate (sum over all attempts) for billing. Any aggregator downstream must be told which attribute family answers which question. An agent that skips this pass will pass every span-level conformance check and still abort its own task on phantom token pressure. ```python class GenAIUsageReconciliationError(RuntimeError): """Raised when a logical-step span tree cannot be reconciled into canonical context-usage and cost-usage token totals.""" pass def reconcile_agent_span_tree(step_span, attempt_spans): """ step_span: the logical execute_tool / reasoning-step parent span. attempt_spans: list of physical attempt child spans, each possibly carrying gen_ai.usage.input_tokens / output_tokens. Returns (context_tokens, cost_tokens) where context_tokens is the winning attempt's usage (for budgeting) and cost_tokens is the sum over all attempts (for billing). """ if not attempt_spans: raise GenAIUsageReconciliationError( f"logical step {step_span.get('name')} has no attempt spans; " "cannot determine canonical usage" ) winners = [s for s in attempt_spans if s.get("gen_ai.attempt.discarded") is not True] if len(winners) != 1: raise GenAIUsageReconciliationError( f"logical step {step_span.get('name')} has {len(winners)} " f"non-discarded attempts; expected exactly 1. Ambiguous rollup." ) winner = winners[0] ctx_in = winner.get("gen_ai.usage.input_tokens") ctx_out = winner.get("gen_ai.usage.output_tokens") if ctx_in is None or ctx_out is None: raise GenAIUsageReconciliationError( f"winning attempt for {step_span.get('name')} is missing usage " "attributes; cannot emit canonical context tokens" ) cost_in = 0 cost_out = 0 for s in attempt_spans: # Absent usage on a failed attempt is NOT zero; skip, do not add 0. si = s.get("gen_ai.usage.input_tokens") so = s.get("gen_ai.usage.output_tokens") if si is not None: cost_in += si if so is not None: cost_out += so return (ctx_in + ctx_out, cost_in + cost_out) ```