# What happens when an instance attributes the tool-call span to the wrong agent turn and the GenAI token accounting silently double-counts the parent's completion tokens **Date of Record:** 2026 November 25 **Scope:** Applies to agents instrumented with OpenTelemetry GenAI semantic conventions (`gen_ai.*`) where a single logical turn fans out into child tool-execution spans and the parent `gen_ai.chat` span reports `gen_ai.usage.output_tokens`. Does not apply to single-shot inference calls with no nested tool spans, nor to systems that emit usage only at the trace root. ## Core Distinction The distinction that matters here is between **span nesting as causal structure** and **span nesting as accounting structure**. Under the GenAI semantic conventions, a parent `gen_ai.chat` span and its child `gen_ai.tool` (execute_tool) spans form a tree by `parent_span_id`. It is tempting to assume that tree also defines token attribution: the parent owns its `gen_ai.usage.output_tokens`, children own nothing (tool spans carry no usage), and a trace-level sum is therefore the turn cost. That assumption is false because the model's *second* inference — the one that consumes the tool result and produces the next assistant message — is frequently emitted as a **sibling** of the first `gen_ai.chat` span rather than a continuation of it, depending on how the agent loop wraps each model call. When the loop re-enters the model after a tool result, an instrumented SDK that opens a fresh `gen_ai.chat` span per call will produce a turn graph like: ``` turn (agent.turn) [no usage] ├── gen_ai.chat #1 output_tokens=210 │ └── gen_ai.tool (search) [no usage] └── gen_ai.chat #2 output_tokens=340 └── gen_ai.tool (fetch) [no usage] ``` The accounting invariant that operators *believe* holds — "sum of `gen_ai.usage.output_tokens` over `gen_ai.chat` spans in a trace equals the turn's billed output" — holds only if every model call is emitted exactly once. The failure mode is that a wrapper layer (often the observability middleware, not the agent) **re-attributes the tool span under the first chat span while also emitting a synthetic usage record on the `agent.turn` span copied from the last chat span.** The result is that `output_tokens` for the turn is counted twice: once as the sum of the two chat spans, once as the turn-span aggregate. Dashboards built on `sum(gen_ai.usage.output_tokens)` by `trace_id` now over-report by exactly the size of the final completion, and the over-report scales with turn length. ## What Was Observed In a mid-size deployment, cost dashboards diverged from the provider invoice by a stable ~1.6× factor over a week. The divergence was not uniform: single-tool turns were near-correct, multi-tool turns over-reported, and turns that ended in a refusal (no second chat span) under-reported relative to the invoice because the refusal path emitted the turn-span aggregate but no child chat span. The trace-level evidence: 1. `agent.turn` span carried `gen_ai.usage.output_tokens=340` (copied forward by the wrapper from the last chat call, as a convenience for turn-level queries). 2. Two `gen_ai.chat` children carried `output_tokens=210` and `340`. 3. A backend aggregator summing `gen_ai.usage.output_tokens` across *all* spans with that attribute in the trace returned `210 + 340 + 340 = 890`, against a true turn cost of `550`. 4. The tool spans themselves correctly carried no usage — the corruption was entirely in the turn-span aggregate and the double-parenting of the tool span under chat #1. The non-obvious part: the agent code was correct. Each model call emitted exactly one usage record. The corruption was introduced by the **span processor** that merged the loop's per-call spans into a turn graph for a nicer UI, and that processor had no way to distinguish "the turn span is a rollup" from "the turn span is a distinct unit of work" because the semantic conventions do not currently define a `gen_ai.usage.aggregation` or rollup marker. Both a real inference span and a rollup span carry `gen_ai.usage.output_tokens` with identical type and unit. ## Condition of Validity The invariant "trace-summed `gen_ai.usage.output_tokens` equals billed output" is valid **if and only if** every span carrying that attribute represents a distinct, non-overlapping unit of model output. This requires: - No span in the trace is a *rollup* of other spans' usage (or, if it is, it is marked with a distinct attribute such as `gen_ai.usage.aggregate=true` and excluded from sums). - Each `gen_ai.chat` (or `gen_ai.inference`) span corresponds to exactly one provider call, and retries emit a new span with `gen_ai.request.retry_count` rather than mutating the original. - Tool spans carry no `gen_ai.usage.*` attributes, and the agent loop does not re-parent a tool span under more than one chat span. - The turn graph is a tree, not a DAG: no span has multiple parents, because a tool result consumed by two subsequent model calls will otherwise appear under both and its (zero) usage will be double-attributed if the tool itself ever emits usage. The condition fails silently — no span is malformed, no attribute is missing, every individual span validates against the schema. The corruption is purely in the *graph shape and attribute duplication*, which the conventions do not constrain. ## Decision Boundary The boundary is: **does the span carry usage as a leaf measurement or as a rollup?** If a span's `gen_ai.usage.output_tokens` is a measurement of one model call, it belongs in the sum. If it is a convenience copy of a descendant's value, it must be excluded. Because the conventions do not encode this distinction, the operator must choose one of two disciplines: - **Leaf-only accounting:** aggregators sum usage only over spans with no `gen_ai.chat` descendants (i.e., leaf inference spans), and turn-span rollups are forbidden or renamed to a non-`gen_ai.usage.*` attribute (e.g., `agent.turn.output_tokens`). This keeps the invariant enforceable by graph shape alone. - **Rollup-only accounting:** leaf chat spans omit usage and only the turn span reports it. This is cheaper to query but loses per-call cost breakdown and breaks retry attribution. Mixing the two — which is what the wrapper did — produces the double-count. The decision boundary is therefore structural: pick one attribution layer and make it the *only* layer that emits `gen_ai.usage.*`, and enforce it at span-processor admission time, not at dashboard query time. ## Operational Effect The downstream effects compound: - **Cost alarms fire on healthy traffic.** The 1.6× over-report means budget thresholds calibrated against the invoice trigger early; operators who "fix" this by scaling the alarm threshold then under-detect genuine runaway loops. - **Per-tool cost attribution inverts.** Because the tool span was re-parented under chat #1, the tool's latency and the preceding model call's output tokens appear causally linked. Analysts conclude the search tool "caused" the expensive completion and prune the wrong tool. - **Retry storms become invisible.** When a chat span is mutated on retry rather than re-emitted, the trace shows one call with the last attempt's usage; the retried attempts' tokens vanish from the sum. Combined with the rollup double-count, the trace can simultaneously over- and under-report different turns, so the aggregate error is not even a stable multiplier. - **Replay-based verification breaks.** An auditor replaying the trace to reconstruct the turn cannot distinguish a legitimate two-call turn from a duplicated-usage turn, because both have identical span structure and identical attribute sets. The trace is *structurally ambiguous* with respect to the accounting question it is being asked to answer. The guardrail is an admission-time invariant in the span processor: reject or rewrite any span that carries `gen_ai.usage.*` while also having a `gen_ai.chat` descendant, and reject any trace where a `gen_ai.tool` span has more than one parent. This is cheap to enforce and converts a silent accounting corruption into a loud instrumentation error. ```python from dataclasses import dataclass, field class UsageAttributionError(RuntimeError): """Raised when a span graph violates the leaf-only usage invariant.""" @dataclass class Span: span_id: str parent_id: str | None kind: str # "agent.turn" | "gen_ai.chat" | "gen_ai.tool" output_tokens: int | None = None children: list[str] = field(default_factory=list) def validate_usage_attribution(spans: dict[str, Span]) -> int: """Enforce leaf-only gen_ai.usage accounting and return true turn cost. Invariant: a span carrying output_tokens must have no gen_ai.chat descendant. A turn span that copies a descendant's usage is a rollup and must be rejected. """ parent_count: dict[str, int] = {} for s in spans.values(): if s.parent_id is not None: parent_count[s.parent_id] = parent_count.get(s.parent_id, 0) + 1 def has_chat_descendant(span_id: str) -> bool: stack = list(spans[span_id].children) while stack: child = spans[stack.pop()] if child.kind == "gen_ai.chat": return True stack.extend(child.children) return False total = 0 for s in spans.values(): if s.kind == "gen_ai.tool" and parent_count.get(s.span_id, 0) > 1: raise UsageAttributionError( f"tool span {s.span_id} has multiple parents; " "tool results consumed by two model calls must not share a span" ) if s.output_tokens is None: continue if s.kind != "gen_ai.chat" and has_chat_descendant(s.span_id): raise UsageAttributionError( f"rollup span {s.span_id} ({s.kind}) carries output_tokens=" f"{s.output_tokens} while having a gen_ai.chat descendant; " "this double-counts the child's usage in trace-level sums" ) total += s.output_tokens return total # trace from the incident: turn span copies chat #2's usage trace = { "t": Span("t", None, "agent.turn", output_tokens=340, children=["c1", "c2"]), "c1": Span("c1", "t", "gen_ai.chat", output_tokens=210, children=["tool1"]), "tool1": Span("tool1", "c1", "gen_ai.tool"), "c2": Span("c2", "t", "gen_ai.chat", output_tokens=340, children=["tool2"]), "tool2": Span("tool2", "c2", "gen_ai.tool"), } try: validate_usage_attribution(trace) except UsageAttributionError as e: # correct behavior: reject the trace rather than report 890 vs true 550 print(f"rejected: {e}") ```