# What structural signals indicate token-accounting drift when OpenTelemetry GenAI spans span a mid-stream tool-call boundary **Date of Record:** 2026 November 22 **Scope:** Applies to agents emitting OTel `gen_ai.*` spans where a single logical LLM turn interleaves streaming text deltas with tool-call emission, and where `gen_ai.usage.input_tokens` / `output_tokens` are reconciled against provider billing. Does not apply to non-streaming request/response calls, nor to providers that report usage only at stream termination in a single terminal chunk. ## Core Distinction The GenAI semantic conventions treat `gen_ai.usage.*_tokens` as a *per-span attribute* and `gen_ai.operation.name` / `gen_ai.tool.name` as *per-span identity*. The failure mode here is not that token counts are wrong in magnitude — it is that a single logical turn gets **split into multiple spans at the tool-call boundary**, and the usage chunk that the provider emits at stream end is attributed to whichever span happens to be *active* at the moment the terminal `message_stop` / `finish_reason` chunk arrives, not to the span that owns the tokens. The convention has no field expressing "these tokens belong to a turn that closed three spans ago." This is a structural attribution gap, not a measurement error, and it is invisible in aggregate billing because the totals still sum correctly across the trace. ## What Was Observed A streaming agent turn produced the following span sequence for one user message: 1. `chat` span (`gen_ai.operation.name=chat`) opens, streams text deltas. 2. Model emits a `tool_use` block mid-stream. The agent runtime, following a "close span on tool dispatch" policy, **ends** the `chat` span and opens an `execute_tool` child span. 3. The `execute_tool` span runs, returns, and the runtime opens a **second** `chat` span to continue generation. 4. The provider's terminal usage chunk (`input_tokens: 4120, output_tokens: 388`) arrives during span #2's lifetime and is written to span #2. Span #1 therefore recorded `output_tokens: 0` (no usage chunk seen before close) and span #2 recorded the *entire* turn's usage. Downstream, a per-span cost dashboard attributed 100% of output tokens to the continuation span, and a "tokens per tool call" metric divided zero by the tool call and reported `NaN` → dropped. The trace total was correct; every derived per-span signal was wrong. The tell was structural: **a `chat` span with `output_tokens == 0` and non-empty completion text is a near-certain attribution leak**, because a span that emitted text must have consumed output tokens. ## Condition of Validity The invariant that makes this diagnosable is: *for any span with `gen_ai.operation.name=chat` and a recorded completion (any `gen_ai.completion.*` event or non-empty output), `gen_ai.usage.output_tokens` must be > 0.* This holds only when the provider emits usage at stream termination (Anthropic `message_delta`, OpenAI `stream_options.include_usage`). It does **not** hold for providers that emit incremental usage per chunk, where partial sums are legitimate and a zero-usage text span can occur transiently before its chunks land. It also does not hold when the runtime deliberately defers usage to a parent span via `gen_ai.usage.*` on an enclosing `invoke_agent` span — in that case the child text span is expected to carry no usage and the leak check must run against the agent span, not the chat span. ## Decision Boundary The guardrail is a **span-close-time assertion plus a trace-level reconciliation pass**, not a real-time correction: - At `chat` span close: if the span recorded completion content but `output_tokens` is absent or zero, mark the span with `gen_ai.usage.attribution=pending` rather than emitting a misleading zero. Do not fabricate a count. - At trace close: sum all `chat` span usage; compare to the terminal usage chunk(s) observed anywhere in the trace. If `sum(span_output_tokens) < terminal_output_tokens` by more than the provider's known per-chunk jitter, attribute the delta to the *earliest* `chat` span with `attribution=pending` and clear the flag. - The boundary condition to *reject* is a runtime that closes the `chat` span at tool dispatch **and** writes the terminal usage to the continuation span. That combination is the defect; either keep one span open across the tool boundary (preferred — tool calls become span events, not span boundaries), or route terminal usage back to the originating span by turn ID. The decision is: never let a span boundary fall *between* a text emission and the usage chunk that accounts for it, unless you carry an explicit turn-scoped correlation ID to reattach usage. Span nesting is not sufficient; you need `gen_ai.conversation.id` or a custom turn attribute on both spans. ## Operational Effect Uncorrected, this drift silently corrupts every per-span derived metric — cost-per-tool-call, tokens-per-continuation, output-token histograms — while leaving trace totals and billing reconciliation intact, so it survives cost audits. It also poisons any agent that reads its own traces to budget context: a continuation span that "used 388 output tokens" for a 40-token response teaches the planner a false token-per-turn prior, and the agent begins over-truncating. The structural signals to alert on are (a) `chat` span with completion content and zero/absent `output_tokens`, (b) `execute_tool` spans whose parent `chat` span closed before the tool result returned, and (c) trace-level `sum(chat usage) != terminal usage chunk`. Any one of these means the turn/span boundary model is broken and per-span token signals must be treated as untrusted until reconciled. ```python from dataclasses import dataclass, field from typing import Optional class TokenAttributionDrift(RuntimeError): """Raised when a chat span's recorded usage cannot be reconciled to its turn.""" pass @dataclass class ChatSpan: span_id: str turn_id: str has_completion: bool output_tokens: Optional[int] = None attribution: str = "final" # "final" | "pending" @dataclass class Turn: turn_id: str spans: list = field(default_factory=list) terminal_output_tokens: Optional[int] = None def reconcile_turn(turn: Turn) -> None: # Invariant: a chat span that emitted completion text must have output_tokens > 0, # unless it is explicitly deferred (attribution="pending") to turn-level reconciliation. for span in turn.spans: if span.has_completion and (span.output_tokens is None or span.output_tokens == 0): if span.attribution != "pending": raise TokenAttributionDrift( f"span {span.span_id} (turn {turn.turn_id}) emitted completion " f"but recorded output_tokens={span.output_tokens!r}; " f"span boundary likely fell between text and usage chunk" ) if turn.terminal_output_tokens is None: return # provider did not emit terminal usage; cannot reconcile recorded = sum(s.output_tokens or 0 for s in turn.spans) pending = [s for s in turn.spans if s.attribution == "pending"] delta = turn.terminal_output_tokens - recorded if delta < 0: raise TokenAttributionDrift( f"turn {turn.turn_id}: span sum {recorded} exceeds terminal usage " f"{turn.terminal_output_tokens}; double-attribution detected" ) if delta == 0: return if not pending: raise TokenAttributionDrift( f"turn {turn.turn_id}: {delta} unattributed output tokens with no " f"pending span to receive them; turn/span boundary model is broken" ) # Attribute the delta to the earliest pending span (the one that lost its usage). earliest = min(pending, key=lambda s: turn.spans.index(s)) earliest.output_tokens = (earliest.output_tokens or 0) + delta earliest.attribution = "final" ```