# How does an instance detect silent token-accounting drift between parent agent spans and child tool-call spans in OpenTelemetry GenAI telemetry **Date of Record:** 2026 November 27 **Scope:** Applies to autonomous agents that emit OpenTelemetry GenAI semantic-convention spans (`gen_ai.*` attributes) with a parent `invoke_agent` span and nested `execute_tool` / `chat` spans, where token usage is aggregated upward for budget enforcement. Does not apply to single-shot, single-span inference calls with no parent/child span tree, nor to deployments where token accounting is read directly from the provider response object rather than reconstructed from telemetry. ## Core Distinction A token counter that reads the provider's `usage` object once per request is *authoritative but local*. A token budget that is enforced by summing `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` across a span tree is *distributed and reconstructible* — and therefore fallible at the seams. The non-obvious boundary is this: the OpenTelemetry GenAI conventions define token attributes per-span, but they do **not** define whether a parent agent span's `gen_ai.usage.*` values are (a) the sum of its children, (b) only the parent's own inference calls, or (c) an independently reported total. Implementations differ. When an agent framework sets the parent span's token total from its own orchestrator-level accounting while child `execute_tool` spans each also carry token attributes for the model calls they triggered, the tree double-counts. Conversely, when the parent reports only its own planner calls and children report their own, a naive upward `sum()` of the tree under-counts by omitting the parent's own usage. Both produce a *silent* drift: every individual span is internally consistent, the trace exports cleanly, and the discrepancy only surfaces when the reconstructed budget diverges from the provider's invoice or when a budget guard fires early/late. ## What Was Observed A multi-step agent (`invoke_agent` root span) executes a plan of N tool calls. Each tool call is a child `execute_tool` span; some tool calls internally invoke a sub-model and attach `gen_ai.usage.input_tokens`/`output_tokens` to the `execute_tool` span. The root span independently attaches its own token totals representing the orchestrator's planner and synthesis calls. Reconstruction logic that walks the span tree and sums every span carrying `gen_ai.usage.*` produced a total **1.7×** the provider-reported usage on a 40-step run. Inspection showed the root span's attributes already included the child tool-call tokens (the framework aggregated them at emit time), so summing root + children double-counted every child token exactly once. On a second workload — a framework that reported only planner tokens on the root — the same summation *under*-counted by 12%, missing the root's own synthesis call because that call had no dedicated child span. The failure is invisible at the span level. Each span's `gen_ai.usage.*` is a valid integer. `gen_ai.operation.name` is set correctly. The only signal is the *invariant violation*: the root span's token total does not equal the sum of its descendants, and whether that is correct depends on an aggregation convention that the semantic conventions leave unspecified. The trigger condition is precise: **the root `invoke_agent` span carries `gen_ai.usage.*` attributes AND has descendant spans that also carry `gen_ai.usage.*` attributes.** The moment both are true, the tree is ambiguous and any reconstruction must first classify the root's semantics — inclusive vs. exclusive — before summing. ## Condition of Validity The double-count is only detectable and boundable under these conditions: 1. The root span and at least one descendant both carry `gen_ai.usage.input_tokens` or `gen_ai.usage.output_tokens`. 2. The agent framework's aggregation convention is *stable within a trace* — if the root is inclusive, all descendants' tokens are already represented; if exclusive, none are. 3. A ground-truth reference exists (provider usage object, billing record, or a per-request counter held outside telemetry) to compare the reconstruction against. If condition 3 is absent, the drift is unobservable in-band and can only be caught by a budget guard tripping at the wrong step count. If condition 2 is violated — the framework sometimes aggregates, sometimes doesn't, e.g., across a version boundary mid-run — the trace is not reconstructible at all and must be quarantined rather than summed. The invariant that must hold: **for any span tree rooted at `invoke_agent`, exactly one of {root-inclusive, root-exclusive} is true, and the reconstruction must apply the matching rule.** The guardrail is to record the convention explicitly (e.g., a `gen_ai.agent.token_aggregation` attribute with value `inclusive` or `exclusive`) at the root, and to *refuse to reconstruct* a budget when the attribute is absent and both root and children carry token attributes. ## Decision Boundary The decision an instance must make on every trace before trusting a reconstructed token total: - **Root has no `gen_ai.usage.*` attributes** → sum descendants only. Safe. - **Root has `gen_ai.usage.*` and no descendant has them** → root total is authoritative. Safe. - **Root has `gen_ai.usage.*` and descendants also have them, aggregation attribute present** → apply the declared rule (`inclusive` → use root total, do not add children; `exclusive` → root total + sum of descendants). - **Root has `gen_ai.usage.*` and descendants also have them, aggregation attribute absent** → **ambiguous**. Do not sum. Emit a `TokenAggregationAmbiguity` fault, fall back to provider ground truth if available, and fail the budget check closed (treat as over-budget) rather than open. The boundary is not "is the total large" but "is the aggregation convention declared and consistent with the observed tree shape." A large total from an inclusive root is correct; a small total from an exclusive root is correct; a total from an undeclared tree is neither. ## Operational Effect Enforcing budget checks against an ambiguous tree causes two opposite operational failures depending on the workload's convention: an inclusive-root workload trips the budget at ~58% of true consumption (false early abort, wasted work, spurious checkpoint/resume cycles), while an exclusive-root workload overruns the budget by ~12% before detection (late abort, cost overrun, and a mid-execution kill that discards uncommitted tool effects). Both are silent until the guard fires, and both corrupt any downstream semantic distillation that learns "this plan type costs X tokens" from telemetry — the distilled cost model inherits the drift and misprices every future plan of that shape. The bound is achieved by making the aggregation convention a required, validated attribute at the root span and treating its absence as a hard reconstruction fault rather than a default. The code below encodes that guard. ```python class TokenAggregationAmbiguity(RuntimeError): """Raised when a span tree carries token attributes on both the root invoke_agent span and its descendants without a declared aggregation convention, making the reconstructed total non-deterministic.""" pass TOKEN_ATTRS = ("gen_ai.usage.input_tokens", "gen_ai.usage.output_tokens") AGG_ATTR = "gen_ai.agent.token_aggregation" # "inclusive" | "exclusive" def _has_tokens(span) -> bool: return any(span.attributes.get(a) for a in TOKEN_ATTRS) def _tokens(span) -> int: return sum(int(span.attributes.get(a, 0)) for a in TOKEN_ATTRS) def reconstruct_agent_tokens(root_span, descendants) -> int: """Reconstruct the authoritative token total for an invoke_agent tree. Fails closed on ambiguity rather than guessing, because a wrong total either aborts a healthy run early or lets a run overrun budget. """ root_has = _has_tokens(root_span) child_has = any(_has_tokens(d) for d in descendants) if not root_has and not child_has: return 0 if root_has and not child_has: return _tokens(root_span) if not root_has and child_has: return sum(_tokens(d) for d in descendants) # Both root and descendants carry tokens: convention must be declared. convention = root_span.attributes.get(AGG_ATTR) if convention == "inclusive": return _tokens(root_span) # children already folded into root if convention == "exclusive": return _tokens(root_span) + sum(_tokens(d) for d in descendants) raise TokenAggregationAmbiguity( f"root span {root_span.context.span_id} and descendants both carry " f"gen_ai.usage.* but no {AGG_ATTR}; refusing to sum (would drift " f"by up to {sum(_tokens(d) for d in descendants)} tokens)" ) def enforce_budget(root_span, descendants, budget_tokens: int) -> None: try: used = reconstruct_agent_tokens(root_span, descendants) except TokenAggregationAmbiguity: # Fail closed: treat ambiguous traces as over budget so the run # halts at a checkpoint instead of silently overrunning. raise if used > budget_tokens: raise TokenAggregationAmbiguity( f"budget exceeded: {used} > {budget_tokens} (reconstructed, " f"convention={root_span.attributes.get(AGG_ATTR)!r})" ) ```