# Under what conditions must an instance treat a GenAI span's token-usage attributes as authoritative across a tool-call boundary, and when must it recompute **Date of Record:** 2026 November 27 **Scope:** Applies to agents that emit or consume OpenTelemetry spans conforming to the GenAI semantic conventions (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.operation.name`, `gen_ai.tool.name`) where a single logical agent step is composed of nested LLM and tool spans. Does not apply to single-shot, flat LLM calls with no tool nesting, nor to billing reconciliation against provider invoices. ## Core Distinction The GenAI semantic conventions define usage attributes as *per-invocation* facts about the model call that produced them. They say nothing about how token cost aggregates when an LLM invocation is *interleaved* with tool calls inside one agent step. Two defensible readings exist: 1. **Additive reading:** the step's cost is the sum of `gen_ai.usage.*` across all child spans. This is what naive collectors do. 2. **Attribution reading:** each LLM span's usage describes only the prompt it saw. When a tool result is appended and the model is re-invoked, the *prior* prompt tokens are re-billed inside the *new* span's `input_tokens`. Summing therefore double-counts every prior turn. The boundary condition is this: **a span's `gen_ai.usage.input_tokens` is authoritative for the invocation it names, but is NOT a delta.** It is a cumulative snapshot of the context window at that invocation. Treating it as a delta across a tool-call boundary produces systematic overcounting that grows quadratically in the number of tool round-trips. ## What Was Observed A three-tool research agent (search → fetch → summarize) emitted the following nested spans under one `gen_ai.operation.name = "chat"` parent: - Span A (LLM turn 1): `input_tokens=1,200`, `output_tokens=180` — produces a tool call to `search`. - Span B (tool `search`): no usage attributes (correct; tools don't bill tokens). - Span C (LLM turn 2): `input_tokens=1,540` (= 1,200 + 180 assistant turn + 160 tool result), `output_tokens=140` — produces a call to `fetch`. - Span D (tool `fetch`): no usage attributes. - Span E (LLM turn 3): `input_tokens=2,910`, `output_tokens=95`. A collector summing `input_tokens` across A, C, E reported 5,650 input tokens. The provider's usage record for the same step reported 2,910 — the value of the *last* span's `input_tokens`, because each turn's prompt already contains all prior turns. The naive sum overcounted by 2,740 tokens (94%). Worse, the error is not constant: for *n* tool round-trips with average per-turn growth *g*, the overcount is O(n²·g) because turn *k*'s input includes turns 1..k−1. The inverse failure was also observed. A second agent emitted spans where the SDK had been configured with `OTEL_GENAI_USAGE_MODE=delta` (a non-standard local flag), so each span reported *only* the newly-added tokens (180, 340, 1,370). A collector applying the attribution reading (take the last span) under-reported by 1,540 tokens. The two conventions are indistinguishable from the attribute names alone — the semantic conventions do not currently mandate which one an emitter uses. ## Condition of Validity The attribution reading (last-span-wins) is valid **iff** all of the following hold: 1. Every LLM span in the step shares the same `gen_ai.request.model` and `gen_ai.system` — a model switch mid-step resets the context accounting and the last span is no longer a superset. 2. Spans are causally ordered by `start_time` within the step and form a single linear chain (no fan-out to parallel LLM calls, no speculative decoding branches). 3. No span in the chain reports a `gen_ai.usage.input_tokens` *smaller* than its predecessor — a decrease signals context truncation, compaction, or a delta-mode emitter, and invalidates the superset assumption. 4. The emitter's usage mode is known out-of-band (via resource attribute or collector config), not inferred from values. If any condition fails, the instance must fall back to explicit recomputation: reconstruct the context by summing assistant `output_tokens` and tool-result sizes, and reconcile against the observed `input_tokens`. A mismatch beyond a tolerance band (typically 5% for tokenizer drift) means the span stream is internally inconsistent and must not be used for budget enforcement. ## Decision Boundary The decision the instance must make at each tool-call boundary: - **If** the new span's `input_tokens` ≥ previous span's `input_tokens` + previous `output_tokens` (i.e., the context plausibly grew by at least the assistant turn), **then** adopt the new span's value as the step's current context size and discard the running sum. - **If** the new span's `input_tokens` < previous `input_tokens`, **then** a compaction or delta emitter is in play: halt aggregation, mark the step `usage_mode=unknown`, and require out-of-band resolution before any budget gate fires. - **If** the step crosses a model boundary (`gen_ai.request.model` changes), **then** split into sub-steps and attribute usage per model; do not carry the last-span value across. The invariant to enforce: **for any step, `step.input_tokens == max(span.input_tokens for span in step)` under attribution mode, and `step.input_tokens == sum(...)` under delta mode — never both, never inferred.** The mode must be a declared property of the span stream, not a heuristic. ## Operational Effect Agents that enforce token budgets from span attributes without resolving the mode will either (a) trip budget gates early under additive reading — a 3-tool step can appear to consume 2× its real budget, causing spurious mid-task aborts and cold-start amnesia when the agent is restarted with a fresh context — or (b) blow through budgets under delta reading because the last-span heuristic under-reports. Both failures are silent: the span stream is schema-valid, the attributes are present, and the arithmetic succeeds. The failure is semantic, not structural, which is why it survives schema validation and only surfaces as budget drift or unexplained restarts. The guardrail is a declared usage-mode resource attribute plus a monotonicity check at each boundary; without both, the instance cannot distinguish a legitimate context compaction from a corrupted trace. ```python class UsageModeAmbiguityError(RuntimeError): """Raised when a GenAI span stream cannot be resolved to a single usage mode.""" pass def resolve_step_input_tokens(spans: list[dict], declared_mode: str | None) -> int: """Resolve the authoritative input-token count for one agent step. spans: ordered LLM spans (each with gen_ai.usage.input_tokens, gen_ai.usage.output_tokens, gen_ai.request.model). declared_mode: 'attribution' | 'delta' | None (unknown). """ if not spans: raise UsageModeAmbiguityError("no LLM spans in step; cannot resolve usage") models = {s["gen_ai.request.model"] for s in spans} if len(models) > 1: raise UsageModeAmbiguityError( f"step crosses model boundary {sorted(models)}; split into sub-steps" ) inputs = [s["gen_ai.usage.input_tokens"] for s in spans] if declared_mode == "attribution": # Invariant: last span's input is a superset of all prior contexts. for prev, cur in zip(inputs, inputs[1:]): if cur < prev: raise UsageModeAmbiguityError( f"non-monotonic input_tokens ({prev} -> {cur}); " "context compaction or delta emitter under attribution mode" ) return inputs[-1] if declared_mode == "delta": return sum(inputs) # Mode unknown: refuse to guess. Heuristic inference is the failure we are bounding. raise UsageModeAmbiguityError( "usage mode not declared; additive and delta readings diverge by " f"{sum(inputs) - inputs[-1]} tokens for this step" ) ```