# What structural signals indicate token-cost attribution drift inside OpenTelemetry GenAI tool-call span trees **Date of Record:** 2026 November 27 **Scope:** Applies to agents emitting OpenTelemetry GenAI spans (`gen_ai.*` semantic conventions) where a parent `execute_tool` / chat span fans out into nested tool-call child spans that each report `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens`. Does not cover single-span inference pricing, batch offline accounting, or providers that only expose aggregate account-level usage. ## Core Distinction A span tree can be *structurally valid* — every child span has exactly one parent, `trace_id`/`span_id` linkage is intact, no orphans — while its token accounting is *semantically double-counted or under-counted*. The distinction that matters operationally is between **structural integrity** (the tree you can render in a waterfall) and **attribution integrity** (the sum of leaf `gen_ai.usage.*` attributes equals the true billed total for the trace). These two properties decouple precisely at the boundary where a tool-call child span re-emits the parent's usage, or where a nested LLM call inside a tool is attributed to the tool span rather than to a distinct chat span. A waterfall that looks clean is not evidence of correct cost attribution. ## What Was Observed A planner agent (`gen_ai.operation.name = "chat"`) issued a tool call. The tool implementation itself invoked a sub-agent that made its own LLM request. The instrumentation, following the convention that "tool spans carry the usage of the call that produced them," stamped `gen_ai.usage.input_tokens` on **both** the parent `execute_tool` span and the inner chat span. The exporter's per-trace cost rollup summed all spans with `gen_ai.usage.*` present, producing a trace cost of exactly 2× the provider invoice for that request window. The waterfall rendered perfectly: parent chat → tool span → inner chat, all correctly nested. No span was missing a parent. The only tell was a reconciliation delta between the exporter's summed token count and the provider's `usage` field, and a suspicious ratio of `1.98–2.03` recurring across traces whose tool implementations happened to be LLM-backed. The inverse failure was observed on the same fleet: a retrieve-then-generate tool that called an embedding endpoint. The embedding call was not instrumented as a chat span (embeddings use a different operation name and, at the time, no usage attribute was emitted), so the tool span carried *zero* usage while the provider billed embedding tokens. The trace under-counted. Both failures coexisted in the same deployment, which is why a simple global multiplier never reconciled. ## Condition of Validity Token attribution is only valid when three invariants hold simultaneously: 1. **Leaf-only emission.** `gen_ai.usage.input_tokens` / `output_tokens` are emitted on the span that *directly* represents the billable model invocation, and on no ancestor. A tool span that wraps a model call must *not* copy usage upward; the nested chat span is the sole carrier. 2. **Operation-name discipline.** Every billable invocation is tagged with a `gen_ai.operation.name` in the recognized set (`chat`, `text_completion`, `embeddings`, `generate_content`), and the rollup filters on that set rather than on "any span with a usage attribute." This bounds the embedding-under-count case. 3. **One-to-one span-to-request mapping.** A single span must correspond to a single provider request. Streaming or retried requests that multiplex multiple provider calls into one span violate this and silently deflate per-request cost. The invariant is violated the moment any of these is relaxed, and the violation is invisible to structural validation because the tree remains well-formed. ## Decision Boundary The operational decision is: **when a child span's usage attribute is present but an ancestor also carries usage, which one is authoritative?** The boundary rule that resolves it deterministically: - If a span has a descendant with `gen_ai.operation.name` in the billable set, the ancestor's usage attribute is **derived/duplicated** and must be excluded from rollup. - If a span has *no* billable descendant and carries usage, it is the authoritative carrier. - If a span carries usage and has a billable descendant *and* the descendant's usage is zero or absent, treat the ancestor as authoritative and emit a `attribution.ambiguous` flag — this is the embedding-tool case where the descendant was never instrumented. The boundary is crossed (and the rollup is wrong) when the exporter applies a flat `sum(all spans with usage)` instead of this conditional. The decision must be made per-span at export time, not deferred to the dashboard, because the dashboard cannot reconstruct which ancestor usage was a copy. ## Operational Effect With leaf-only emission enforced, per-trace cost reconciles to the provider invoice within rounding, and the recurring 2× ratio disappears. The `attribution.ambiguous` flag converts the silent embedding under-count into a visible instrumentation gap that can be backfilled. Critically, the fix is **not** a pricing multiplier — it is a structural rule about *where* usage lives in the tree. Agents that later consume these spans for budget enforcement (e.g., halting a task at a token ceiling) inherit the corrected attribution; without it, a planner that double-counts will trip its budget ceiling at half the real spend, and a planner that under-counts will blow through it silently. The span tree remains the same shape; only the attribution invariant changes, which is why this must be enforced at emission time by the instrumentation layer, not reconstructed after the fact. ```python from dataclasses import dataclass, field from typing import Optional BILLABLE_OPS = {"chat", "text_completion", "embeddings", "generate_content"} class AttributionInvariantError(RuntimeError): """Raised when a span tree cannot yield a single authoritative token owner.""" pass @dataclass class Span: span_id: str parent_id: Optional[str] operation_name: Optional[str] input_tokens: int = 0 output_tokens: int = 0 children: list = field(default_factory=list) def is_billable(span: Span) -> bool: return span.operation_name in BILLABLE_OPS def has_billable_descendant(span: Span) -> bool: stack = list(span.children) while stack: node = stack.pop() if is_billable(node) and (node.input_tokens or node.output_tokens): return True stack.extend(node.children) return False def attribute_trace(root: Span) -> tuple[int, list[str]]: """Return (authoritative_total_tokens, ambiguous_span_ids). Leaf-only rule: a span carrying usage is authoritative ONLY if it has no billable descendant that also carries usage. Otherwise its usage is a duplicate copy and is excluded from the rollup. """ total = 0 ambiguous: list[str] = [] stack = [root] while stack: span = stack.pop() carries = bool(span.input_tokens or span.output_tokens) if carries: if has_billable_descendant(span): # ancestor duplicated a descendant's usage -> exclude pass elif not is_billable(span) and not any( is_billable(c) for c in span.children ): # usage on a non-billable span with no billable child: # the embedding-tool under-count case, cannot resolve ambiguous.append(span.span_id) total += span.input_tokens + span.output_tokens else: total += span.input_tokens + span.output_tokens stack.extend(span.children) if ambiguous: # Surface, do not silently accept: cost rollup is unreliable. raise AttributionInvariantError( f"ambiguous attribution on spans {ambiguous}: " f"usage present but no billable operation tagged; " f"rollup total {total} may under-count provider invoice" ) return total, ambiguous def reconcile(root: Span, provider_invoice_tokens: int, tol: float = 0.02) -> None: total, _ = attribute_trace(root) if provider_invoice_tokens == 0: return drift = abs(total - provider_invoice_tokens) / provider_invoice_tokens if drift > tol: raise AttributionInvariantError( f"attribution drift {drift:.3f} exceeds tolerance {tol}: " f"summed={total} invoice={provider_invoice_tokens}" ) ```