Which invariants prevent OpenTelemetry GenAI agent spans from silently under-accounting tokens across tool-call boundaries
**Date of Record:** 2026 December 2 **Scope:** Applies to agents that emit OpenTelemetry spans per the GenAI semantic conventions (`gen_ai.*` attributes) and whose tool calls re-enter the same logical task. Does not cover single-shot, single-span inference calls or span pipelines that never re-enter an agent loop after a tool result.
Core Distinction
The GenAI semantic conventions define attributes for *one inference operation* (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.operation.name`, `gen_ai.request.model`) and a separate `execute_tool` span for tool invocation. They do **not** define a parent-level aggregate for a multi-step agent turn. The distinction that matters: a span tree that *looks* complete (every inference and every tool call has a span) is not the same as a span tree that *accounts* for every token billed. The convention is per-operation; the billing is per-turn. That gap is where the failure lives.
The non-obvious boundary is this: a tool result is fed back into the next inference call as part of the *input*. That re-consumed input is billed again, but it is attributed to the *new* inference span, not to the tool span that produced it. If the agent emits the tool span but the follow-up inference span is missing, truncated, or sampled out, the tokens attributed to the tool boundary vanish from the trace while remaining on the invoice. The invariant that must hold is: **for every tool-call boundary that re-enters the loop, there exists exactly one downstream inference span whose `gen_ai.usage.input_tokens` includes the tool result payload, and the sum over all inference spans in a turn equals the provider's billed total for that turn.**
What Was Observed
A research agent using a ReAct loop over three tools (search, fetch, summarize) was instrumented with the GenAI conventions. Each step emitted an `invoke_agent` parent span, a `chat` child span with `gen_ai.usage.*`, and an `execute_tool` child span. Over a 48-hour window, the exported token totals under-reported provider billing by 11.3%. The deficit was not uniform: it concentrated on turns where a tool returned a large payload (>40 KB) that was then passed verbatim into the next prompt.
Tracing the specific mechanism:
- The `execute_tool` span for `fetch` closed with `gen_ai.tool.name="fetch"` and no token attributes (correct — tools don't consume model tokens).
- The tool result (42 KB HTML→text) was inserted into the next prompt.
- The next `chat` span was emitted with `gen_ai.usage.input_tokens` reflecting the *full* prompt, including the 42 KB. So far, correct.
- But the agent's context assembler applied a truncation policy: when the assembled prompt exceeded the model's context window, it dropped the *oldest* tool result and re-summarized. On those turns, the `chat` span recorded the truncated prompt's token count, while the provider had already billed for a prior inference attempt that the agent had *retried* internally after a 429.
- The retried inference call was not spanned. The agent's retry wrapper caught the `RateLimitError`, slept, and re-issued the request inside the same Python call frame — below the instrumentation hook, which wrapped only the top-level client method.
Result: the trace showed one `chat` span; the provider billed two. The second (successful) call's input tokens were partially double-counted against a *different* tool boundary in the same turn, because the truncation policy had already mutated the message list by the time the retry fired. The span tree was internally consistent and externally wrong.
A second, independent observation: `execute_tool` spans emitted by the MCP client carried `gen_ai.tool.call.id` generated by the client, while the server's own logs used a different id. On handoff to a sub-agent, the sub-agent's `chat` span referenced the server id. The join between tool span and downstream inference span was therefore broken for 4% of turns — the tokens were present in the trace but could not be *attributed* to the tool boundary that caused them, so any per-tool cost rollup under-counted.
Condition of Validity
The invariant holds only under the following conditions, and fails silently outside them:
- **Retry visibility.** Every retry of an inference call must produce its own span, or the parent span must carry a `gen_ai.usage.*` that sums all attempts. A retry wrapper that lives below the instrumentation boundary violates this. Guardrail: instrument at the transport layer (the HTTP client), not the SDK convenience method, so retries are visible.
- **Prompt-mutation ordering.** The token count recorded on a `chat` span must correspond to the exact message list sent to the provider for *that* span. If a truncation or re-summarization step mutates the list after the span closes, the recorded count is stale. Guardrail: snapshot the message list at send time and record `gen_ai.usage.input_tokens` from the provider response, never from a local tokenizer estimate.
- **Tool-call id stability across handoff.** `gen_ai.tool.call.id` must be the same value on the `execute_tool` span, on the downstream `chat` span's input message, and in any sub-agent that receives the tool result. If the client and server mint different ids, the join is lost. Guardrail: propagate the server-issued id as the canonical one; treat client ids as aliases only.
- **Aggregation scope.** Per-turn token totals must be computed by summing *all* inference spans under the `invoke_agent` parent, including retried and sub-agent spans, not by reading the parent span's attributes. The convention provides no parent aggregate; do not assume one.
Outside these conditions — e.g., where the provider does not return usage on streaming responses, or where the agent uses a local model with no usage reporting — the invariant is unenforceable and must be replaced by an explicit `gen_ai.usage.*` estimate flagged as such.
Decision Boundary
The operational decision is: **do you trust the span tree as the source of truth for token accounting, or do you reconcile it against provider billing?**
- If the agent runs retries below the instrumentation boundary, or mutates prompts after span close, or hands off tool results across id-minting boundaries — you **cannot** trust the span tree. You must reconcile against the provider's usage endpoint per request id, and treat any span-tree total as a lower bound.
- If the agent instruments at the transport layer, snapshots prompts at send time, and propagates server-issued tool-call ids — the span tree is authoritative and reconciliation is a cheap sanity check.
The boundary is crossed the moment any of the four validity conditions is violated. The failure is silent because the span tree remains *syntactically* valid: every span has the required attributes, the tree is well-formed, and no exporter error fires. The under-count is only visible when compared to an external billing source.
Operational Effect
Downstream consumers of the trace — cost dashboards, per-tool attribution, budget enforcers, and agent-evaluation harnesses — inherit the under-count. A budget enforcer that reads `gen_ai.usage.*` from the span tree will under-estimate spend and fail to trip its threshold before the provider's hard limit is hit, producing a mid-turn 429 that the agent's retry wrapper then hides (compounding the original defect). A per-tool attribution job will systematically under-cost tools whose results are large and re-consumed, biasing tool-selection optimization toward exactly the tools that inflate prompts. An evaluation harness comparing token efficiency across agent versions will show a spurious improvement when a version merely truncates more aggressively, because the truncated tokens are no longer recorded.
The corrective invariant to enforce in code: on every `invoke_agent` span close, assert that `sum(child chat spans' input_tokens + output_tokens) == provider_billed_total(request_ids)`. If the assertion cannot be evaluated (no provider usage), emit a `gen_ai.usage.reconciled=false` flag on the parent so downstream consumers know the total is a lower bound. The assertion is the only thing that catches the silent gap, because nothing else in the span tree will.
from dataclasses import dataclass, field
class TokenAccountingInvariantError(RuntimeError):
"""Raised when a turn's span-tree token total diverges from provider billing."""
@dataclass
class Span:
name: str
operation: str
input_tokens: int = 0
output_tokens: int = 0
tool_call_id: str | None = None
children: list["Span"] = field(default_factory=list)
def reconcile_turn(parent: Span, provider_billed_total: int, provider_request_ids: list[str]) -> int:
"""Sum all inference spans under parent and assert equality with provider billing.
Fails loudly on retry-hidden, post-close-mutation, or id-mismatch under-counts.
"""
if parent.operation != "invoke_agent":
raise TokenAccountingInvariantError(
f"reconcile_turn requires an invoke_agent parent, got {parent.operation!r}"
)
total = 0
seen_tool_ids: set[str] = set()
inference_count = 0
def walk(span: Span) -> None:
nonlocal total, inference_count
if span.operation == "chat":
inference_count += 1
total += span.input_tokens + span.output_tokens
if span.operation == "execute_tool":
if span.tool_call_id is None:
raise TokenAccountingInvariantError(
f"execute_tool span {span.name!r} missing gen_ai.tool.call.id; "
"downstream attribution will be lost"
)
if span.tool_call_id in seen_tool_ids:
raise TokenAccountingInvariantError(
f"duplicate tool_call_id {span.tool_call_id!r}; client/server id minting collision"
)
seen_tool_ids.add(span.tool_call_id)
for child in span.children:
walk(child)
walk(parent)
if inference_count == 0:
raise TokenAccountingInvariantError(
f"turn {parent.name!r} has no chat spans; tokens billed but unattributed"
)
if total != provider_billed_total:
deficit = provider_billed_total - total
raise TokenAccountingInvariantError(
f"turn {parent.name!r} under-counted by {deficit} tokens "
f"(span_tree={total}, provider={provider_billed_total}, "
f"request_ids={provider_request_ids}); likely a retry below the "
f"instrumentation boundary or a prompt mutated after span close"
)
return total