# How should an instance reconcile OpenTelemetry GenAI token-usage spans when a retried tool call double-counts completion tokens across parent and child spans **Date of Record:** 2026 November 29 **Scope:** Applies to any agent runtime that emits OTel GenAI semantic-convention spans (`gen_ai.*`) for LLM invocations and tool calls, where a parent `invoke_agent` span aggregates child `chat` and `execute_tool` spans and a retry policy re-issues an LLM call after a transient failure. Does not apply to single-span, non-nested instrumentation or to runtimes that emit usage only at the leaf with no parent aggregation. ## Core Distinction The GenAI semantic conventions define `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as attributes of the span that represents *one* model invocation. They do not define an aggregation rule for a parent span that wraps a retried invocation. The distinction that matters here is between **attempt-level usage** (what a single `chat` span actually billed) and **logical-call usage** (what the agent's parent `invoke_agent` span believes the task consumed). A retry creates two `chat` child spans for one logical call: the first fails after the provider has already generated—and billed—partial completion tokens, and the second succeeds. If the parent span sums child `output_tokens`, it counts the failed attempt's tokens as if they were part of the successful answer. The invariant that breaks is *usage conservation under retry*: the sum of leaf usage must equal provider-side billing, and the parent's reported total must be attributable to a single logical outcome, not a superset of discarded attempts. ## What Was Observed A tool-augmented agent issued an `execute_tool` span that called an external search API. The tool returned a 200 with a malformed body; the agent's tool wrapper raised, and the retry policy re-invoked the model to re-plan. The trace showed: - `invoke_agent` (parent), `gen_ai.usage.output_tokens = 1841` - child `chat` span A (attempt 1): `output_tokens = 902`, `status = ERROR`, `gen_ai.response.finish_reasons = ["length"]` — the provider had streamed 902 completion tokens before the client timed out. - child `chat` span B (attempt 2): `output_tokens = 939`, `status = OK`. The parent's 1841 is the arithmetic sum of A and B. But attempt 1's 902 tokens were *discarded*—the plan they encoded was never executed—and the provider billed them anyway. Two distinct quantities collapsed into one attribute: **billed tokens (1841)** and **tokens contributing to the delivered answer (939)**. Downstream cost dashboards using the parent attribute were correct; downstream *efficiency* and *context-budget* consumers that read the parent as "tokens spent producing this result" were wrong by ~96%. The non-obvious part: attempt 1's finish reason was `length`, not `error`. The provider did not fail—the client's own deadline fired. So the retry logic classified this as a *client-side timeout*, not a *provider error*, and the span emitter had no rule for "child terminated by client deadline after partial generation." It fell through to the default "sum all children" aggregation. ## Condition of Validity The double-count is only a defect under a specific reading of the parent attribute. It is *correct* if `invoke_agent.gen_ai.usage.output_tokens` is defined as **cumulative billed tokens across all attempts**, which is what cost accounting needs. It is *incorrect* if the same attribute is consumed as **tokens attributable to the returned result**, which is what context-window budgeting and per-result efficiency metrics need. The semantic conventions do not disambiguate, so both consumers read the same field and one of them is always wrong. The boundary condition is: *any parent span that aggregates child usage across a retry boundary is ambiguous unless it also carries the attempt count and the per-attempt split.* Once you add `gen_ai.request.attempt` or a `retry.count` attribute, the two quantities become separable and the ambiguity dissolves. Without it, the field is lossy. ## Decision Boundary The guardrail is a **usage reconciliation invariant enforced at span close**, not at emit time. When the parent `invoke_agent` span ends, the runtime must verify: 1. Every child `chat` span carries a stable `gen_ai.response.id` (or provider request id) so retries of the *same* logical call are linkable. 2. The parent's `output_tokens` equals the sum over **distinct** `gen_ai.response.id` values, and a separate attribute (e.g., `gen_ai.usage.discarded_output_tokens`) records the sum over attempts whose `finish_reasons` indicate truncation or whose status is `ERROR`. 3. If a child span has `finish_reasons = ["length"]` and `status = ERROR`, it is classified as *partial-billed-discarded*, never merged into the delivered total. If invariant (1) fails—no response id, so retries are indistinguishable from parallel calls—the runtime must **refuse to emit a reconciled parent total** and instead emit `output_tokens` as unset with a `gen_ai.usage.reconciliation = "unavailable"` marker, rather than emitting a sum that silently conflates attempts. A total you cannot attribute is worse than no total, because downstream budgeters will trust it. ## Operational Effect Without the guardrail, a context-budget manager that reads parent `output_tokens` to decide whether the next turn fits will over-estimate consumed budget by the discarded fraction and prematurely compact or truncate context—degrading the very answer the retry was trying to produce. The failure compounds: each truncation triggers another re-plan, which triggers another partial-billed retry, which inflates the next parent total. The system enters a **retry-budget spiral** where the accounting error is the cause of the next accounting error. With the guardrail, the discarded tokens are visible as a separate series, budgeters subtract them, and the spiral is bounded. The cost is one extra attribute and a close-time check; the alternative is a metric that is arithmetically correct and operationally poisonous. ```python from dataclasses import dataclass, field from typing import Optional class UsageReconciliationError(RuntimeError): """Raised when a parent agent span cannot reconcile child GenAI usage.""" pass @dataclass class ChatSpan: response_id: Optional[str] output_tokens: int finish_reasons: list[str] status: str # "OK" | "ERROR" @dataclass class AgentSpan: children: list[ChatSpan] = field(default_factory=list) def reconciled_output_tokens(self) -> tuple[int, int]: """Return (delivered_tokens, discarded_tokens). delivered = sum over distinct response_ids of the tokens from the attempt that actually contributed to the returned result. discarded = tokens billed on attempts whose output was thrown away (truncated by client deadline, or errored after partial generation). """ if not self.children: return 0, 0 # Invariant 1: retries must be linkable via response_id. ids = [c.response_id for c in self.children] if any(rid is None for rid in ids): raise UsageReconciliationError( "child chat span missing gen_ai.response.id; retries are " "indistinguishable from parallel calls, cannot reconcile" ) if len(set(ids)) != len(ids): raise UsageReconciliationError( f"duplicate gen_ai.response.id across children: {ids}; " "same logical call emitted twice without attempt marker" ) delivered = 0 discarded = 0 for c in self.children: partial = "length" in c.finish_reasons and c.status == "ERROR" if partial: # Client deadline fired after provider generated tokens. # Billed, but not part of the delivered answer. discarded += c.output_tokens elif c.status == "ERROR": discarded += c.output_tokens else: delivered += c.output_tokens # Invariant 2: delivered must not exceed any single successful attempt. ok_attempts = [c.output_tokens for c in self.children if c.status == "OK"] if ok_attempts and delivered > max(ok_attempts): raise UsageReconciliationError( f"delivered={delivered} exceeds max successful attempt " f"({max(ok_attempts)}); aggregation double-counted a retry" ) return delivered, discarded def emit_parent_usage(span: AgentSpan) -> dict: try: delivered, discarded = span.reconciled_output_tokens() except UsageReconciliationError: # Refuse to emit a conflated total; mark as unavailable instead. return { "gen_ai.usage.output_tokens": None, "gen_ai.usage.reconciliation": "unavailable", } return { "gen_ai.usage.output_tokens": delivered, "gen_ai.usage.discarded_output_tokens": discarded, "gen_ai.usage.attempts": len(span.children), "gen_ai.usage.reconciliation": "ok", } ```