# Which invariants prevent token-attribution drift across nested tool-call spans in OpenTelemetry GenAI semconv **Date of Record:** 2026 November 29 **Scope:** Applies to agents whose execution is instrumented with OpenTelemetry GenAI semantic conventions where a single logical turn fans out into nested `execute_tool` spans and child model invocations. Does not apply to single-shot prompt/response telemetry or to non-instrumented agents where token counts are only aggregated at the process level. ## Core Distinction The GenAI semconv distinguishes a *model invocation span* (attributes `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.operation.name`, `gen_ai.request.model`) from a *tool execution span* (`gen_ai.operation.name = "execute_tool"`, `gen_ai.tool.name`, `gen_ai.tool.call.id`), which by convention carries **no** usage attributes of its own. The failure mode is not "missing token counts." It is **double-counting and mis-parenting**: an orchestrator that re-emits the parent span's usage on every child tool span, or a sub-agent that emits its own `gen_ai.usage.*` under a tool span, produces a trace whose *summed* input tokens exceed the billed total by a factor equal to the fan-out width. Because semconv does not mandate a canonical aggregation rule, the backend's rollup silently disagrees with the provider invoice — and the discrepancy is invisible until a cost-per-task dashboard is reconciled against a billing line item. ## What Was Observed A retrieval agent executed a single user turn that produced one root `invoke_agent` span, five `execute_tool` child spans (parallel vector-store lookups), and six nested `chat` spans (one per tool result plus a final synthesis). The provider billed 11,240 input tokens for the turn. The collector's rollup reported 47,900 input tokens across the trace. The delta was exactly the sum of the root span's `gen_ai.usage.input_tokens` replicated onto each of the five tool spans by an auto-instrumentation shim that copied parent attributes down the span tree — a common "context propagation" convenience that is correct for `gen_ai.conversation.id` and catastrophic for usage counters. A second, subtler artifact appeared in the same trace: three of the six `chat` spans carried `gen_ai.usage.output_tokens` but **no** `gen_ai.usage.input_tokens`, because the sub-agent's SDK only populated input tokens when the prompt exceeded a cache threshold. The rollup treated missing attributes as zero, understating the true input total by 3,180 tokens on those spans alone. Net effect on the trace: over-count on tool spans, under-count on model spans, with no single span where the error was visible in isolation. The trace was internally consistent — every span had a valid parent, no orphans, no gaps. The invariant that broke was not structural integrity but **attribution conservation**: the sum of leaf-level usage must equal the billed total, and no usage value may appear on more than one span in an ancestor-descendant path. ## Condition of Validity Token attribution across a tool-call chain is only sound when three conditions hold simultaneously: 1. **Usage is leaf-local.** `gen_ai.usage.*` may appear only on spans where a model invocation actually occurred (`gen_ai.operation.name` in `{chat, text_completion, generate_content}`). Tool spans, agent spans, and wrapper spans must never carry usage attributes, even when they "represent" the cost of their children. 2. **Absence is distinguishable from zero.** A model span with no `gen_ai.usage.input_tokens` attribute is *unknown*, not *zero*. Rollups must propagate an `unknown` sentinel that poisons the aggregate rather than silently contributing 0 — otherwise partial instrumentation looks like cheap turns. 3. **Aggregation is defined over the leaf set, not the span set.** The correct total for a trace is `sum(usage over spans where usage is defined)`, computed once, at the leaf boundary. Any backend that aggregates by summing all spans with a `gen_ai.*` prefix, or that inherits attributes down the tree, violates this by construction. When any one condition fails, the trace remains structurally valid — parent/child links, span kinds, and service names all check out — while the cost signal drifts. This is why the failure survives schema validation and only surfaces at reconciliation. ## Decision Boundary The boundary is between **span modeling as a structural record** and **span modeling as a billing ledger**. OpenTelemetry's data model treats attributes as descriptive, not additive; it has no notion of "this attribute is a counter that must not be duplicated." The GenAI semconv inherits this. Therefore: - If the trace is consumed only for latency analysis and error rates, attribute duplication on tool spans is harmless. - If the trace is consumed for cost attribution, token budgeting, or per-tool ROI, the duplication is a correctness bug, and the invariant must be enforced at instrumentation time — not repaired at query time, because once the collector has written the duplicated attribute there is no reliable way to distinguish "this tool span legitimately consumed 2,000 tokens" (it can't, per semconv) from "this tool span inherited 2,000 tokens from its parent." The decision: **treat any `gen_ai.usage.*` attribute on a span whose `gen_ai.operation.name` is not a model operation as a hard instrumentation error**, reject the span at the collector, and fail the trace's attribution rather than emit a plausible-but-wrong number. A missing cost number is recoverable; a wrong one is not. ## Operational Effect Enforcing the invariant changes three operational behaviors. First, the auto-instrumentation shim must maintain an explicit allowlist of attributes eligible for parent-to-child propagation (`gen_ai.conversation.id`, `gen_ai.system`, trace-level baggage) and must exclude the entire `gen_ai.usage` namespace from inheritance — this is the single highest-leverage guardrail, because shims are where the duplication originates. Second, the rollup must emit a per-trace `attribution_complete` boolean and a `attribution_unknown_spans` count alongside the token total, so that dashboards can render "11,240 tokens (3 spans unknown)" rather than a confident wrong number. Third, reconciliation jobs must compare leaf-summed totals against provider invoices per `gen_ai.conversation.id`, and a divergence above a tolerance threshold must open an incident against the instrumentation, not the billing system — the default assumption that the invoice is wrong inverts the debugging direction and wastes hours. The deeper effect is that token cost becomes a *verified* quantity rather than a *reported* one. Once the invariant is enforced, the trace can be trusted as a ledger, and per-tool token attribution becomes meaningful: you can see that the vector-store tool's results drove 40% of the synthesis span's input tokens, because the synthesis span is the only place those tokens appear. ```python from dataclasses import dataclass, field from typing import Optional MODEL_OPERATIONS = {"chat", "text_completion", "generate_content"} class TokenAttributionError(RuntimeError): """Raised when a span violates the leaf-local usage invariant.""" @dataclass class Span: span_id: str parent_id: Optional[str] operation_name: str attributes: dict = field(default_factory=dict) def validate_span(span: Span) -> None: usage_keys = [k for k in span.attributes if k.startswith("gen_ai.usage.")] if not usage_keys: return if span.operation_name not in MODEL_OPERATIONS: raise TokenAttributionError( f"span {span.span_id} (op={span.operation_name}) carries usage " f"attributes {usage_keys}; usage is leaf-local and may only appear " f"on model-operation spans" ) def aggregate_leaf_usage(spans: list[Span]) -> dict: total_input = 0 total_output = 0 unknown_spans = 0 for span in spans: validate_span(span) if span.operation_name not in MODEL_OPERATIONS: continue inp = span.attributes.get("gen_ai.usage.input_tokens") out = span.attributes.get("gen_ai.usage.output_tokens") if inp is None or out is None: unknown_spans += 1 continue total_input += inp total_output += out return { "input_tokens": total_input, "output_tokens": total_output, "attribution_complete": unknown_spans == 0, "attribution_unknown_spans": unknown_spans, } def reconcile(invoice_input: int, rollup: dict, tolerance: float = 0.02) -> None: if not rollup["attribution_complete"]: raise TokenAttributionError( f"cannot reconcile: {rollup['attribution_unknown_spans']} model spans " f"missing usage attributes; aggregate is a lower bound" ) delta = abs(rollup["input_tokens"] - invoice_input) / max(invoice_input, 1) if delta > tolerance: raise TokenAttributionError( f"attribution drift {delta:.1%} exceeds tolerance {tolerance:.1%}: " f"rollup={rollup['input_tokens']} invoice={invoice_input}" ) ```