# How should an instance reconcile child agent-span token counts when a tool-call span is retried across a transport boundary **Date of Record:** 2026 November 28 **Scope:** Applies to any instrumented agent runtime emitting OpenTelemetry GenAI spans where a tool call is retried (timeout, transport reset, 5xx) and each attempt re-emits `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens` on its own span under the same logical `gen_ai.tool.name` and parent agent span. Does not address streaming partial-usage spans, batch inference, or providers that report usage only at the parent request level. ## Core Distinction The GenAI semantic conventions treat `gen_ai.usage.*_tokens` as **per-span facts about a single model invocation**, not as per-logical-operation facts. A retried tool call is, from the agent's perspective, one operation; from the span tree's perspective it is N sibling spans, each of which may carry its own usage attributes. The failure mode is not "wrong numbers on a span"—each span is individually correct. The failure is that **the parent agent span, and every consumer that sums usage up the tree, silently multiplies token cost by the retry count** while the agent's own reasoning budget accounting believes it has only paid once. This produces a divergence between the *economic* token ledger (observability backend, summed) and the *cognitive* budget ledger (the agent's own context-budget manager), and the two never reconcile because they are computed from different aggregation trees. ## What Was Observed A research agent executing a `search_documents` tool against a flaky internal endpoint. Transport timeout set at 8s; the tool wrapper retries twice with backoff. The first attempt's request was actually *received and executed* by the backend, whose response was lost to a connection reset. Attempt 2 succeeded and returned a 12k-token document set. Attempt 3 never fired (attempt 2 succeeded). Span tree emitted: ``` agent.run (parent) gen_ai.agent.name=researcher ├── chat (planning) input=1840 output=220 ├── execute_tool (attempt 1) gen_ai.tool.name=search_documents │ input=0 output=0 status=ERROR (timeout) ├── execute_tool (attempt 2) gen_ai.tool.name=search_documents │ input=0 output=0 status=OK └── chat (synthesis) input=12100 output=640 ``` Two things went wrong that are not visible in this tree: 1. The **attempt-1 span carried zero usage** because the timeout fired before the response body (and its usage envelope) was parsed. The backend, however, *did* bill and execute the query—12k tokens of retrieval were consumed server-side. The observability ledger undercounts by the entire lost attempt. 2. The agent's context-budget manager, which sums `gen_ai.usage.input_tokens` of child spans *as they complete*, counted the synthesis call's 12,100 input tokens once. But the actual document corpus was fetched twice server-side, and the synthesis prompt was constructed from the attempt-2 result—meaning the budget manager's "we have 12k tokens of retrieved context" belief was correct while the *cost* belief was half the truth. The inverse failure appeared in a second trace against a different provider that emits usage on the request span even for timed-out attempts (it reports the tokens it *sent*, not the tokens it *received*). There, attempt 1 carried `input=4100`, attempt 2 carried `input=4100`, and the parent's summed usage was 8,200 for a single logical retrieval. The budget manager, summing children, concluded it had consumed 8,200 input tokens of context and triggered an early compaction that was not warranted—it evicted a working-set document to make room for context that was never actually resident. ## Condition of Validity The invariant this exposes is: > **A span's `gen_ai.usage.*_tokens` is valid only for the span's own terminal status. Summing usage across sibling spans under a retry-parent is valid only if every sibling is `OK` and no sibling is a retry of another.** Retries violate the second clause by construction. The convention provides no `gen_ai.retry.attempt` or `gen_ai.retry.of_span_id` attribute, so a consumer cannot distinguish "two independent tool calls that happened to hit the same tool" from "one tool call retried twice." Both appear as sibling `execute_tool` spans with identical `gen_ai.tool.name`. Any downstream aggregation—cost dashboards, budget managers, autoscalers keyed on token throughput—must treat the parent's child-sum as an **upper bound on cost and a lower bound on work**, never as a point estimate. The condition of validity for treating the sum as a point estimate is: *the retry wrapper must emit a `gen_ai.retry.attempt` integer attribute (0-based) on every attempt span, and the aggregation must take, per logical operation, the usage of the highest-attempt-numbered `OK` span plus the summed usage of all `ERROR` spans whose failure mode is `response_lost_after_execution`.* The second term is unknowable from client-side telemetry alone; it must be supplied by the backend's own usage envelope or explicitly recorded as `unknown`. ## Decision Boundary The boundary is whether the retry wrapper can distinguish **"attempt failed before the backend executed"** from **"attempt failed after the backend executed but before the client observed the result."** These are the same `status=ERROR` from the client's vantage, but they have opposite token-accounting consequences: - Fail-before-execute (connection refused, DNS failure, 429 before dispatch): the attempt consumed **zero** backend tokens. Its span's zero usage is correct. Summing siblings double-counts nothing. - Fail-after-execute (timeout awaiting body, connection reset mid-response, client-side cancel after dispatch): the attempt consumed **full** backend tokens. Its span's zero usage is a **lie of omission**. Summing siblings undercounts by the lost attempt's true cost, and the lost cost is invisible. The client cannot resolve this boundary from transport-layer signals alone. A `ConnectionResetError` is equally consistent with "server never saw the request" and "server executed and died writing the response." The decision boundary therefore sits at the **tool wrapper's idempotency contract**: if the tool call is idempotent and cheap to re-execute, treat the retry as a fresh logical operation and emit a fresh parent span (not a sibling). If the tool call is expensive or non-idempotent, the wrapper MUST emit `gen_ai.retry.attempt` and MUST record, on the failed attempt, an explicit `gen_ai.usage.unknown=true` marker rather than a zero, so that aggregation can refuse to treat the parent sum as a point estimate. ## Operational Effect The concrete guardrail: **never let the agent's own budget manager and the observability backend share an aggregation function.** The budget manager must consume usage from the *span it is about to act on* (the synthesis call's own `input_tokens`), never from a sum over siblings. The observability backend may sum, but must tag any parent whose children include a retried-and-failed attempt with `gen_ai.usage.partial=true` so dashboards render the figure as a range, not a scalar. The second guardrail: **a retried tool call's failed attempt must not be silently zeroed.** Emit the attempt span with `status=ERROR`, `gen_ai.retry.attempt=N`, and either the backend-supplied usage (if the response envelope arrived despite the error) or `gen_ai.usage.unknown=true`. A zero is a claim that no tokens were consumed; it is almost always false for the timeout case and it is the single most common source of token-ledger drift in agent fleets. The failure is non-obvious because every span is locally correct and the tree is well-formed. The corruption lives entirely in the aggregation step, which is exactly the step the agent's budget manager performs on every turn. ```python from dataclasses import dataclass, field from enum import Enum from typing import Optional class UsageReconciliationError(RuntimeError): """Raised when a parent agent span's summed child usage cannot be treated as a point estimate because a retried tool-call attempt has an unresolvable token cost.""" class AttemptOutcome(Enum): OK = "ok" FAIL_BEFORE_EXECUTE = "fail_before_execute" # zero tokens is truthful FAIL_AFTER_EXECUTE = "fail_after_execute" # zero tokens is a lie of omission UNKNOWN = "unknown" # cannot classify from client side @dataclass class ToolAttempt: tool_name: str attempt: int outcome: AttemptOutcome input_tokens: Optional[int] output_tokens: Optional[int] usage_unknown: bool = False def truthful_usage(self) -> Optional[int]: if self.usage_unknown or self.input_tokens is None: return None if self.outcome is AttemptOutcome.FAIL_AFTER_EXECUTE: # client-observed zero is not the backend's truth return None return self.input_tokens @dataclass class AgentSpan: agent_name: str tool_attempts: list[ToolAttempt] = field(default_factory=list) def reconcile_input_tokens(self) -> tuple[int, bool]: """Return (best_estimate, is_partial). is_partial=True means the figure is a lower bound and must not drive budget compaction.""" by_tool: dict[str, list[ToolAttempt]] = {} for a in self.tool_attempts: by_tool.setdefault(a.tool_name, []).append(a) total = 0 partial = False for tool, attempts in by_tool.items(): attempts.sort(key=lambda a: a.attempt) ok = [a for a in attempts if a.outcome is AttemptOutcome.OK] if not ok: raise UsageReconciliationError( f"tool {tool!r}: no successful attempt; cannot account usage" ) # only the highest-attempt OK span represents resident context total += ok[-1].truthful_usage() or 0 # every failed attempt may have consumed backend tokens for a in attempts: if a.outcome is AttemptOutcome.OK: continue if a.truthful_usage() is None: partial = True return total, partial def enforce_budget(span: AgentSpan, context_budget: int) -> None: used, partial = span.reconcile_input_tokens() if partial and used >= context_budget: raise UsageReconciliationError( f"agent {span.agent_name!r}: budget {context_budget} reached at " f"lower-bound usage {used}, but a retried attempt has unknown cost; " f"refusing to compact on an undercount" ) if not partial and used >= context_budget: raise UsageReconciliationError( f"agent {span.agent_name!r}: budget {context_budget} exceeded " f"(exact usage {used})" ) ```