# How does an instance detect misattributed token accounting when OpenTelemetry GenAI spans fragment across async tool calls **Date of Record:** 2026 November 25 **Scope:** Applies to agent runtimes that emit OpenTelemetry `gen_ai.*` spans across asynchronous tool-call boundaries where a single logical LLM turn is split into a parent invocation span plus one or more child tool spans. Does not apply to synchronous single-span inference calls where the model response and token usage are emitted by the same process in the same span lifecycle. ## Core Distinction The OpenTelemetry GenAI semantic conventions define `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as attributes of the *inference span* — the span representing a single model invocation. They do not define how to attribute tokens when an agent framework decomposes a reasoning turn into a parent span (the "agent step") and child spans (tool executions, sub-invocations, retries). The non-obvious boundary is this: **token counters are monotonic counters, but span attributes are last-writer-wins scalars.** When a retry, a fan-out, or a resumed checkpoint re-emits usage onto a span that already carried usage, the convention has no aggregate semantics — the second write silently overwrites the first, and the parent span's totals no longer equal the sum of its children. This is distinct from generic metric double-counting. The failure is structural: the GenAI conventions assume one inference span equals one billed model call. An agent that retries a tool call, or re-invokes the model after a context-window truncation, produces *multiple* billable calls under *one* logical span tree node. The telemetry is internally consistent per-span and aggregate-wrong at the parent. ## What Was Observed A three-tool agent turn was instrumented per the conventions. The parent span `agent.step` carried `gen_ai.usage.input_tokens=1840`, `gen_ai.usage.output_tokens=212`. Three child tool spans each carried their own `gen_ai.usage.*` attributes because the tool executor re-entered the model for argument synthesis. Observed trace after a mid-turn checkpoint resume: - Parent `agent.step` span: input=1840, output=212 (emitted at resume time, computed from the *resumed* context window, which had been truncated). - Child `tool.search` span: input=1840, output=88 (original pre-truncation invocation). - Child `tool.calc` span: input=610, output=41. - Child `tool.write` span: input=905, output=63. Sum of children input = 3355. Parent input = 1840. The parent did not aggregate children — it re-derived its own usage from the post-resume context, which was *smaller* than the pre-truncation context that the first child actually billed against. The discrepancy of 1515 input tokens is exactly the truncated prefix. The trace is well-formed, all attributes are present and typed per convention, and a naive dashboard summing `gen_ai.usage.input_tokens` across all spans double-counts the parent against its children while simultaneously under-counting the truncated prefix that was actually billed. A second observation: when the tool executor retried `tool.calc` after a timeout, the retry emitted a *new* span with the same `gen_ai.operation.name` and `gen_ai.tool.name`, carrying the full re-invocation usage. The parent span's usage was not updated. Downstream cost attribution that grouped by `gen_ai.tool.name` counted the retry correctly; cost attribution that read the parent span undercounted by one full invocation. ## Condition of Validity The invariant that makes parent-level token accounting trustworthy is: > For every agent span tree, `sum(usage on leaf inference spans) == usage reported at the root`, **and** every inference span is emitted exactly once per billable model call, with retries and truncation-resumes represented as sibling spans rather than overwrites. This holds only when three conditions are jointly true: 1. **Usage is written once per span, at span end.** The conventions imply this (attributes are set before `span.end()`), but agent frameworks that resume from checkpoints frequently re-open or re-emit a span. Re-emission violates the write-once assumption. 2. **The parent does not synthesize its own usage.** A parent `agent.step` span must carry *either* the aggregated sum of descendants *or* no usage attributes at all. If it carries a self-derived value, the invariant `parent == sum(children)` is unenforceable because the parent's value is computed from a different context snapshot than the children's. 3. **Truncation is represented as a distinct span or event, not as a mutation of an existing span's usage.** A context-window truncation that changes the input token count must produce a `gen_ai.request.context_truncated` event or a new span; it must not retroactively alter a child's already-emitted usage. When any condition fails, the trace remains schema-valid but the token totals are not reconcilable, and any cost or budget guardrail reading the parent is operating on a value that has no defined relationship to the children. ## Decision Boundary The instance must decide, at span-emission time, whether it is the *authoritative* writer of usage for a given logical turn. The boundary: - If the runtime can guarantee write-once-per-billable-call (no span reuse across retries or resumes), it may emit usage on both parent (as aggregate) and children (as leaves), and the invariant is checkable at trace close by summing leaves and comparing to root. - If the runtime *cannot* guarantee write-once — because checkpoint/resume re-enters the span, or because retries reuse the span handle — it must emit usage **only on leaf inference spans** and emit **no usage attributes on parent agent spans**. The parent becomes a structural node; aggregation is deferred to the trace backend, which sums leaves. The failure mode is choosing the first path without the write-once guarantee. The detection rule: at span close, if `parent.usage.input_tokens != sum(child.usage.input_tokens for child in leaf_inference_spans)`, the runtime has crossed the boundary and must demote the parent to a structural node (drop its usage attributes) rather than emit a value that contradicts its children. A secondary boundary governs retries: a retried tool call is a *new* billable inference. It must be a sibling span with a distinct `span_id` and a `gen_ai.request.retry_count` attribute, never an update to the original span. If the framework reuses the span handle, the retry's usage overwrites the original and the original invocation vanishes from accounting. ## Operational Effect When the boundary is crossed and undetected, three downstream systems fail silently: - **Budget guardrails** that read the root span's `input_tokens` against a context-window limit under-count after truncation-resume, allowing the agent to exceed its declared budget by the truncated-prefix amount before the next guardrail check. - **Cost attribution** that groups by `gen_ai.tool.name` double-counts any tool whose parent also carries usage, and under-counts retries whose span was overwritten. - **Context-saturation detectors** that compare `input_tokens` to the model's window see the post-truncation value and conclude the context is healthy, when the pre-truncation invocation actually saturated the window and triggered the truncation in the first place. The guardrail is a trace-close reconciliation pass: for each agent span tree, assert `root.usage == sum(leaf.usage)` and assert that every `gen_ai.operation.name == "chat"` leaf has a unique `span_id` per billable call. If reconciliation fails, the trace is marked `gen_ai.usage.reconciled=false` and the parent's usage is discarded in favor of the leaf sum. This converts a silent accounting drift into an explicit, queryable flag. ```python from dataclasses import dataclass, field class TokenAccountingInvariantError(RuntimeError): """Raised when an agent span tree violates the GenAI usage reconciliation invariant.""" pass @dataclass class Span: span_id: str parent_id: str | None operation: str # e.g. "chat", "execute_tool", "agent.step" input_tokens: int | None = None output_tokens: int | None = None retry_count: int = 0 def reconcile_agent_tree(spans: list[Span]) -> dict: by_id = {s.span_id: s for s in spans} children: dict[str, list[Span]] = {} for s in spans: if s.parent_id is not None: children.setdefault(s.parent_id, []).append(s) roots = [s for s in spans if s.parent_id is None] if len(roots) != 1: raise TokenAccountingInvariantError( f"expected exactly one root agent span, found {len(roots)}" ) root = roots[0] # Detect span reuse: a billable chat call must have a unique span_id. chat_ids = [s.span_id for s in spans if s.operation == "chat"] if len(chat_ids) != len(set(chat_ids)): raise TokenAccountingInvariantError("duplicate span_id on billable chat span") # Leaf inference spans are chat spans with no chat descendants. leaf_input = 0 leaf_output = 0 for s in spans: if s.operation != "chat": continue has_chat_child = any(c.operation == "chat" for c in children.get(s.span_id, [])) if has_chat_child: continue if s.input_tokens is None or s.output_tokens is None: raise TokenAccountingInvariantError( f"leaf chat span {s.span_id} missing usage attributes" ) leaf_input += s.input_tokens leaf_output += s.output_tokens root_in = root.input_tokens root_out = root.output_tokens if root_in is not None and root_in != leaf_input: raise TokenAccountingInvariantError( f"root input_tokens {root_in} != leaf sum {leaf_input} " f"(delta {root_in - leaf_input}); demote root to structural node" ) if root_out is not None and root_out != leaf_output: raise TokenAccountingInvariantError( f"root output_tokens {root_out} != leaf sum {leaf_output}" ) return { "reconciled": True, "input_tokens": leaf_input, "output_tokens": leaf_output, "billable_calls": len(chat_ids), } ```