# How does an instance detect that its GenAI spans have silently lost token-accounting lineage across a tool-call boundary **Date of Record:** 2026 November 20 **Scope:** Applies to agent runtimes emitting OpenTelemetry spans under the GenAI semantic conventions (`gen_ai.*` attributes) where a parent inference span spawns child tool-execution spans, and where token/cost telemetry is aggregated by attribute propagation rather than by explicit linkage. Does not apply to single-shot, single-span inference calls with no child spans, nor to runtimes that emit a dedicated `gen_ai.usage.*` event stream decoupled from span hierarchy. ## Core Distinction The GenAI semantic conventions define token accounting attributes — `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, and increasingly `gen_ai.usage.cost` — as **per-span** attributes describing the model invocation that span represents. They do *not* define a lineage attribute that tells an aggregator "these tokens were consumed on behalf of, and must be billed to, an ancestor span." This omission is invisible in the happy path, where a single inference span carries its own usage and a collector sums leaf spans. It becomes a boundary failure the moment an agent's inference span emits a **tool-call** (`gen_ai.tool.name`, `gen_ai.tool.call.id`) that spawns a child span which itself performs a *second* model invocation — a sub-agent, a re-ranker, a summarizer, a reflection pass. The child span correctly carries its own `gen_ai.usage.*`. But nothing in the span declares whether those tokens belong to the child's own budget or are debited from the parent's turn. The aggregator, summing leaf usage, double-counts or mis-attributes, and the instance has no signal that its accounting lineage is broken. ## What Was Observed A tool-calling agent executed a `search_and_summarize` tool. The parent inference span `invoke_agent` (span kind `CLIENT`, `gen_ai.operation.name="chat"`) recorded `gen_ai.usage.input_tokens=1840`, `output_tokens=210`. The tool span `execute_tool search_and_summarize` (`gen_ai.operation.name="execute_tool"`, `gen_ai.tool.name="search_and_summarize"`, `gen_ai.tool.call.id="call_9f2"`) spawned a child inference span for an internal summarization model. That child span emitted `gen_ai.usage.input_tokens=6100`, `output_tokens=480` — a large context because it stuffed retrieved documents. The collector's cost pipeline summed `gen_ai.usage.*` across all spans with `gen_ai.operation.name` in `{chat, text_completion}`. It produced a per-trace total of 7940 input tokens. The *actual* billed input was 1840 (parent) + 6100 (child) = 7940 — numerically coincidentally correct here. The failure appeared on the *next* turn: the parent span for turn 2 re-included the child's summarized output in its context but attributed the *entire* prior turn's tool output to itself, emitting `input_tokens=5200`. The aggregator now summed 1840 + 6100 + 5200 = 13140, but the provider billed 1840 + 6100 + (1840 + 480 summary re-fed) ≈ 9260. The 3880-token gap was the summarizer's output counted twice: once as the child's `output_tokens`, once embedded in the parent's next-turn `input_tokens` with no attribute marking it as inherited. Crucially, **no span was malformed**. Every span validated against the schema. `gen_ai.tool.call.id` matched between parent and tool span. The lineage break was semantic, not structural: the conventions have no attribute like `gen_ai.usage.inherited_tokens` or `gen_ai.usage.billing_owner_span_id`, so the aggregator cannot distinguish "tokens this span's model consumed" from "tokens this span's model consumed that were already counted in an ancestor." ## Condition of Validity The invariant that makes attribution sound is: **for every token emitted in a `gen_ai.usage.*` attribute on span S, there exists exactly one span in the trace that is the billing owner, and the sum over billing owners equals provider-billed usage.** This holds only when the following three conditions are simultaneously true: 1. **Tool-call children do not perform independent model inference that is re-ingested by the parent.** If a tool span's subtree contains a `chat` span whose output text appears in the parent's subsequent `input_tokens`, the token is counted on two spans. 2. **The parent's `input_tokens` excludes tokens attributable to a child span's `output_tokens` that the parent merely relays.** The conventions provide no mechanism to enforce this — it is a property of how the runtime constructs its prompt, not of the telemetry. 3. **The aggregator keys on span hierarchy, not on flat `gen_ai.operation.name` matching.** A flat filter (as in the observed collector) has no way to know a `chat` span is nested under an `execute_tool` span under another `chat` span. When any condition fails, the per-trace token sum diverges from billed usage. The divergence is *silent* because both the over-count (double-counted relayed output) and under-count (child tokens dropped if the aggregator only sums top-level `chat` spans) produce plausible-looking integers. There is no checksum in the conventions. ## Decision Boundary An instance must treat **the presence of a `chat` span nested beneath an `execute_tool` span** as the trigger to stop trusting flat aggregation and instead walk the span tree with an explicit ownership rule. The decision boundary is: - **Below the boundary (safe):** tool spans contain no `gen_ai.operation.name="chat"` descendants. Flat summation of `gen_ai.usage.*` is correct. No action needed. - **At the boundary (must intervene):** a `chat` span exists at depth ≥ 2 under another `chat` span, with an `execute_tool` span between them. The instance must either (a) emit an explicit `gen_ai.usage.billing_owner_span_id` attribute on the child pointing at the ancestor that will re-ingest its output, or (b) mark the child's output as `gen_ai.usage.relayed=true` so the aggregator excludes it from the parent's next-turn input count. The instance detects it is *at* the boundary — not merely near it — by a concrete check: for each `chat` span P, compute the set of tool-call IDs in P's `gen_ai.tool.call.id` attributes; for each such ID, find the `execute_tool` span T; for each `chat` span C under T, test whether C's output text (available via span event `gen_ai.content.completion` if content capture is on, or via the tool span's return payload) is a substring of P′'s prompt on the *next* turn. A match means the token is double-counted and the lineage is broken. If content capture is off, the instance cannot run this test and must fall back to the structural heuristic (nested `chat` under `execute_tool` under `chat`) and assume the worst. ## Operational Effect The operational consequence is that **token and cost telemetry emitted under the GenAI conventions is only trustworthy when the emitting runtime enforces the ownership invariant at emission time, because the conventions do not encode it.** An instance that emits nested `chat` spans without a billing-owner attribute produces a trace that is schema-valid and semantically wrong; downstream cost dashboards drift upward monotonically as multi-turn agents relay more sub-agent output, and the drift is indistinguishable from a genuine increase in model usage. The guardrail is to make ownership explicit at the emission boundary: stamp every nested `chat` span with `gen_ai.usage.billing_owner_span_id` referencing the ancestor that will re-ingest its output, and have the aggregator sum only spans where `billing_owner_span_id` is absent or equals the span's own ID. The invariant to assert is: `sum(usage over billing owners) == provider_billed_usage`, and any instance that cannot compute `billing_owner_span_id` must refuse to emit cost attributes rather than emit ambiguous ones. ```python from dataclasses import dataclass, field from typing import Optional class GenAiLineageError(RuntimeError): """Raised when a nested chat span cannot be assigned a unique billing owner.""" pass @dataclass class Span: span_id: str parent_id: Optional[str] operation: str # "chat" | "execute_tool" | ... tool_call_id: Optional[str] = None input_tokens: int = 0 output_tokens: int = 0 billing_owner_span_id: Optional[str] = None children: list = field(default_factory=list) def assign_billing_owner(span: Span, ancestors: list[Span]) -> None: # A chat span nested under execute_tool under chat must name the # ancestor chat span that will re-ingest its output as billing owner. if span.operation != "chat": return chat_ancestors = [a for a in ancestors if a.operation == "chat"] tool_between = any(a.operation == "execute_tool" for a in ancestors) if not chat_ancestors: span.billing_owner_span_id = span.span_id # top-level: owns itself return if not tool_between: # nested chat without a tool boundary: ambiguous, cannot assign raise GenAiLineageError( f"chat span {span.span_id} nested under chat without tool boundary; " f"billing owner undefined" ) owner = chat_ancestors[-1] # nearest enclosing chat is the re-ingester span.billing_owner_span_id = owner.span_id def aggregate_billed_tokens(root: Span) -> int: total = 0 stack = [(root, [])] while stack: node, ancestors = stack.pop() assign_billing_owner(node, ancestors) if node.operation == "chat": # Count only self-owned spans; relayed children are excluded # here and will be counted when the owner re-ingests them. if node.billing_owner_span_id == node.span_id: total += node.input_tokens + node.output_tokens for child in node.children: stack.append((child, ancestors + [node])) return total def verify_against_provider(root: Span, provider_billed: int) -> None: computed = aggregate_billed_tokens(root) if computed != provider_billed: raise GenAiLineageError( f"token lineage broken: trace sums to {computed} but provider " f"billed {provider_billed}; nested chat span lacks a resolvable " f"billing_owner_span_id" ) ```