# What structural signals indicate a GenAI agent span's token accounting has silently diverged from its tool-call attribute tree at the OTel export boundary **Date of Record:** 2026 December 3 **Scope:** Applies to any agent runtime that emits OpenTelemetry `gen_ai.*` spans with nested tool-call child spans and per-span `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens` attributes, where a span processor (batching, sampling, or attribute-filtering) sits between the agent and the collector. Does not apply to runtimes that emit a single flat span per turn with no child tool spans, or to pipelines where token counts are derived post-hoc at the collector from raw prompt text. ## Core Distinction The GenAI semantic conventions treat token usage as an attribute of the *span that produced the model call*, and tool invocations as *child spans of that span*. This is a clean model on paper. It is not clean in practice, because the two quantities are produced by different subsystems at different times and are reconciled only implicitly: the model returns a usage block at the end of generation, while tool child spans are emitted synchronously as the agent loop executes them. A parent span's token count and the sum of its children's contributions are therefore *not* derived from a shared counter. They are two independent observations that a reader is expected to trust as mutually consistent. The failure mode this record covers is **orphaned token attribution under attribute-filtering span processors**: a batching or sampling processor drops or rewrites a parent span's `gen_ai.usage.*` attributes (or drops the parent entirely while retaining children), leaving child tool spans whose parent-side token accounting no longer reconciles. The span tree still *looks* well-formed—every child has a parent ID, every span has a name—but the invariant "sum of token usage over the subtree equals the turn's real cost" is violated with no error surfaced anywhere. This is distinct from context-window saturation, from tool-call divergence, and from handoff state loss: nothing in the agent's reasoning is wrong. The telemetry is wrong, silently, and downstream cost/latency dashboards inherit the error. ## What Was Observed A ReAct-style agent loop was instrumented per the GenAI conventions: one `gen_ai.chat` parent span per model turn, with `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` set from the provider's usage block, and one `gen_ai.tool.call` child span per tool invocation carrying `gen_ai.tool.name` and `gen_ai.tool.call.id`. The collector used a `tail_sampling` processor configured to keep "interesting" traces and a `batch` processor with a 5s timeout. Under load, two structural signals appeared that did not exist in low-traffic testing: 1. **Token-bearing parent spans vanished while tool children survived.** The tail sampler's policy keyed on `gen_ai.tool.name` presence to retain "tool-using traces." When a turn's parent span finished *after* the sampler's decision deadline (long generation, short batch flush), the sampler evaluated the trace on the strength of the already-arrived tool child spans and retained them—but the parent span had not yet been exported and was later dropped by the batch deadline. Result: retained `gen_ai.tool.call` children with a `parent_span_id` pointing at a span that would never arrive. 2. **Reconciliation drift without a single malformed span.** A cost dashboard summing `gen_ai.usage.input_tokens` across all spans undercounted the turn's real input cost by exactly the input tokens of every orphaned parent. Every individual span was valid against the schema. No `dropped_attributes_count` was incremented, because the attributes were never dropped—the *whole span* was dropped after the sampler decision. The schema conformance check passed; the accounting invariant failed. The distinguishing structural signal was not an error attribute. It was a **referential integrity violation in the span tree**: `parent_span_id` values with no matching `span_id` in the exported set, specifically for spans whose name matched `gen_ai.chat`. A second signal: `gen_ai.usage.output_tokens` present on zero spans for turns where `gen_ai.tool.call` children existed—because output tokens are only ever set on the parent, and the parent was the thing that vanished. ## Condition of Validity The invariant holds—i.e., subtree token sums are trustworthy—only when all of the following are true: - The span processor's retention decision for a trace is made *after* the root/parent span has ended and been exported, or the sampler is configured to wait on root-span completion rather than on child-span arrival. - No processor drops a parent span while retaining descendants. Head sampling with consistent trace-ID decisions satisfies this; tail sampling keyed on child-span attributes does not, unless it explicitly holds the trace open until the parent arrives. - `gen_ai.usage.*` attributes are never the sole carrier of cost information. If they are, any parent-span loss is unrecoverable at the collector. The invariant is *violated* whenever a sampling or filtering decision can be reached on a strict subset of a trace's spans, and that subset is asymmetric with respect to which spans carry usage attributes. Because usage attributes live on parents and tool-identifying attributes live on children, any sampler that keys on the latter while dropping the former breaks accounting by construction. ## Decision Boundary The operative boundary is: **does the span processor make its keep/drop decision on the root span's completion, or on any span's arrival?** If on root completion (or on a full-trace timeout that guarantees the root is either present or the whole trace is dropped atomically), the token accounting invariant is preserved and subtree sums are safe to aggregate. If on any-span arrival, then you must treat exported traces as *potentially partial* and gate aggregation behind a referential-integrity check: for every exported span with a non-null `parent_span_id`, assert the parent exists in the exported set, or mark the subtree as `incomplete` and exclude it from cost sums rather than silently summing the survivors. The second boundary is attribute-level: a span processor that filters attributes (not spans) must never strip `gen_ai.usage.*` from a parent while leaving `gen_ai.tool.call.*` on children, because the remaining tree will pass schema validation while failing reconciliation. Attribute filters must be applied uniformly across the subtree or not at all. ## Operational Effect Concretely, the runtime must, at export time, compute a per-trace integrity verdict and attach it rather than trusting the sampler. The guard below runs on the exported span batch, reconstructs parent-child links, and raises when a `gen_ai.chat` parent is missing for a subtree that carries tool-call children—because that is precisely the shape of silent token-accounting divergence. It refuses to emit a cost aggregate over a partial tree, forcing the caller to either re-fetch, widen the sampler window, or record the trace as incomplete rather than mis-billed. ```python from dataclasses import dataclass from typing import Iterable class TokenAccountingDivergence(RuntimeError): """Raised when an exported GenAI span subtree cannot be reconciled because a usage-bearing parent span is absent while its tool-call children survived the span processor.""" pass @dataclass(frozen=True) class Span: span_id: str parent_span_id: str | None name: str attributes: dict USAGE_KEYS = ("gen_ai.usage.input_tokens", "gen_ai.usage.output_tokens") TOOL_PREFIX = "gen_ai.tool." def reconcile_token_accounting(spans: Iterable[Span]) -> dict[str, int]: """Sum usage tokens per turn, but only over subtrees whose parent (gen_ai.chat) span is present in the exported set. Raises if a tool-call child's parent is missing, since that parent is the sole carrier of the usage attributes and its loss silently zeroes cost.""" by_id = {s.span_id: s for s in spans} totals: dict[str, int] = {} for span in by_id.values(): if span.parent_span_id is None: continue parent = by_id.get(span.parent_span_id) has_tool_attr = any(k.startswith(TOOL_PREFIX) for k in span.attributes) if parent is None and has_tool_attr: # Tool child exported, usage-bearing parent absent: the exact # shape of tail-sampler / batch-deadline divergence. raise TokenAccountingDivergence( f"tool child {span.span_id} ({span.name}) references " f"missing parent {span.parent_span_id}; token usage " f"unrecoverable from exported spans" ) if parent is not None and parent.name == "gen_ai.chat": turn = parent.span_id for key in USAGE_KEYS: totals[turn] = totals.get(turn, 0) + int( parent.attributes.get(key, 0) ) if not totals: raise TokenAccountingDivergence( "no gen_ai.chat parent spans with usage attributes survived " "export; refusing to emit a zero-cost aggregate" ) return totals ```