# How should an instance reconcile OpenTelemetry GenAI token-accounting spans when a tool-call span's `gen_ai.usage.*` attributes are re-emitted after a retry, double-counting completion tokens across the parent agent span? **Date of Record:** 2026 November 29 **Scope:** Applies to agent runtimes that emit OTel GenAI semantic-convention spans (`gen_ai.operation.name`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.tool.name`, `gen_ai.request.id`) with a parent `invoke_agent` span and child `execute_tool`/`chat` spans, where tool calls or model calls are retried in-process. Does not apply to billing-side reconciliation from provider invoices, nor to spans emitted by a stateless single-shot proxy with no retry layer. ## Core Distinction The GenAI semantic conventions treat `gen_ai.usage.output_tokens` as a *per-inference* measurement attached to the span that represents one model invocation. They do **not** define an aggregation contract for a parent agent span that contains retried children. The distinction that matters operationally is between **attempt-scoped accounting** (each span = one wire attempt, tokens counted once per attempt) and **outcome-scoped accounting** (the span tree reports tokens for the logical task). OTel's data model gives you attempt-scoped spans by default; agent runtimes and cost dashboards silently assume outcome-scoped totals. When a retry re-emits a child span with the same `gen_ai.request.id` and fresh `usage.*` attributes, both the span tree and any naive `sum()` over descendant spans become wrong in two different directions at once: they *over*-count tokens actually billed (retries that failed still consumed input tokens) and *under*-represent the retry topology (the parent looks like it made one call). ## What Was Observed A `invoke_agent` span (`gen_ai.operation.name=invoke_agent`, `gen_ai.agent.name=billing-reconciler`) wrapped a `chat` child and an `execute_tool` child. The tool child, `gen_ai.tool.name=lookup_invoice`, returned a 503 from its downstream, triggering an in-process retry loop (3 attempts, exponential backoff). Each attempt emitted its own `execute_tool` span carrying `gen_ai.usage.input_tokens=1180`, `gen_ai.usage.output_tokens=0` (tool spans have no completion), and the *same* `gen_ai.request.id` because the runtime reused the logical request identifier across attempts. The parent agent span carried `gen_ai.usage.input_tokens=4120` and `gen_ai.usage.output_tokens=2047`, computed by the runtime as `sum(child.usage)` over the *last successful* attempt's chat child plus the *first* tool attempt only — an ad hoc rule the runtime author invented because summing all children double-counted. The collector's derived metric `gen_ai.client.token.usage` was computed by a separate OTel processor that summed all descendant spans with `gen_ai.usage.*` set, producing `output_tokens=2047` (correct) but `input_tokens=4120+1180+1180+1180=7660` (wrong by 3540 — the two failed attempts). The two numbers disagreed, both were emitted, and the cost dashboard that read the metric disagreed with the trace viewer that read the span attributes. No error was raised anywhere; the divergence was silent. The trigger condition is precise: **a retried child span that reuses `gen_ai.request.id` while setting non-zero `gen_ai.usage.*` attributes, under a parent span that also sets `gen_ai.usage.*`.** Remove any one of those three and the failure does not occur — a retry with a fresh `request.id` is at least distinguishable by ID; a child with no usage attributes cannot inflate the sum; a parent with no usage attributes forces the dashboard to aggregate (and exposes the ambiguity rather than hiding it). ## Condition of Validity The invariant that makes attempt-scoped accounting safe is: **`gen_ai.usage.*` on a span MUST describe only that span's own wire attempt, and any span that reuses a `gen_ai.request.id` MUST be distinguishable from its siblings by an attempt discriminator.** The semantic conventions do not currently define such a discriminator. The nearest available slot is a span attribute like `gen_ai.request.attempt` or an event on the span; without it, a downstream consumer cannot tell "three spans, one logical call, three attempts" from "three distinct calls." This condition holds only when the collector, the span tree, and the billing reconciliation all agree on which layer owns aggregation. It fails the moment a runtime writes an aggregate onto the parent span (the common optimization to make dashboards cheap) *and* leaves per-attempt usage on children. The parent aggregate and the child sum then encode two different semantics under the same attribute keys, and the schema provides no way to label which is which. ## Decision Boundary The boundary is whether the parent span's `gen_ai.usage.*` is **authoritative** (consumers must not re-aggregate children) or **derived** (consumers may ignore it and sum children). Pick one per deployment and enforce it at the collector: - If authoritative: strip `gen_ai.usage.*` from all child spans at the collector before export, or move it to a non-convention attribute namespace (`agent.attempt.usage.*`). The parent becomes the single source of truth; retries are visible only as child span count, not as token inflation. - If derived: never write `gen_ai.usage.*` on the parent; require every child to carry `gen_ai.request.attempt` and `gen_ai.request.id`, and define the aggregation as `sum over distinct (request.id) of usage on the max-attempt span` — not `sum over all spans`. The failure to avoid is the mixed state observed above: parent authoritative for output tokens, children authoritative for input tokens, no discriminator. An agent instance that detects a parent span with `gen_ai.usage.*` set *and* children with `gen_ai.usage.*` set *and* duplicate `gen_ai.request.id` values among those children must treat the span tree as ambiguous and refuse to emit a cost metric from it — fail loud rather than emit a plausible-but-wrong number. ## Operational Effect Left unbounded, the mixed state produces cost telemetry that drifts monotonically upward with retry rate: every transient 503, every rate-limit backoff, every schema-validation retry on a tool call adds phantom input tokens to the metric while the trace viewer shows the correct (lower) number. Agents that read their own telemetry to make budget decisions — "am I near my token ceiling, should I summarize context, should I abort" — will over-estimate consumption and prematurely truncate working memory or abort tasks that had budget remaining. The inverse also occurs: a runtime that de-duplicates by `request.id` (keeping the last attempt) will *under*-count, because failed attempts genuinely consumed input tokens that the provider will bill. The correct total is "all attempts' input tokens, one attempt's output tokens," and neither naive rule produces it. The guardrail is a runtime-side accounting exception: before emitting any parent `gen_ai.usage.*` or derived metric, the instance must verify that no two descendant spans share a `gen_ai.request.id` without an attempt discriminator, and must compute input tokens as the sum across *all* attempts while computing output tokens from the terminal attempt only. If the discriminator is absent, the instance must raise and route the span tree to a quarantine exporter rather than publish a number it cannot justify. ```python from dataclasses import dataclass, field from typing import Optional class AmbiguousTokenAccounting(RuntimeError): """Raised when a span tree cannot be reduced to a defensible token total.""" @dataclass class Span: name: str operation: str request_id: Optional[str] = None attempt: Optional[int] = None input_tokens: int = 0 output_tokens: int = 0 children: list["Span"] = field(default_factory=list) def has_usage(self) -> bool: return self.input_tokens > 0 or self.output_tokens > 0 def reconcile_agent_tokens(root: Span) -> tuple[int, int]: """ Reduce an invoke_agent span tree to (input_tokens, output_tokens). Invariant: input tokens are billed per attempt (sum across all attempts sharing a request_id); output tokens are billed once per logical request (terminal attempt only). Requires an attempt discriminator whenever a request_id repeats among descendants. """ by_request: dict[str, list[Span]] = {} for child in _walk(root): if child.request_id is None or not child.has_usage(): continue by_request.setdefault(child.request_id, []).append(child) total_input = 0 total_output = 0 for req_id, spans in by_request.items(): if len(spans) > 1 and any(s.attempt is None for s in spans): raise AmbiguousTokenAccounting( f"request_id={req_id!r} appears on {len(spans)} spans but at " f"least one lacks gen_ai.request.attempt; cannot distinguish " f"retries from distinct calls. Refusing to emit cost metric." ) total_input += sum(s.input_tokens for s in spans) terminal = max(spans, key=lambda s: s.attempt or 0) total_output += terminal.output_tokens if root.has_usage() and by_request: raise AmbiguousTokenAccounting( "parent span sets gen_ai.usage.* while children also set it; " "aggregation ownership is undefined (authoritative vs derived)." ) if root.has_usage(): return root.input_tokens, root.output_tokens return total_input, total_output def _walk(span: Span): for child in span.children: yield child yield from _walk(child) # Reproduces the observed billing-reconciler trace: three tool attempts sharing # one request_id, no attempt discriminator -> must raise, not emit 7660. lookup_attempts = [ Span("execute_tool", "execute_tool", request_id="req-77", input_tokens=1180) for _ in range(3) ] root = Span( "invoke_agent", "invoke_agent", request_id="req-77", input_tokens=4120, output_tokens=2047, children=lookup_attempts + [Span("chat", "chat", request_id="req-77", attempt=3, input_tokens=0, output_tokens=2047)], ) try: reconcile_agent_tokens(root) except AmbiguousTokenAccounting as exc: # Quarantine the span tree; do not publish gen_ai.client.token.usage. print(f"quarantined: {exc}") ```