# What structural signals indicate token-accounting drift in OpenTelemetry GenAI agent spans when tool-call attributes and usage semantics diverge mid-trace **Date of Record:** 2026 November 22 **Scope:** Applies to agent runtimes emitting OpenTelemetry spans under the GenAI semantic conventions (`gen_ai.*`) where a single logical agent invocation is decomposed into nested spans (agent → LLM call → tool call) and token usage is aggregated across that tree. Does not cover single-shot completion logging, non-OTel telemetry pipelines, or cost attribution across billing tenants. ## Core Distinction The GenAI semantic conventions treat `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as **per-span measurements of a single model invocation**, and treat tool calls as **sibling spans** under the LLM span that requested them, carrying `gen_ai.tool.name` and `gen_ai.tool.call.id` rather than token attributes. The subtle invariant this rests on is that **the sum of usage attributes over the leaf LLM spans of a trace equals the true token consumption of the agent turn**. That invariant silently breaks when an agent framework performs *retries, speculative/parallel tool fan-out, or context re-serialization between spans* — because each of those events can produce a real model invocation that either (a) emits a span without usage attributes, (b) emits usage attributes on a span that is not a leaf, or (c) re-emits usage for tokens already counted in a parent. The distinction that matters operationally: a **missing** usage attribute and a **double-counted** usage attribute produce the same downstream symptom (a wrong total) but require opposite remediation, and OTel span structure alone cannot tell them apart without a correlation key. ## What Was Observed A tool-using agent (planner → executor → verifier loop) was instrumented with `gen_ai` spans. During normal operation the trace tree looked correct: one `invoke_agent` root, one `chat` span per LLM turn carrying `gen_ai.usage.*`, and `execute_tool` child spans carrying `gen_ai.tool.name` and `gen_ai.tool.call.id`. Aggregate input tokens matched the provider dashboard within 0.3%. Under load, three structural anomalies appeared in the same trace shapes: 1. **Orphaned usage on retried chat spans.** When the provider returned a 429 and the SDK retried internally, the retry produced a *second* `chat` span with identical `gen_ai.request.model` and identical `gen_ai.tool.call.id` set, but the runtime copied the usage attributes from the first attempt onto the retry span as well. The trace now contained two leaf `chat` spans whose `gen_ai.tool.call.id` sets were identical. Summing usage over leaves over-counted by exactly the retried turn's tokens. The signal: **duplicate `gen_ai.tool.call.id` across sibling leaves** is the fingerprint of a retry that was mis-emitted as a fresh invocation rather than as a retry event on the same span. 2. **Usage attached to a non-leaf `chat` span.** When the planner batched three tool calls into one model response, the runtime emitted a single `chat` span with usage, then three `execute_tool` children, then a *follow-up* `chat` span that re-sent the accumulated tool results. The follow-up span's `gen_ai.usage.input_tokens` included the entire prior context (correct per the convention — it is a real invocation), but the runtime also propagated a `gen_ai.usage.input_tokens` attribute onto the *parent* `invoke_agent` span equal to the sum of its children. Any consumer that summed "all spans with usage attributes" double-counted every token. The signal: **a span that has child spans and also carries `gen_ai.usage.*`** is a rollup, not a measurement, and must be excluded from leaf summation. 3. **Tool-call attribute drift across a context re-serialization.** When the executor truncated tool output to fit the context window, it re-emitted the tool result into the next `chat` request but dropped the `gen_ai.tool.call.id` linkage (the truncated result was inlined as plain text). The next `chat` span therefore had a `gen_ai.tool.name` reference in its prompt but **no matching `execute_tool` span and no `gen_ai.tool.call.id`**. The token accounting stayed correct, but the trace could no longer prove which tool produced the tokens — a verification gap, not an accounting gap. The signal: **a `chat` span whose prompt references a tool result with no corresponding `execute_tool` span in the trace** indicates linkage loss, and any auditor recomputing cost-per-tool will silently attribute those tokens to "model overhead." In all three cases the total was wrong, but the *structural* fingerprint differed: duplicate call IDs (retry), parent-with-children-and-usage (rollup), and dangling tool references (linkage loss). ## Condition of Validity The leaf-summation invariant holds **only if** all of the following are enforced at emit time: - **Exactly one leaf `chat` span per real model invocation**, with retries recorded as span *events* (`gen_ai.retry` event with attempt number) on the same span, not as new sibling spans. If the SDK creates a new span per attempt, the invariant is void unless a dedup key exists. - **Usage attributes appear only on spans with no `chat`/`execute_tool` children.** Rollups belong in a separate metric (`gen_ai.client.token.usage` histogram), never as span attributes on a parent. - **Every `gen_ai.tool.call.id` that appears in a `chat` span's request context has a corresponding `execute_tool` span in the same trace**, or an explicit `gen_ai.tool.call.status = "truncated"` marker on the `chat` span. - **`gen_ai.tool.call.id` is globally unique within a trace** (UUID or trace-scoped counter). If the runtime reuses call IDs across retries, dedup by ID alone is unsafe and you must also compare `gen_ai.request.model` and span start time. When any of these is violated, the aggregate token number is not merely imprecise — it is *unbounded* in error direction, because retries and rollups both inflate and linkage loss deflates, and the two can cancel to a plausible-looking but wrong total. ## Decision Boundary The operational decision is **when to trust a summed token count from a trace versus when to quarantine the trace and fall back to provider-side billing records**. The boundary is crossed when the structural preconditions above fail in a way that cannot be resolved by a deterministic rule applied to span attributes alone. Concretely: - **Trust the sum** if every `chat` span is a leaf, call IDs are unique, and all tool references resolve. This is the common case and requires no external data. - **Reconcile against provider usage** if duplicate call IDs or parent-with-usage spans are present — the trace is *repairable* by deduping on `(gen_ai.tool.call.id, span start time)` and excluding non-leaf usage, but the repair must be validated against an authoritative source before the number is used for cost attribution. - **Quarantine the trace** if tool references dangle *and* the trace spans a context re-serialization boundary (detectable by a `chat` span whose `gen_ai.request.messages` count drops between consecutive turns). Here the tokens are real but unattributable, and no span-level rule can recover the mapping; the trace must be flagged as `incomplete` and excluded from per-tool cost rollups. The boundary is *not* "does the total match billing" — a matching total can hide two compensating errors. The boundary is structural: **can every emitted usage attribute be assigned to exactly one leaf invocation and one resolvable tool context?** If yes, sum. If no, reconcile. If the linkage is unrecoverable, quarantine. ## Operational Effect Emitting a trace that violates the leaf-summation invariant does not just produce a wrong dashboard number — it **poisons downstream verification**. An auditor agent that recomputes cost-per-tool from spans will, in the retry case, attribute the retried turn's tokens to the tool that triggered it, inflating that tool's apparent cost and potentially causing the planner to *de-prioritize a correct tool* on the next turn. In the linkage-loss case, the auditor sees tokens with no tool attribution and may conclude the model is "wasting" context, triggering an unnecessary context-compaction step that drops the very tool result that was needed. The failure compounds because the auditor's corrective action is itself a state mutation driven by a corrupted measurement. The guardrail is to make the invariant **checkable at emit time, not at query time**: the instrumentation layer should refuse to close a `chat` span if it carries usage and has `chat`/`execute_tool` children, and should emit a `gen_ai.tool.call.id` set on every `chat` span so that dangling references are detectable by set difference. A trace that fails these checks should be tagged `gen_ai.trace.accounting = "unreliable"` so that any consumer — human or agent — knows the sum is advisory. The correction is structural and cheap; the cost of skipping it is a self-reinforcing loop where bad accounting drives bad agent decisions. ```python from dataclasses import dataclass, field from typing import Optional class TokenAccountingDriftError(RuntimeError): """Raised when a GenAI trace's span structure violates the leaf-summation invariant.""" @dataclass class GenAISpan: name: str attributes: dict = field(default_factory=dict) children: list = field(default_factory=list) start_time: float = 0.0 @property def has_usage(self) -> bool: return "gen_ai.usage.input_tokens" in self.attributes or \ "gen_ai.usage.output_tokens" in self.attributes @property def tool_call_ids(self) -> set: raw = self.attributes.get("gen_ai.tool.call.id", "") return {x for x in raw.split(",") if x} if raw else set() @property def is_leaf(self) -> bool: return not self.children def validate_leaf_summation(root: GenAISpan) -> int: """ Returns the trusted total input tokens, or raises TokenAccountingDriftError if the trace structure makes the sum unreliable. """ leaves = [] stack = [root] while stack: span = stack.pop() if span.has_usage and not span.is_leaf: raise TokenAccountingDriftError( f"span {span.name!r} carries usage but has children; " f"rollup usage must go to a metric, not a span attribute" ) if span.is_leaf and span.name == "chat": leaves.append(span) stack.extend(span.children) seen_ids: dict = {} total = 0 for leaf in leaves: for cid in leaf.tool_call_ids: key = (cid, leaf.start_time) if cid in seen_ids and seen_ids[cid] != leaf.start_time: raise TokenAccountingDriftError( f"duplicate gen_ai.tool.call.id {cid!r} across sibling chat spans " f"at {seen_ids[cid]} and {leaf.start_time}; likely a retry emitted " f"as a new span — dedupe or emit as a span event before summing" ) seen_ids[cid] = leaf.start_time total += int(leaf.attributes.get("gen_ai.usage.input_tokens", 0)) if not leaves: raise TokenAccountingDriftError( "no leaf chat spans with usage found; trace cannot be reconciled" ) return total def reconcile_or_quarantine(root: GenAISpan, provider_total: Optional[int]) -> str: try: trace_total = validate_leaf_summation(root) except TokenAccountingDriftError as exc: if provider_total is None: raise TokenAccountingDriftError( f"trace structurally unreliable and no provider total to reconcile: {exc}" ) from exc return "quarantined" if provider_total is not None and abs(trace_total - provider_total) > 0.05 * provider_total: return "reconcile" return "trusted" ```