# What happens when an instance emits OpenTelemetry GenAI spans across a tool-call boundary without reconciling token accounting against the parent agent span **Date of Record:** 2026 November 20 **Scope:** Applies to LLM-backed agent runtimes that emit OpenTelemetry GenAI semantic convention spans (`gen_ai.*` attributes) per tool call and per model invocation, and that aggregate token counts upward to a parent agent span. Does not apply to single-shot inference services with no tool loop, nor to runtimes that delegate accounting entirely to a gateway that owns the span tree. ## Core Distinction The GenAI semantic conventions define token attributes (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) at the *inference span* level, and separately define agent/tool spans (`gen_ai.agent.*`, `gen_ai.tool.*`) that describe orchestration. The conventions deliberately do **not** mandate how child inference spans roll up into a parent agent span. This is a real gap, not an oversight: an agent span may fan out to N inference calls across M tool invocations, and the "correct" aggregate is ambiguous because **retries, streaming partials, and tool-result re-feeds each produce inference spans that consume tokens but are not logically distinct reasoning steps.** The failure boundary is this: an instance that treats the parent agent span's token total as the sum of all child `gen_ai.usage.*` values will **overcount** whenever a tool call is retried, a stream is re-issued after a transport drop, or a tool result is re-fed into a second inference to recover from a malformed response. The overcount is silent—no span is marked error—and it corrupts every downstream metric (cost attribution, budget enforcement, cache-hit ratio) that trusts the aggregate. ## What Was Observed A three-step agent (plan → tool call → synthesize) was instrumented with one `gen_ai.agent.invoke` parent span and child spans per model call and per tool call. The tool call to an external HTTP endpoint returned a 503 on the first attempt; the runtime's retry wrapper re-issued the request. The second attempt succeeded. The runtime emitted **two** `gen_ai.tool.execute` spans (correct—both attempts happened) but only **one** inference span for the tool-argument-generation step, because the runtime cached the argument object across the retry. The parent agent span aggregated tokens as `sum(child.gen_ai.usage.input_tokens) + sum(child.gen_ai.usage.output_tokens)`. Because the retry reused cached arguments, no extra inference span existed—yet the runtime's *budget enforcer*, which tracked tokens at the HTTP client layer, had already charged the first (failed) attempt's argument-generation tokens against the session. The two accounting surfaces disagreed by the size of one argument-generation call. The divergence was discovered only when a downstream cost dashboard showed a 4.1% variance against the billing provider's invoice over a 24-hour window—within noise for most teams, but fatal for a per-tenant budget that must not exceed a hard cap. A second, sharper case: streaming inference where the transport dropped mid-stream after 900 output tokens had been emitted. The runtime re-issued the request; the second stream produced 1,100 tokens including the re-generated prefix. The parent span recorded 2,000 output tokens. The model provider charged for 1,100 (the first stream was truncated and not billed past the drop point under the provider's partial-billing policy). The span tree was internally consistent but **externally wrong by 900 tokens**, and no attribute on any span recorded that a re-issue had occurred. ## Condition of Validity The roll-up invariant holds **only if** every inference span that consumed billable tokens is represented exactly once in the child set, and no inference span represents tokens that were not billed. This is violated by three concrete conditions: 1. **Retry-with-cache:** a failed attempt whose tokens were charged but whose span was suppressed because the *logical* operation was retried. The span tree under-represents consumption. 2. **Stream re-issue:** a dropped stream whose partial tokens were charged but whose span carries only the final, re-generated total. The span tree mis-represents consumption (neither under nor over, but wrong). 3. **Tool-result re-feed:** a malformed tool result that triggers a second inference to repair the call. Both inference spans are real and billed, but runtimes that dedupe by `gen_ai.operation.name` collapse them and lose one. The invariant is *not* violated by parallel fan-out (multiple distinct inference spans, each billed once) or by speculative decoding (provider-side, not visible at the span layer). It is violated whenever **the mapping from billable token events to spans is not injective.** ## Decision Boundary The architectural guardrail is a **span-emission contract** enforced at the instrumentation boundary, not at the aggregation layer: - Every billable token event MUST produce exactly one inference span, even if the logical operation is retried. The span carries `gen_ai.request.is_retry = true` (or equivalent custom attribute) and the retry index. - The parent agent span MUST NOT compute its token total by summation. It MUST carry a `gen_ai.usage.*` value derived from a **ledger**—an append-only record of token events keyed by a deterministic `event_id`—so that retries and re-issues are counted once and only once. - Aggregation MUST be a *reconciliation* step: parent total = ledger sum; child span sum = audit surface. Divergence between the two is a first-class signal, not a rounding error. The boundary condition: if the runtime cannot guarantee injective span emission (e.g., because it uses a third-party SDK that suppresses retry spans), it MUST mark the parent agent span `gen_ai.usage.reconciled = false` and refuse to emit a token total. A missing total is recoverable; a wrong total poisons every downstream consumer. ## Operational Effect Without the contract, three failure modes propagate: - **Budget enforcement drifts.** Per-tenant caps either over-fire (killing sessions that were under budget) or under-fire (billing overruns). The drift is non-stationary because retry rates vary by tool and by provider. - **Cost attribution becomes unauditable.** Finance cannot reconcile span-derived cost against provider invoices, so the observability layer loses its authority as a source of truth. - **Cache-hit and efficiency metrics invert.** A runtime that retries aggressively looks *more* efficient per span (fewer spans per successful call) while consuming *more* tokens—the metrics move in opposite directions and the dashboard lies. The recovery procedure is to replay the ledger against the span tree over a fixed window, emit a `gen_ai.reconciliation.mismatch` event per divergent agent span, and backfill `is_retry` / `reissue_index` attributes on the suppressed spans. Until reconciliation completes, the affected tenant's budget enforcer must run in advisory mode. ```python from dataclasses import dataclass, field from typing import Iterable class TokenAccountingMismatch(RuntimeError): """Raised when a parent agent span's token total diverges from the ledger.""" @dataclass class TokenEvent: event_id: str span_id: str input_tokens: int output_tokens: int is_retry: bool = False @dataclass class AgentSpan: span_id: str child_span_ids: list[str] = field(default_factory=list) reported_input: int = 0 reported_output: int = 0 def reconcile(span: AgentSpan, ledger: Iterable[TokenEvent], tolerance: int = 0) -> tuple[int, int]: """Return (input, output) from the ledger, raising if it disagrees with the span total.""" events = list(ledger) # Enforce injective mapping: one event per span_id, retries counted once. seen: dict[str, TokenEvent] = {} for ev in events: if ev.span_id in seen and not ev.is_retry: raise TokenAccountingMismatch( f"duplicate non-retry token event for span {ev.span_id}: " f"{seen[ev.span_id].event_id} vs {ev.event_id}" ) seen[ev.span_id] = ev ledger_in = sum(ev.input_tokens for ev in seen.values()) ledger_out = sum(ev.output_tokens for ev in seen.values()) if abs(ledger_in - span.reported_input) > tolerance or abs(ledger_out - span.reported_output) > tolerance: raise TokenAccountingMismatch( f"span {span.span_id}: reported=({span.reported_input},{span.reported_output}) " f"ledger=({ledger_in},{ledger_out})" ) return ledger_in, ledger_out ```