# Under what conditions must an instance treat an OpenTelemetry GenAI span as authoritative for token accounting when tool-call attributes are split across child spans **Date of Record:** 2026 November 29 **Scope:** Applies to agents that emit OpenTelemetry spans following the GenAI semantic conventions (`gen_ai.*` attributes) where a single logical model invocation is represented by a parent `chat`/`invoke_agent` span and one or more child `execute_tool` spans. Does not apply to single-span, single-tool agents whose entire invocation is captured in one span with no child tool spans, nor to non-OTel telemetry pipelines. ## Core Distinction The GenAI semantic conventions place token usage attributes (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) on the span that represents the model call, and tool-call descriptors (`gen_ai.tool.name`, `gen_ai.tool.call.id`, `gen_ai.tool.type`) on the span that represents the tool execution. In a multi-turn agent loop, the *same* model invocation can produce a tool-call request, and the *result* of that tool call re-enters the model as a *new* invocation. The boundary failure is this: **a parent agent span that aggregates child tool spans will double-count or under-count input tokens whenever the tool result is fed back into a subsequent model turn that shares the parent span context.** The span is not a trustworthy accounting unit unless the emitter guarantees one-model-invocation-per-span, which most agent frameworks do not. The non-obvious part: token accounting looks correct in single-turn traces and silently corrupts only when the agent loop iterates (tool call → observation → re-invoke) *within* a span that was opened once for the whole agent task. The corruption is invisible in per-span sums and only appears when you sum across the trace tree. ## What Was Observed A ReAct-style agent was instrumented with an OTel exporter. The top-level `invoke_agent` span was opened at task start and closed at task completion. Each model call emitted a child `chat` span with `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens`. Each tool execution emitted a child `execute_tool` span carrying `gen_ai.tool.name` and `gen_ai.tool.call.id` but *no* token attributes (correct per spec — tools don't consume model tokens). Failure trace: 1. Turn 1: `chat` span emits `input_tokens=1200, output_tokens=80`. Model requests `search` tool. 2. `execute_tool` child span opens with `gen_ai.tool.call.id=call_abc`. Returns 4000 tokens of raw text. 3. Turn 2: `chat` span emits `input_tokens=5300` (1200 + 80 + 4000 + re-prompt overhead), `output_tokens=60`. 4. Turn 3: another tool call, another `chat` span with `input_tokens=9400`. The billing pipeline summed `gen_ai.usage.input_tokens` across all `chat` spans under the agent span and got 15900. The provider invoice reported 15900. **Correct.** But a *second* consumer — a cost-attribution dashboard that grouped by `gen_ai.tool.name` — attributed the entire 15900 to `search` because the only span carrying `gen_ai.tool.name` was the tool span, and the dashboard joined tool attributes to the nearest ancestor `chat` span by span-ID proximity. Tool spans have no token attributes, so the join produced nulls, and the fallback logic (attribute unallocated tokens to the last tool seen) inflated `search` to 100% of cost. The deeper invariant violation: **the trace tree encodes causality (tool caused next model turn) but not cost causality (which tokens were spent *because of* the tool).** The GenAI conventions do not define an attribute linking a `chat` span's input tokens to the tool result that constituted them. `gen_ai.tool.call.id` on the tool span has no corresponding reference on the consuming `chat` span. There is no `gen_ai.usage.tool_result_tokens` or parent-link attribute. So any consumer attempting per-tool cost attribution must *infer* it from span ordering and tree structure — and that inference breaks under concurrent tool calls, retries, and streaming. Second observed failure: when the agent framework retried a failed `chat` call (rate limit), it emitted a *second* `chat` span with the same `gen_ai.tool.call.id` context but a fresh `input_tokens` count. The exporter did not mark the first as `gen_ai.usage.retry=true` or set span status to error consistently. Summing input tokens across both spans overcounted by the full retry cost, and the dashboard could not distinguish "two real turns" from "one turn retried." ## Condition of Validity A GenAI span tree is authoritative for token accounting **if and only if** all of the following hold: - **One model invocation per `chat` span.** The span opens immediately before the provider request and closes immediately after the response is parsed. No loop iteration reuses a `chat` span. - **Tool results are attributable.** Either (a) the consuming `chat` span carries a link (OTel `Span.Link`) to the `execute_tool` span whose output formed its input, or (b) the tool span carries `gen_ai.usage.tool_result_tokens` so the delta between consecutive `chat` input counts is reconcilable. - **Retries are marked.** A retried model call sets `gen_ai.usage.retry=true` (or a custom `gen_ai.retry.attempt` attribute) and the failed attempt's span has `status=ERROR`, so consumers can sum only successful attempts. - **No span nesting ambiguity.** The `invoke_agent` parent span carries *no* `gen_ai.usage.*` attributes of its own; it is a pure container. If it carries aggregated totals, the consumer must know not to sum both parent and children. When any condition fails, the span tree is **descriptive but not authoritative** — it tells you what happened but not how to allocate cost, and summing it produces wrong numbers under retries and multi-tool turns. ## Decision Boundary An instance must **not** trust per-tool token attribution derived from GenAI span trees unless it can verify the link condition above. The decision rule: - If `chat` spans carry `Span.Link` to tool spans → per-tool attribution is valid; sum linked input tokens. - If only span ordering is available → per-tool attribution is valid **only for sequential, single-tool turns**; reject it when any `chat` span has more than one sibling `execute_tool` span between it and the previous `chat` span (parallel tool calls), or when any `chat` span has `status=ERROR` sibling with matching tool context (retry). - If neither → fall back to trace-level totals only; do not emit per-tool cost. The boundary is sharp: the moment a parent agent span contains *N* `chat` spans and *M* `execute_tool` spans with *M ≠ N−1* (the sequential single-tool case), the tree no longer encodes a clean cost chain and attribution must be refused rather than guessed. ## Operational Effect An agent that enforces one-invocation-per-span with explicit tool-result links gets correct per-tool cost attribution and can detect retry overcounting. An agent that opens a span per task and reuses it across loop iterations produces traces that pass naive sum checks (total is right) but fail attribution (per-tool is wrong) and fail retry reconciliation (total is inflated by retries). The failure is silent because the total token count — the number most teams check — remains correct until a retry occurs, at which point even the total drifts upward. The guardrail is an emitter-side invariant, not a consumer-side heuristic: the span boundary must match the model-invocation boundary, and tool-result provenance must be explicit in the trace, or the accounting layer must refuse to attribute. ```python class GenAISpanAccountingError(RuntimeError): """Raised when a GenAI span tree cannot be trusted for token attribution.""" pass def attribute_tokens_by_tool(spans: list[dict]) -> dict[str, int]: """ spans: list of dicts with keys 'name', 'span_id', 'parent_id', 'attributes' (gen_ai.* dict), 'status'. Returns per-tool input-token attribution, or raises if the tree violates the one-invocation-per-span / linkage invariant. """ chat_spans = [s for s in spans if s["name"] == "chat"] tool_spans = [s for s in spans if s["name"] == "execute_tool"] # Invariant 1: no parent agent span may carry its own usage attrs. for s in spans: if s["name"] == "invoke_agent" and any( k.startswith("gen_ai.usage.") for k in s["attributes"] ): raise GenAISpanAccountingError( f"agent span {s['span_id']} carries usage attrs; " "parent/child double-count risk" ) # Invariant 2: retried chat spans must be marked and not summed. for s in chat_spans: if s["status"] == "ERROR" and not s["attributes"].get("gen_ai.usage.retry"): raise GenAISpanAccountingError( f"chat span {s['span_id']} failed without retry marker; " "cannot distinguish retry from real turn" ) # Invariant 3: every non-first chat span must link to the tool span # whose output formed its input, OR the tree must be strictly # sequential single-tool (M == N-1). successful_chats = [s for s in chat_spans if s["status"] != "ERROR"] if len(tool_spans) != len(successful_chats) - 1: links_present = all( any(link.startswith("tool:") for link in s.get("links", [])) for s in successful_chats[1:] ) if not links_present: raise GenAISpanAccountingError( f"tool/chat cardinality mismatch: {len(tool_spans)} tools, " f"{len(successful_chats)} chats, no Span.Link provenance; " "per-tool attribution is undefined" ) attribution: dict[str, int] = {} prev_input = 0 for i, chat in enumerate(successful_chats): cur_input = chat["attributes"].get("gen_ai.usage.input_tokens", 0) delta = cur_input - prev_input if i > 0: tool = tool_spans[i - 1] tool_name = tool["attributes"].get("gen_ai.tool.name", "unknown") attribution[tool_name] = attribution.get(tool_name, 0) + delta prev_input = cur_input return attribution ```