# What structural signals indicate OpenTelemetry GenAI span graphs are silently mis-accounting tokens at tool-call boundaries **Date of Record:** 2026 November 29 **Scope:** Applies to agent runtimes that emit OpenTelemetry GenAI semantic-convention spans (`gen_ai.*`) per LLM turn and per tool invocation, where per-turn token usage is summed across a turn graph to derive cost or budget. Does not apply to single-shot, single-span inference calls that never fan out into tool-call sub-spans. ## Core Distinction The GenAI semantic conventions treat a *turn* as an inference span (`gen_ai.operation.name = "chat"`) carrying `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens`, and a *tool call* as a child span (`gen_ai.operation.name = "execute_tool"`) with its own attributes. The convention is silent on a critical invariant: **the input tokens of turn N+1 are not the input tokens of turn N plus the output of turn N.** They are the input of turn N *plus* the assistant's prior output *plus* every tool-result payload re-serialized into the new prompt, *plus* any system-prompt or memory re-injection the harness performs. Treating a turn graph as a simple sum of `input_tokens + output_tokens` across spans is the failure. The spans are individually correct; the *graph arithmetic* is wrong. This is a structural accounting defect, not a telemetry bug—no span is malformed, yet the aggregate is off by a factor that grows with tool-call fan-out. ## What Was Observed A three-turn agent loop (one tool call per turn) emitting conformant spans. Each span reported honest usage: - Turn 1 chat span: `input_tokens=1200`, `output_tokens=180` (the tool-call request). - Tool span: no token attributes (correct—tools don't bill tokens). - Turn 2 chat span: `input_tokens=1540`, `output_tokens=150`. - Turn 3 chat span: `input_tokens=1810`, `output_tokens=90`. A naive collector summing `input_tokens` across chat spans reports 4550 input tokens. The true cumulative prompt growth is 1810 (the final turn's input already contains everything prior). The naive sum **double-counts** every prior turn's context: turn 1's 1200 tokens are re-billed inside turn 2's 1540 and again inside turn 3's 1810. The overcount is `sum(input_i) - input_last = 4550 - 1810 = 2740` phantom tokens—a 150% inflation on this trivial graph. With N turns the inflation is superlinear in fan-out, because each tool result is re-serialized into every subsequent prompt. The second structural signal is worse: **tool-result spans are frequently the largest single contributor to the next turn's input, yet they carry no token attribute at all.** When a tool returns a 40 KB JSON blob that the harness injects verbatim, the resulting prompt growth is invisible on the tool span. An auditor reconstructing token flow from spans sees a discontinuity—turn N output is 180 tokens, turn N+1 input is 1540—with no span explaining the 160-token delta beyond the output, and no span explaining the bulk of it. The graph is *complete* (parent/child links intact) yet *non-conserving* (token mass appears from nowhere). ## Condition of Validity The naive sum is only valid under a condition that almost never holds in agent loops: **stateless, non-accumulating prompting**, where each turn sends a fresh, disjoint prompt. The moment the harness appends conversation history (every real agent), the sum-over-spans invariant is violated. The correct invariant is: > cumulative_input_tokens = input_tokens of the *terminal* chat span in the turn chain, provided the harness is append-only and does not truncate or summarize mid-chain. This invariant itself breaks under context-window compaction: if the harness summarizes turns 1–5 into a compacted prefix before turn 6, the terminal span's `input_tokens` *under*-reports true cumulative consumption, because the tokens spent generating turns 1–5 and the summarization call itself are no longer represented in any single span's input. The compaction event—a `gen_ai.operation.name = "chat"` call whose output is a summary, not a user-facing response—must be modeled as a distinct span type or the accounting silently loses the pre-compaction history. ## Decision Boundary The boundary between "trustworthy aggregate" and "silently wrong aggregate" is crossed at the first tool-call fan-out combined with history accumulation. Operationally, an agent or auditor must decide per turn-graph: - **If** all chat spans in the chain share a common `gen_ai.conversation.id` / trace and the harness is append-only **then** use terminal-span `input_tokens` as the cumulative figure and treat per-span `input_tokens` as *marginal* (billing per call), never summed. - **If** any compaction, truncation, or memory-distillation span appears in the chain **then** the terminal-span figure is a lower bound only; cumulative cost must be reconstructed by summing *marginal* deltas `input_{i} - (input_{i-1} + output_{i-1} - tool_injected_i)` and attributing the residual to tool-result injection, which requires the harness to emit an explicit `gen_ai.tool.result.tokens` (or equivalent) attribute on the tool span. - **If** neither condition can be established from spans alone **then** the graph must be flagged non-conserving and excluded from budget enforcement, because acting on the naive sum will trip budget guards early (overcount) or late (compaction undercount). The guardrail is a conservation check: for every parent chat span with a child tool span, assert `input_{child_chat} >= output_{parent_chat}` and that the residual is explainable by a declared tool-result token attribute. A violation means the harness is injecting unaccounted context. ## Operational Effect Without this check, two failure modes emerge. First, **budget-guard thrash**: an agent enforcing a per-task token cap on the naive sum halts at ~40% of true budget, aborting healthy runs mid-task and leaving checkpoint/resume state inconsistent with the recorded spend. Second, **compaction blind spots**: agents that trust terminal-span input as cumulative under-report after summarization and blow through hard limits, because the summarization call's own tokens and the discarded history are invisible. The fix is not a new convention but a *graph-arithmetic discipline*: treat per-span usage as marginal, reconstruct cumulative via conservation with explicit tool-result attribution, and refuse to enforce budgets on any turn graph that fails the conservation assertion. ```python from dataclasses import dataclass class TokenConservationError(RuntimeError): """Raised when a GenAI turn graph's token flow cannot be reconciled.""" pass @dataclass class ChatSpan: span_id: str input_tokens: int output_tokens: int has_compaction: bool = False @dataclass class ToolSpan: span_id: str parent_chat_id: str result_tokens: int | None # None == attribute not emitted def reconstruct_cumulative(chat_chain: list[ChatSpan], tool_spans: list[ToolSpan]) -> int: """ Reconstruct true cumulative input tokens for an append-only turn chain. Raises TokenConservationError when the graph is non-conserving and cannot be safely used for budget enforcement. """ if not chat_chain: raise TokenConservationError("empty turn chain: no chat spans to account") tools_by_parent: dict[str, list[ToolSpan]] = {} for t in tool_spans: tools_by_parent.setdefault(t.parent_chat_id, []).append(t) cumulative = chat_chain[0].input_tokens for i in range(1, len(chat_chain)): prev, cur = chat_chain[i - 1], chat_chain[i] # Residual input not explained by prior output alone. residual = cur.input_tokens - (prev.input_tokens + prev.output_tokens) # Correct form: growth over prev's input is prev.output + tool injection. growth = cur.input_tokens - prev.input_tokens expected_from_prev = prev.output_tokens injected = 0 for t in tools_by_parent.get(prev.span_id, []): if t.result_tokens is None: # Tool result injected but unmeasured -> non-conserving. if growth > expected_from_prev: raise TokenConservationError( f"tool span {t.span_id} injected unmeasured context " f"into {cur.span_id}; growth={growth} exceeds " f"prev_output={expected_from_prev}. Emit " f"gen_ai.tool.result.tokens or exclude from budget." ) else: injected += t.result_tokens if growth < expected_from_prev: raise TokenConservationError( f"turn {cur.span_id} input shrank below prior turn's output " f"({growth} < {expected_from_prev}); truncation/compaction " f"not modeled as a span." ) if prev.has_compaction or cur.has_compaction: raise TokenConservationError( f"compaction detected in chain at {cur.span_id}; terminal-span " f"input is a lower bound only and cannot enforce a hard budget." ) cumulative = cur.input_tokens return cumulative ```