# How should an instance reconcile OpenTelemetry GenAI spans when a tool-call chain fragments token usage across nested, retried, and re-entrant spans **Date of Record:** 2026 November 30 **Scope:** Applies to agent runtimes that emit OTel GenAI semantic-convention spans (`gen_ai.*`) for LLM invocations and tool calls, and that derive per-tenant or per-task cost attribution from `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens` summed across spans. Does not apply to single-shot, single-span inference with no tool loop, nor to billing systems that read provider-side invoices directly. ## Core Distinction The GenAI semantic conventions model *an LLM invocation* as a span, and tool execution as a **child** span of the invocation that requested it. This is a call-tree model, and it is correct for latency. It is **wrong for token accounting** the moment a tool result is fed back into a *new* LLM invocation that itself spawns more tools, because the natural parent-child nesting produces a tree where usage tokens live on the *leaf-adjacent* LLM spans while the tool spans in between carry zero usage. Summing `gen_ai.usage.*` over all spans in a trace is then arithmetically fine — but summing over the **subtree of a parent span**, which is what every span-aggregating cost exporter does, is only correct if the tree is a tree. Agent retry loops and re-entrant tool calls make it a **DAG with repeated nodes**, and the convention has no field that marks a span as a re-emission of prior work. The distinction that matters: *span identity* (`trace_id`, `span_id`) is unique per emission, but *work identity* (which tokens were already billed) is not represented anywhere in the convention. Cost attribution requires a work-identity key that the convention does not supply, and the naive sum silently double-counts. ## What Was Observed A three-step agent chain: `plan` (LLM) → `search` (tool) → `synthesize` (LLM) → `verify` (LLM), where `synthesize` failed schema validation and was retried once with the same prompt plus a repair instruction. The emitted trace: ``` span A gen_ai.chat plan usage.in=1200 usage.out=180 span B tool.execute search usage absent span C gen_ai.chat synthesize usage.in=2100 usage.out=400 (attempt 1, failed validation) span D gen_ai.chat synthesize usage.in=2350 usage.out=390 (attempt 2, repair) span E gen_ai.chat verify usage.in=2600 usage.out=90 ``` Two failures surfaced simultaneously. **Failure 1 — retry double-count under subtree aggregation.** The cost exporter walked the subtree rooted at A and summed usage: `1200+180+2100+400+2350+390+2600+90 = 9310` tokens. Actual provider-billed tokens were `1200+180 + 2100+400 + 2350+390 + 2600+90` minus nothing — the retry *was* really billed twice. So far the sum is correct. The error appeared when the exporter deduplicated by `gen_ai.request.model` + prompt hash to "avoid double billing retries": it dropped span D, under-reporting by 2740 tokens, because the repair prompt differed only in a suffix and the hash collided on a truncated prefix. The dedup heuristic assumed retries are *not* billed; providers bill every attempt. There is no `gen_ai.retry.attempt` attribute in the convention to disambiguate, so the exporter invented one and got the semantics backwards. **Failure 2 — orphaned tool cost and re-entrant nesting.** A second run used a tool that itself calls an LLM (a summarizer tool). The runtime emitted: ``` span A gen_ai.chat orchestrator usage.in=900 usage.out=200 span B tool.execute summarize usage absent span C gen_ai.chat summarize usage.in=4000 usage.out=300 ``` The convention says tool spans carry no `gen_ai.usage.*` (they are not LLM invocations), so C's 4300 tokens are attributed to the *tool*, not to the orchestrator's budget. Downstream, a per-agent budget enforcer that summed only spans where `gen_ai.operation.name == "chat"` **and** `parent` is an agent span missed C entirely, because C's parent is a tool span. The budget under-counted by 4300 tokens — 39% of true spend — and the agent ran past its ceiling. The unifying observation: **the call tree encodes causality, not accounting.** Every aggregator that treated the tree as the accounting unit either double-counted retries or dropped re-entrant subtrees, depending on which attribute it filtered on. ## Condition of Validity Subtree summation of `gen_ai.usage.*` is a valid cost attribution **iff** all three hold: 1. **Injectivity of work.** No two spans in the subtree represent the same billed provider call. Holds for a strictly linear chain with no retries. Violated by any retry, fallback model swap, or speculative parallel sampling. 2. **Containment of re-entrancy.** No LLM invocation occurs beneath a `tool.execute` span. Violated by any tool that internally calls a model (summarizers, embedders, sub-agents exposed as tools, code interpreters that invoke an LLM). 3. **Completeness of usage emission.** Every span with `gen_ai.operation.name` in `{chat, text_completion, embeddings}` carries both `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens`. Violated by streaming paths that close the span before the final usage chunk arrives, and by providers that report usage only on a terminal event the SDK drops on cancellation. When any condition fails, subtree sum is not a lower or upper bound on true cost — it is an *unbounded* estimator in either direction, which is why the failure is dangerous: it looks plausible. ## Decision Boundary The boundary is not "use spans vs. don't." It is **which key you aggregate on**. Two regimes: - **Trace-tree aggregation** (sum over subtree, dedup by prompt hash) is admissible only when the chain is provably linear and non-re-entrant — i.e., a single-agent, no-retry, no-LLM-tool pipeline. In practice this is a *degenerate* case; treat it as the exception, not the default. - **Work-key aggregation** is required otherwise. Emit an explicit accounting key on every LLM span — a `gen_ai.request.id` (or a custom `agent.work_key`) that is *stable across retries of the same logical call* and *unique across distinct calls* — and aggregate by `(work_key, attempt)` where `attempt` is monotonic. Re-entrant LLM spans beneath tool spans must be hoisted into the accounting set regardless of parent operation type. The invariant to enforce: **the cost aggregation set is defined by `gen_ai.operation.name ∈ {chat, text_completion, embeddings}`, independent of parent span kind, and every element carries a non-null work_key and attempt.** Parent-child structure is for latency and causality only; it must never gate whether a span's tokens are counted. Retries are counted per attempt, never deduplicated by prompt similarity. ## Operational Effect Enforcing the work-key invariant converts an unbounded estimator into a bounded one: total attributed cost equals the sum over `(work_key, attempt)` of emitted usage, which is a *superset* of true billed calls (safe over-count when a span is emitted but the call was cancelled before billing) and equals true cost when usage emission is complete. The residual error is bounded by cancellation races, not by tree topology. Practically, this means the runtime must (a) stamp a work_key at the point of logical call construction, before retry wrapping, so retries inherit it; (b) propagate that key through tool invocation so re-entrant LLM calls inherit the *calling agent's* work_key lineage rather than starting a new root; and (c) reject at emission time any LLM span lacking a work_key, because such a span is unattributable and will corrupt every downstream sum. The budget enforcer then reads a flat set, not a tree, and the double-count/orphan failure modes vanish by construction. The cost is one extra attribute and a lineage-propagating context variable — cheap relative to the 39% budget overrun it prevents. ```python from dataclasses import dataclass from typing import Iterable LLM_OPS = {"chat", "text_completion", "embeddings"} class CostAttributionError(RuntimeError): """Raised when a GenAI span cannot be attributed to a billed work unit.""" @dataclass(frozen=True) class GenAISpan: span_id: str parent_id: str | None operation_name: str # gen_ai.operation.name work_key: str | None # stable across retries; unique per logical call attempt: int | None # monotonic retry counter input_tokens: int | None output_tokens: int | None def attribute_cost(spans: Iterable[GenAISpan]) -> dict[tuple[str, int], int]: """ Aggregate tokens by (work_key, attempt) across ALL LLM spans, regardless of parent span kind. Re-entrant LLM calls under tool spans are included; retries are counted per attempt, never deduped. """ totals: dict[tuple[str, int], int] = {} for s in spans: if s.operation_name not in LLM_OPS: continue if s.work_key is None or s.attempt is None: raise CostAttributionError( f"LLM span {s.span_id} ({s.operation_name}) lacks work_key/attempt; " "unattributable and would corrupt subtree sums" ) if s.input_tokens is None or s.output_tokens is None: raise CostAttributionError( f"LLM span {s.span_id} missing usage tokens; " "streaming close-before-usage would under-count" ) key = (s.work_key, s.attempt) totals[key] = totals.get(key, 0) + s.input_tokens + s.output_tokens return totals def enforce_no_reentrant_gap(spans: list[GenAISpan]) -> None: """Fail loudly if an LLM span hides beneath a tool span without a work_key lineage.""" by_id = {s.span_id: s for s in spans} for s in spans: if s.operation_name not in LLM_OPS: continue parent = by_id.get(s.parent_id) if s.parent_id else None if parent and parent.operation_name == "tool.execute" and s.work_key is None: raise CostAttributionError( f"re-entrant LLM span {s.span_id} under tool {parent.span_id} " "has no inherited work_key; budget enforcer would orphan it" ) ```