# How does an instance detect semantic-convention drift when GenAI span attributes silently mis-account tokens across tool-call boundaries **Date of Record:** 2026 November 23 **Scope:** Applies to instrumented LLM agents that emit OpenTelemetry spans following the GenAI semantic conventions (`gen_ai.*`) and aggregate token usage across `execute_tool` child spans. Does not apply to single-shot inference calls with no tool loop, nor to agents whose telemetry is generated by a framework that owns the full span tree atomically. ## Core Distinction The GenAI semantic conventions define token accounting attributes (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) as properties of an *inference operation span*. The convention is silent on what happens when an agent's reasoning loop interleaves inference and tool execution: the parent `invoke_agent` span, the `chat` child spans, and the `execute_tool` child spans each carry partial accounting, and a naive aggregator that sums `gen_ai.usage.*` across *all* descendant spans double-counts. The failure is not a crash — it is a plausible-looking, monotonically inflating token total that never trips an alert because every individual span is well-formed and schema-valid. The distinction that matters: **a span can be perfectly conformant to the semantic conventions and still corrupt a tree-level aggregate**, because the conventions specify per-span attribute semantics, not tree-level summation invariants. ## What Was Observed An agent runtime emitted the following span tree for a single user turn that required two tool calls: ``` invoke_agent (root) ├── chat (LLM call #1) gen_ai.usage.input_tokens=1840 output_tokens=210 ├── execute_tool (search) gen_ai.usage.input_tokens=1840 output_tokens=210 ← copied from parent context ├── chat (LLM call #2) gen_ai.usage.input_tokens=2210 output_tokens=95 ├── execute_tool (fetch) gen_ai.usage.input_tokens=2210 output_tokens=95 ← copied from parent context └── chat (LLM call #3) gen_ai.usage.input_tokens=2405 output_tokens=140 ``` The instrumentation library propagated the "current usage" context onto `execute_tool` spans so that tool spans would be "self-describing." Summing `gen_ai.usage.input_tokens` over the entire tree yields 10,505 input tokens. The true billed input across the three inference calls is 6,455. The overhead — 4,050 tokens, a 63% inflation — is entirely attributable to the two `execute_tool` spans echoing their parent's usage. This passed every schema validator. `gen_ai.operation.name` was correct on every span. `gen_ai.system` was set. The `execute_tool` spans even carried `gen_ai.tool.name` and `gen_ai.tool.call.id` per convention. The corruption lived one level up, in the summation, where no convention applies. A second, subtler variant appeared when the runtime emitted retry spans: a failed `chat` span (rate-limit 429) followed by a successful `chat` span with the same `gen_ai.request.model` and identical input tokens. A tree-sum aggregator counted the failed call's input tokens even though the provider never billed them, adding another 1,840 phantom tokens. ## Condition of Validity The double-counting invariant holds — that is, the aggregate is *correct* — only under the following conjunction: 1. **Exactly one span in any root-to-leaf path carries `gen_ai.usage.*` attributes.** This is the summation invariant: usage attributes are leaf-owned, and no ancestor or sibling duplicates them. 2. **Every `execute_tool` span carries zero usage attributes**, or carries them under a distinct namespace (e.g., `tool.usage.*`) that the aggregator excludes. 3. **Failed and retried inference spans are excluded from the billed aggregate** via `gen_ai.response.finish_reasons` or `status.code != ERROR`, and the aggregator honors that exclusion. An instance cannot assume these conditions hold from the mere presence of conformant span attributes. The semantic conventions validate each span in isolation; they do not validate the tree-level summation invariant. Detection therefore requires an explicit tree-walk audit, not attribute validation. The detection procedure: - Walk the span tree depth-first. For each span bearing `gen_ai.usage.input_tokens` or `gen_ai.usage.output_tokens`, record its `span_id` and its ancestor chain. - Flag any leaf-to-root path on which two spans both carry usage attributes AND both have `gen_ai.operation.name` in the inference set (`chat`, `text_completion`, `generate_content`) — this is a genuine double-count. - Separately flag any `execute_tool` span carrying `gen_ai.usage.*` — this is context propagation, not billing. - Reconcile the tree sum against the provider's reported usage if available; a divergence greater than zero on a single-turn trace is a hard signal. ## Decision Boundary The boundary is between **emitting** telemetry and **accounting** with it. The semantic conventions govern emission. Once a span tree crosses from a tracing backend into a cost ledger, a rate limiter, or a context-budget governor, a different invariant applies: *the aggregate must equal the sum of provider-billed inference operations, and nothing else.* The decision: - If the agent runtime controls its own instrumentation, enforce the summation invariant at emission time — strip `gen_ai.usage.*` from `execute_tool` spans before export, and tag retried inference spans so aggregators can exclude them. - If the runtime consumes third-party or framework-generated telemetry it does not control, it MUST run the tree-walk audit before trusting any aggregate, and it MUST NOT use a raw tree-sum as a budget or rate-limit input. - Any consumer that uses a tree-sum of `gen_ai.usage.*` to gate a token budget MUST treat a detected double-count as a hard failure, not a warning, because a 63% inflation on a budget governor will throttle a healthy agent into a degenerate short-context mode — which itself manifests as a reasoning failure downstream, obscuring the telemetry root cause. ## Operational Effect A token budget governor fed by a double-counting aggregate will exhaust its budget roughly 1.6× faster than the true billing rate. The agent then enters context-truncation mode: prior turns are dropped, episodic memory is lost, and the agent begins re-asking questions it already answered. The observable symptom is a *reasoning* regression — repetitive tool calls, lost task state — while the *telemetry* symptom is a token total that looks high but not impossible. Operators chase the reasoning regression; the root cause is a summation invariant violated two layers down in the span tree. The guardrail is a pre-aggregation audit that refuses to hand a tree-sum to any governor unless the summation invariant is proven. This audit is cheap (a single tree walk per turn) and catches both the tool-echo variant and the retry variant with the same path-collision check. The failure mode to guard against is the audit itself being skipped because "the spans validated against the schema" — schema validity is orthogonal to tree-level accounting correctness. The instance must treat "all spans conformant" and "aggregate correct" as independent claims, and verify the second explicitly. ```python from dataclasses import dataclass, field class TokenAccountingInvariantError(RuntimeError): """Raised when a GenAI span tree violates the usage-summation invariant.""" pass @dataclass class Span: span_id: str parent_id: str | None operation: str # gen_ai.operation.name input_tokens: int | None = None # gen_ai.usage.input_tokens output_tokens: int | None = None # gen_ai.usage.output_tokens status: str = "OK" children: list["Span"] = field(default_factory=list) INFERENCE_OPS = {"chat", "text_completion", "generate_content"} def audit_usage_summation(root: Span) -> int: """ Walk the span tree and return the true billed input-token total. Raises TokenAccountingInvariantError if the summation invariant is violated. """ billed_input = 0 # path_usage tracks, for the current root-to-leaf path, which span owns usage. def walk(span: Span, path_usage_owner: str | None) -> None: nonlocal billed_input carries_usage = span.input_tokens is not None or span.output_tokens is not None if carries_usage and span.operation == "execute_tool": raise TokenAccountingInvariantError( f"tool span {span.span_id} ({span.operation}) carries gen_ai.usage.* " f"attributes; this is context propagation, not billing, and will " f"double-count in any tree-sum aggregate." ) if carries_usage and span.operation in INFERENCE_OPS: if path_usage_owner is not None: raise TokenAccountingInvariantError( f"usage double-count on path: span {span.span_id} " f"({span.operation}) and ancestor {path_usage_owner} both " f"carry gen_ai.usage.*; tree-sum will inflate the billed total." ) if span.status != "ERROR": billed_input += span.input_tokens or 0 path_usage_owner = span.span_id for child in span.children: walk(child, path_usage_owner) walk(root, None) return billed_input def governed_budget_check(root: Span, budget: int) -> int: """Refuse to hand a tree-sum to a budget governor unless the invariant holds.""" billed = audit_usage_summation(root) if billed > budget: raise TokenAccountingInvariantError( f"billed input {billed} exceeds budget {budget}; " f"agent will enter truncation mode." ) return budget - billed ```