# In what scenarios must an instance treat OpenTelemetry GenAI token accounting as non-additive across a tool-call chain, and how does span-parenting corrupt the rollup **Date of Record:** 2026 November 25 **Scope:** Applies to agents that emit OTel GenAI spans (`gen_ai.*` attributes) per LLM invocation and per tool call, and that aggregate `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens` by walking the span tree. Does not apply to single-shot LLM calls with no tool loop, nor to billing systems that consume provider-side invoices rather than telemetry. ## Core Distinction The GenAI semantic conventions describe *per-span* usage attributes: each `gen_ai.chat` (or `gen_ai.invoke_agent`) span carries the token counts the model returned for *that* completion. They do not specify an aggregation rule across a parent/child span tree. Operators assume the obvious one — sum the leaf `gen_ai.chat` spans and you get the chain total — and that assumption is wrong in two distinct ways that compound. The first is **context re-billing**: in an agentic tool loop, every subsequent LLM call re-sends the entire accumulated history (prior assistant turns, tool results, prior reasoning). A five-step chain whose steps consume 2k, 4k, 7k, 11k, and 16k input tokens has a *leaf sum* of 40k input tokens, but the *logical conversation* is only 16k tokens deep. The leaf sum is correct for provider billing and wrong for any capacity, cost-per-task, or context-window metric. These are two different quantities and the conventions give them the same attribute name. The second is **span-parenting double-count**: a `gen_ai.invoke_agent` span may itself carry usage attributes (some SDKs populate the agent span from the final completion), and it also has `gen_ai.chat` children. A naive `sum(span.gen_ai.usage.input_tokens for span in tree)` walks both and double-counts the agent span's copy. Worse, tool-execution spans (`gen_ai.execute_tool`) sometimes inherit a parent's usage attribute through span processors that copy resource/scope attributes downward. The invariant: **token accounting is additive only over a set of spans that are (a) mutually non-ancestral and (b) each representing exactly one provider completion.** Any rollup that violates either clause is not a token count; it is an arbitrary number. ## What Was Observed A code-review agent performing a 6-call tool chain (read file → grep → read file → run tests → read diff → summarize). Instrumentation emitted one `gen_ai.invoke_agent` root span and six `gen_ai.chat` children, plus four `gen_ai.execute_tool` spans nested under the chat spans that triggered them. Observed telemetry, condensed: | span | parent | input_tokens | output_tokens | |---|---|---|---| | invoke_agent (root) | — | 16,240 | 1,102 | | chat[0] | root | 2,010 | 180 | | chat[1] | root | 4,120 | 96 | | chat[2] | root | 7,330 | 210 | | chat[3] | root | 11,004 | 512 | | chat[4] | root | 13,900 | 88 | | chat[5] | root | 16,240 | 1,102 | Three separate defects surfaced in the rollup dashboard: 1. The dashboard summed *all* spans with a `gen_ai.usage.input_tokens` attribute: 16,240 + (2,010+…+16,240) = **86,844** input tokens for a task whose true provider-side total was 54,604 and whose final context depth was 16,240. The root span's usage was a copy of `chat[5]`, double-counted. 2. A per-tool-call cost breakdown attributed the *entire* accumulating context to each tool span, because a span processor had propagated the triggering chat span's usage down to `execute_tool` children. The `grep` tool appeared to "cost" 4,120 input tokens. 3. A context-window saturation alert fired at step 4 (13,900 tokens) against a 16k budget, but the alert was computed by summing leaf input tokens cumulatively — it predicted exhaustion at step 2 and never fired at the real boundary. The agent's own self-reporting was consistent with defect 1: it believed it had consumed ~87k tokens and began aggressively truncating history, which *changed its behavior* — it dropped the diff from context and produced a wrong summary. Telemetry corruption became a reasoning fault. ## Condition of Validity Leaf-sum token accounting is valid if and only if all of the following hold: - **Non-ancestral set.** The summed spans form an antichain in the span tree. No span in the set is an ancestor of another. Enforce by filtering to spans where `span.kind == "CLIENT"` and `gen_ai.operation.name == "chat"`, and asserting no two share an ancestor-descendant relation. - **One completion per span.** Each summed span carries a `gen_ai.response.id` (or provider-equivalent) that is unique within the set. Duplicate response IDs indicate a span processor copied attributes or the SDK re-emitted. - **Usage is terminal, not inherited.** `gen_ai.usage.*` must originate from the provider response object, not from a span processor's attribute propagation. Detect by checking that every span with usage also has a `gen_ai.response.model` and a matching `gen_ai.response.id`; a span with usage but no response ID is inherited and must be excluded. - **Chain depth is tracked separately.** The *context depth* (input tokens of the final call) and the *cumulative billed* tokens (leaf sum) are stored as two distinct derived attributes, e.g. `derived.chain.context_depth` and `derived.chain.billed_input_total`. They are never conflated under one name. When any condition fails, the rollup is undefined and must be rejected rather than reported. ## Decision Boundary The boundary is whether the consumer needs **billing truth** or **state truth**. - Billing, quota enforcement, rate-limit projection → use the leaf sum over the antichain of `chat` spans, *excluding* any span lacking a unique `gen_ai.response.id`. This is the number the provider will invoice. - Context-window management, saturation alerting, history-truncation policy, cost-per-logical-task → use the *maximum* input-token value across the chain (the final call's input), never the sum. Summing here is a category error: it models re-billed context as new information. - Agent self-reflection / budget self-governance → the agent must be given `chain.context_depth` and `chain.billed_input_total` as separate fields, because an agent that reads a single "tokens used" number will mis-plan its remaining budget by a factor equal to chain depth. A concrete rule: **if `billed_input_total / context_depth > 1.5`, the chain is in the re-billing regime and any single-number token budget handed to the agent is invalid.** At a 6-step chain the ratio was 3.4; the agent's truncation policy was calibrated to a budget that did not exist. ## Operational Effect The failure is not a metrics bug; it propagates into agent behavior. An agent that receives a corrupted token count as part of its own context (via a `get_budget_status` tool, a system-prompt injection of "you have used N tokens", or a supervisor's steering message) will make truncation, summarization, and early-termination decisions on a fabricated number. The corruption is silent because the number is plausible — it is larger than reality, which biases toward premature truncation and lost context, exactly the failure mode the telemetry was supposed to prevent. The guardrail is a **rollup validator** that runs at the collector or exporter boundary, before any aggregation is exposed to the agent or dashboard, and that refuses to emit a single token total when the antichain or response-ID invariants fail. It emits the two derived quantities separately and tags the span with `derived.accounting.regime = "re-billing"` when the ratio exceeds threshold, so downstream consumers cannot accidentally treat the sum as context depth. When the validator cannot establish the invariants — for example, a provider SDK that omits response IDs — it must fail closed and surface the chain as unaccounted rather than guess. ```python from __future__ import annotations from dataclasses import dataclass, field class TokenRollupInvariantError(RuntimeError): """Raised when a GenAI span tree cannot be safely aggregated for token accounting.""" @dataclass class Span: span_id: str parent_id: str | None operation: str # "chat" | "execute_tool" | "invoke_agent" input_tokens: int = 0 output_tokens: int = 0 response_id: str | None = None response_model: str | None = None @dataclass class ChainRollup: billed_input_total: int billed_output_total: int context_depth: int regime: str chat_span_ids: list[str] = field(default_factory=list) def _is_ancestor(anc: Span, node: Span, by_id: dict[str, Span]) -> bool: cur = node while cur.parent_id is not None: if cur.parent_id == anc.span_id: return True cur = by_id[cur.parent_id] return False def rollup_chain(spans: list[Span]) -> ChainRollup: by_id = {s.span_id: s for s in spans} # Clause 1: usage must be terminal, not inherited. A span with usage but # no response_id is a propagated copy and must be excluded, not summed. chat_spans = [ s for s in spans if s.operation == "chat" and (s.input_tokens or s.output_tokens) ] inherited = [s for s in chat_spans if s.response_id is None] if inherited: raise TokenRollupInvariantError( f"chat spans with usage but no response_id (inherited attributes): " f"{[s.span_id for s in inherited]}" ) # Clause 2: the summed set must be an antichain. for i, a in enumerate(chat_spans): for b in chat_spans[i + 1:]: if _is_ancestor(a, b, by_id) or _is_ancestor(b, a, by_id): raise TokenRollupInvariantError( f"ancestral chat spans in rollup: {a.span_id} vs {b.span_id}" ) # Clause 3: response IDs must be unique within the set. seen: dict[str, str] = {} for s in chat_spans: assert s.response_id is not None if s.response_id in seen: raise TokenRollupInvariantError( f"duplicate gen_ai.response.id {s.response_id!r} on " f"{seen[s.response_id]} and {s.span_id}" ) seen[s.response_id] = s.span_id if not chat_spans: raise TokenRollupInvariantError("no billable chat spans in tree") billed_in = sum(s.input_tokens for s in chat_spans) billed_out = sum(s.output_tokens for s in chat_spans) context_depth = max(s.input_tokens for s in chat_spans) ratio = billed_in / context_depth if context_depth else 0.0 regime = "re-billing" if ratio > 1.5 else "single-shot" return ChainRollup( billed_input_total=billed_in, billed_output_total=billed_out, context_depth=context_depth, regime=regime, chat_span_ids=[s.span_id for s in chat_spans], ) ```