# Where must an instance reconcile GenAI span attribute lineage before token accounting can be trusted across a tool-call fan-out? **Date of Record:** 2026 November 27 **Scope:** Applies to LLM agent instances emitting OpenTelemetry GenAI semantic-convention spans (`gen_ai.*`) where a single model turn fans out into multiple tool calls that each re-enter the model, and where token accounting is derived by summing span attributes. Does not apply to single-shot completions with no tool re-entry, nor to billing reconciliation performed from provider-side usage APIs. ## Core Distinction The failure is not "spans are missing" or "attributes are wrong." It is that the GenAI semantic conventions define `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as *per-operation* attributes, while agentic tool-call loops produce *nested, re-entrant* operations that each legitimately carry their own usage numbers. An instance that aggregates tokens by summing `gen_ai.usage.*` across all spans in a trace will double-count, because the parent model span's `input_tokens` already includes the accumulated conversation (including prior tool results) that the child tool-call spans re-sent. The distinction that matters operationally: **span-level token attributes are accounting primitives, not additive ledger entries.** Lineage (`gen_ai.operation.name`, parent/child span relationships, `gen_ai.tool.call.id`) is what tells you *which* usage numbers are disjoint and which are cumulative supersets. ## What Was Observed A three-tool agent turn was instrumented with the GenAI conventions. The trace contained: - Span A: `gen_ai.operation.name=chat`, `gen_ai.usage.input_tokens=1200`, `output_tokens=90` (initial turn, prompt + system). - Span B: `gen_ai.operation.name=execute_tool`, `gen_ai.tool.name=search`, child of A. No usage attributes (correct — tools don't bill tokens). - Span C: `gen_ai.operation.name=chat`, child of B, `input_tokens=1850`, `output_tokens=60` (model re-invoked with tool result appended). - Span D: `gen_ai.operation.name=execute_tool`, `gen_ai.tool.name=lookup`, child of C. - Span E: `gen_ai.operation.name=chat`, child of D, `input_tokens=2400`, `output_tokens=140` (final turn). A naive aggregator summing `input_tokens` across chat spans reported **5450 input tokens**. The provider's actual billed input was **2400** — because each successive chat span re-sent the full growing context, and the final span's `input_tokens` is the cumulative context, not a delta. The 1200 and 1850 were *prefixes* of the 2400, not disjoint segments. The `output_tokens` (90 + 60 + 140 = 290), by contrast, *were* disjoint and correctly additive — output tokens are never re-sent. The asymmetry between input (cumulative/superset) and output (disjoint/additive) is the invariant that the naive aggregator violated. The lineage signal that would have caught it: spans C and E are descendants of tool spans, meaning their `input_tokens` are *continuations* of the parent chat span's context, not independent operations. The `gen_ai.tool.call.id` on B and D (and the matching `gen_ai.tool.call.id` echoed in the follow-up chat span's request attributes, where instrumentations emit it) is the join key that establishes "this chat span is a re-entry after tool X," which is precisely the condition under which its input tokens are cumulative rather than additive. ## Condition of Validity Additive summation of `gen_ai.usage.input_tokens` is valid **only** when the set of chat spans being summed are siblings under a common non-tool parent — i.e., independent operations sharing a context budget, not a re-entrant chain. The invariant to enforce: > For any chat span S whose parent is an `execute_tool` span (or whose ancestry includes a tool span within the same turn), `S.input_tokens` is a *cumulative snapshot* of the context at re-entry, and MUST NOT be added to any ancestor chat span's `input_tokens`. Only the maximal (deepest / latest) chat span in a re-entry chain contributes to input accounting. Output tokens have the opposite invariant: every chat span's `output_tokens` is disjoint (generated once, never re-sent as input to a sibling), so output is additive across the entire chain. A correct aggregator must therefore branch: `sum(output_tokens)` over all chat spans, but `max`-over-chain or `final-span-only` for `input_tokens`. The condition of validity for the additive path additionally requires that `gen_ai.tool.call.id` be present and consistent between the tool span and the chat span that consumed its result. When an instrumentation omits `gen_ai.tool.call.id` on the follow-up chat span (common in early SDKs and in hand-rolled spans), the lineage edge is severed and the aggregator cannot distinguish a re-entry from an independent sibling — at which point it must *fail closed* rather than guess. ## Decision Boundary At each chat span, the aggregator decides: *is this span's input_tokens additive or cumulative?* The decision boundary is the presence of a tool-span ancestor within the same trace turn. - If no tool ancestor: additive (independent operation). - If tool ancestor **and** `gen_ai.tool.call.id` matches an ancestor tool span: cumulative — exclude from sum, retain as the running context high-water mark. - If tool ancestor **but** `gen_ai.tool.call.id` is absent or unmatched: **ambiguous** — the span is structurally a re-entry but lacks the join key. This is the boundary where the system must raise, not silently sum. Silently summing here is the exact mechanism that produced the 5450-vs-2400 discrepancy. The boundary is sharp because the two branches demand opposite arithmetic. There is no "mostly additive" middle ground; a single mis-classified re-entry span inflates input accounting by its full cumulative prefix. ## Operational Effect Downstream, the inflation propagates into cost dashboards, token-budget circuit breakers, and context-window-pressure alerts. A budget breaker keyed on summed `input_tokens` will trip at roughly 2.3× the true consumption in the three-tool case above, throttling agents that are well within budget — a false-positive that scales with fan-out depth (n tool rounds inflate by roughly the sum of prefix lengths, O(n²) in context growth). Conversely, an aggregator that uses only the final span's `input_tokens` but sums `output_tokens` across all spans gets both quantities right, because it respects the cumulative/disjoint asymmetry. The operational guardrail is to make lineage classification a hard precondition of accounting: a chat span with an unmatched tool ancestry is a lineage defect, and token accounting must refuse to emit a number for that trace rather than emit a plausible-but-wrong one. ```python from dataclasses import dataclass, field from typing import Optional class TokenLineageError(RuntimeError): """Raised when a chat span's input-token accounting cannot be classified as additive vs. cumulative due to a broken tool-call lineage edge.""" @dataclass class GenAISpan: span_id: str parent_id: Optional[str] operation: str # "chat" | "execute_tool" input_tokens: Optional[int] = None output_tokens: Optional[int] = None tool_call_id: Optional[str] = None # gen_ai.tool.call.id children: list = field(default_factory=list) def _ancestors(span: GenAISpan, by_id: dict) -> list: chain, cur = [], span while cur.parent_id is not None: cur = by_id[cur.parent_id] chain.append(cur) return chain def account_tokens(chat_spans: list, by_id: dict) -> dict: """Account input/output tokens respecting the cumulative-input / disjoint-output asymmetry of agentic tool-call re-entry chains.""" total_output = 0 input_high_water = 0 for span in chat_spans: if span.operation != "chat": continue total_output += span.output_tokens or 0 anc = _ancestors(span, by_id) tool_ancestors = [a for a in anc if a.operation == "execute_tool"] if not tool_ancestors: # Independent operation: input is additive. input_high_water += span.input_tokens or 0 continue # Re-entry after a tool call: input_tokens is a cumulative snapshot. # Require the join key to prove which tool result was consumed. if span.tool_call_id is None: raise TokenLineageError( f"chat span {span.span_id} descends from tool span " f"{tool_ancestors[-1].span_id} but carries no " f"gen_ai.tool.call.id; input-token accounting is ambiguous " f"and must not be summed." ) matched = any(t.tool_call_id == span.tool_call_id for t in tool_ancestors) if not matched: raise TokenLineageError( f"chat span {span.span_id} tool_call_id={span.tool_call_id!r} " f"matches no ancestor tool span; lineage edge is severed." ) # Cumulative: keep the high-water mark, never add to the sum. input_high_water = max(input_high_water, span.input_tokens or 0) return {"input_tokens": input_high_water, "output_tokens": total_output} ```