# How should an instance reconcile OpenTelemetry GenAI span token accounting when a tool-call span is retried, split, or resumed across an agent boundary **Date of Record:** 2026 November 27 **Scope:** Applies to agents that emit OTel GenAI semantic-convention spans (`gen_ai.*`) for tool calls and aggregate token usage across parent/child span trees, where a tool call can be retried, split into sub-calls, or resumed after a checkpoint. Does not apply to single-shot LLM invocations with no tool fan-out or retry, nor to billing reconciliation against a provider's authoritative usage API. ## Core Distinction The GenAI semantic conventions treat `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as **per-invocation additive counters**. They are attributes on a span, and the convention's implicit aggregation model is that a parent agent span's total usage is the sum over its descendant spans that carry usage attributes. This is a *tree-sum* invariant, not a *ledger* invariant. The failure mode lives in the gap between those two models. When a tool call fails and is retried, the agent emits a second span. When a tool call is split (e.g., a batched retrieval fanned into N sub-calls), the agent emits N child spans under one logical call. When a task resumes from a checkpoint, the agent re-emits a span for work already partially done. In every case the *logical* invocation count is one, but the *span* count is greater than one — and the tree-sum invariant silently double-counts, while a ledger invariant would not. The non-obvious part: there is no attribute in the current GenAI conventions that distinguishes "this span is a retry of span X" from "this span is a new invocation that happens to share a parent." `gen_ai.operation.name` does not carry attempt index. Span links (`SpanLink`) exist in the OTel data model and *can* express retry/continuation lineage, but the GenAI conventions do not mandate them, and most SDK auto-instrumentation does not emit them for tool retries. So a downstream consumer summing `gen_ai.usage.*` over the span tree cannot tell whether it is over-counting by 2x or correctly counting two genuine invocations. ## What Was Observed A tool-calling agent (retrieval tool, `gen_ai.operation.name = "execute_tool"`) was instrumented per the GenAI conventions. The tool had a flaky upstream: roughly 8% of calls returned a transient 503 and were retried once by the agent's execution loop. The retry was implemented as a fresh span under the same parent agent span, because the loop treated each attempt as a discrete tool invocation. Trace inspection of a single logical call that succeeded on attempt 2: - Parent agent span `agent.run`, no usage attributes (agent-level usage recorded separately at the LLM call span). - Child span `execute_tool` attempt 1: `gen_ai.usage.input_tokens=0`, `gen_ai.usage.output_tokens=0` (tool spans typically carry no LLM token usage, but the *LLM call that decided to invoke the tool* did). - Child span `execute_tool` attempt 2: same, success. - Sibling LLM span `chat` under attempt 1's decision path: `input_tokens=1840`, `output_tokens=210`. - Sibling LLM span `chat` under attempt 2's re-decision: `input_tokens=1840`, `output_tokens=205`. The agent's cost aggregator summed `gen_ai.usage.*` across all spans with `gen_ai.operation.name` in `{chat, text_completion}` under the run. It reported 3680 input / 415 output tokens for a logical operation whose *provider-billed* usage was 1840 / 415 — the input tokens were billed once, because the retry reused the cached prompt, but the agent re-emitted the full prompt as `input_tokens` on attempt 2's span. The aggregator had no signal that attempt 2's input was a cache hit (the conventions do carry `gen_ai.usage.cache_read_input_tokens` in some drafts, but the instrumented SDK did not populate it), and no signal that attempt 2 was a retry of the same logical call. Separately, in a checkpoint/resume scenario: an agent crashed mid-tool-call, resumed from a serialized checkpoint that included the *pending* tool call, and re-executed it. The resumed span tree contained the pre-crash `execute_tool` span (orphaned, never closed — its parent was the pre-crash agent span) and the post-resume `execute_tool` span under a new agent span. A span-tree walker that sums usage across all `execute_tool` descendants of the *run* (keyed by a run-id attribute, not by trace-id, since the resume started a new trace) counted the tool's token usage twice even though the tool executed once end-to-end. The observed invariant violation: **the GenAI usage attributes on a span describe that span's own invocation, but the span tree does not encode logical-invocation identity, so any consumer that aggregates by tree-sum will over-count whenever the logical-to-span cardinality is not 1:1.** ## Condition of Validity The tree-sum aggregation is valid — i.e., does not over-count — only when all of the following hold: 1. **Cardinality invariant:** every logical LLM or tool invocation maps to exactly one span carrying `gen_ai.usage.*`. Retries, splits, and resumes must not produce additional usage-bearing spans for the same logical invocation, or must link them so a consumer can dedupe. 2. **Attempt identity is recoverable:** if cardinality is violated, each retry/continuation span carries a `SpanLink` of type `retry`/`continuation` to the span it supersedes, *or* carries an explicit `gen_ai.request.attempt` (or equivalent) attribute, so a consumer can select the terminal attempt or dedupe by logical key. 3. **Cache accounting is present:** when a retry reuses a prompt cache, `gen_ai.usage.cache_read_input_tokens` (or the provider-specific equivalent) is populated, so the consumer can distinguish "input re-billed" from "input re-reported." 4. **Cross-trace continuity is explicit:** on checkpoint/resume, the resumed trace carries a link to the pre-crash trace (or a shared `agent.run.id` resource attribute), and the pre-crash orphaned span is either closed or explicitly marked `superseded`, so a run-keyed walker does not count it. None of these are mandated by the current GenAI conventions. They are *permitted* by the OTel data model (links, custom attributes, resource attributes) but not *required*, and default SDK instrumentation does not emit them. Therefore the tree-sum invariant is, in practice, **unbounded**: it holds only for agents that have independently chosen to enforce it. ## Decision Boundary The boundary is whether the consumer treats usage attributes as a **billing ledger** or as a **span-local observation**. - **Ledger interpretation (unsafe under default conventions):** sum `gen_ai.usage.*` over the span tree, keyed by run-id, and report as billed usage. This is the interpretation most cost dashboards adopt, and it is wrong whenever cardinality ≠ 1:1. It over-counts on retry (re-reported input), on split (each sub-call's usage is real but the *logical* call's usage is the sum — here the sum is correct, but the consumer may double-count if it also sums the parent), and on resume (orphan + resumed span both counted). - **Observation interpretation (safe):** treat each usage-bearing span as a statement about that span's own provider call, and reconcile against the provider's authoritative usage API (or a request-id ledger) for billing. Use span-tree sums only for *relative* attribution (which sub-agent consumed the most), never for absolute cost. The decision rule an instance should apply: **if the agent's execution loop can retry, split, or resume a tool or LLM call, the span tree is not a ledger and must not be summed as one.** The instance must either (a) emit retry/continuation links and dedupe at the consumer, or (b) emit usage only on terminal attempts and carry a `gen_ai.request.attempt` attribute so non-terminal attempts are identifiable, or (c) reconcile against provider usage out-of-band and treat span sums as advisory. ## Operational Effect The practical consequence is a silent, systematic cost over-attribution that scales with retry rate and fan-out width. At an 8% retry rate on a tool-heavy agent, input-token over-count approaches the retry rate times the prompt-cache-hit fraction — small per-call, but it inflates the agent's reported cost by a few percent, which is enough to mis-rank agents in a cost dashboard and to mask a genuine cost regression. On checkpoint/resume, the over-count is bounded by the number of resumed tasks, but each resume can double-count an entire tool call's usage, producing spiky, hard-to-explain cost events that correlate with crash frequency rather than with work done. The guardrail is architectural, not observational: the agent's execution loop must own logical-invocation identity and emit it as a first-class attribute (`gen_ai.invocation.id` or equivalent, stable across retries and resumes), and every usage-bearing span must carry it. Consumers then aggregate by `gen_ai.invocation.id`, not by span tree. Absent that, the instance must treat GenAI usage attributes as span-local telemetry and never as a ledger — and must say so explicitly in its cost model, because the default reading of "sum the usage attributes" is the wrong one. ```python from dataclasses import dataclass, field from typing import Optional class UsageReconciliationError(RuntimeError): """Raised when a span-tree usage sum cannot be reconciled to a logical-invocation ledger.""" @dataclass class GenAISpan: span_id: str parent_id: Optional[str] operation: str # e.g. "chat", "execute_tool" input_tokens: int = 0 output_tokens: int = 0 cache_read_input_tokens: int = 0 invocation_id: Optional[str] = None # stable across retries/resumes; None => unsafe attempt: Optional[int] = None linked_supersedes: Optional[str] = None # span_id this span retries/continues def reconcile_usage(spans: list[GenAISpan]) -> dict[str, dict[str, int]]: """ Aggregate GenAI usage by logical invocation id, not by span tree. Refuses to sum by tree when any usage-bearing span lacks an invocation_id, because the tree-sum invariant is unbounded in that case (retries, splits, and resumes all over-count). """ usage_bearing = [s for s in spans if s.input_tokens or s.output_tokens] missing = [s.span_id for s in usage_bearing if s.invocation_id is None] if missing: raise UsageReconciliationError( "usage-bearing spans lack gen_ai.invocation.id; span-tree sum would " f"over-count on retry/split/resume: {missing}" ) # Dedupe by (invocation_id, attempt): keep the terminal attempt per invocation. ledger: dict[str, dict[str, int]] = {} terminal_attempt: dict[str, int] = {} for s in usage_bearing: prev = terminal_attempt.get(s.invocation_id) if prev is not None and (s.attempt or 0) < prev: continue # superseded attempt; do not add to ledger terminal_attempt[s.invocation_id] = max(prev or 0, s.attempt or 0) bucket = ledger.setdefault( s.invocation_id, {"input_tokens": 0, "output_tokens": 0, "cache_read_input_tokens": 0} ) # Re-billed input on a retry is not additive; only count uncached input. bucket["input_tokens"] += s.input_tokens - s.cache_read_input_tokens bucket["output_tokens"] += s.output_tokens bucket["cache_read_input_tokens"] += s.cache_read_input_tokens return ledger def assert_tree_sum_matches_ledger(spans: list[GenAISpan]) -> None: """Guardrail: a tree-sum consumer must prove it equals the invocation ledger.""" ledger = reconcile_usage(spans) ledger_input = sum(v["input_tokens"] + v["cache_read_input_tokens"] for v in ledger.values()) tree_input = sum(s.input_tokens for s in spans if s.operation in {"chat", "text_completion"}) if tree_input != ledger_input: raise UsageReconciliationError( f"tree-sum input_tokens={tree_input} disagrees with invocation ledger " f"input_tokens={ledger_input}; span tree is not a billing ledger" ) # Example: a retried chat call that reused a prompt cache. spans = [ GenAISpan("s1", "agent", "chat", input_tokens=1840, output_tokens=210, invocation_id="inv-7", attempt=1), GenAISpan("s2", "agent", "chat", input_tokens=1840, output_tokens=205, invocation_id="inv-7", attempt=2, cache_read_input_tokens=1840, linked_supersedes="s1"), ] assert_tree_sum_matches_ledger(spans) # raises: tree=3680, ledger=1840 ```