# Under what conditions must an instance refuse to emit a terminal GenAI span when tool-call attributes and token counters disagree at close time **Date of Record:** 2026 November 28 **Scope:** Applies to any LLM agent runtime that emits OpenTelemetry spans conforming to the GenAI semantic conventions (`gen_ai.*`) for agent/tool invocations and token usage. Does not apply to pure inference-only spans with no tool-call children, nor to runtimes that discard spans locally and never export. ## Core Distinction There is a difference between *a span that closes* and *a span that is true*. The OpenTelemetry GenAI conventions let you attach `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, and per-tool attributes like `gen_ai.tool.name` and `gen_ai.tool.call.id` to a span, but they do not define a reconciliation invariant between the *aggregate token counter* the model runtime reports at end-of-turn and the *sum of tokens attributable to individual tool calls* recorded as child spans or span events. In a healthy run these agree within a bounded slack. When they diverge beyond slack, the span is structurally well-formed but semantically poisoned: it will be exported, indexed by the observability backend, and used downstream for cost attribution, rate-limit accounting, and — critically — as retrieval context for future agent self-reflection loops. A terminal span emitted under divergence is worse than no span, because it launders an accounting error into a durable record. The non-obvious part: divergence is *not* an error signal. It is a normal consequence of streaming tool-call deltas, provider-side tokenizer differences between the counting API and the serving path, and speculative decoding where the model's final usage block is computed before tool-call arguments finish streaming. The runtime must distinguish "diverged because the provider's counter is coarse" from "diverged because a tool call was dropped, replayed, or double-counted." ## What Was Observed A ReAct-style agent (model → tool → model, up to N iterations) emitted spans where the parent `gen_ai.agent` span carried `gen_ai.usage.input_tokens=18422` and `gen_ai.usage.output_tokens=1104`. Three child `gen_ai.tool` spans carried per-call token attributions summing to `input=17110, output=980`. The residual — 1312 input, 124 output — exceeded the configured slack of 5% + 64 tokens on the input side. The parent span nevertheless closed with `status=OK` and was exported. Forensics on the trace: the third tool call had been issued, its arguments streamed partially, then the model emitted a *second* tool call in the same assistant turn (parallel tool calls). The runtime's span emitter created a child span for the first tool call, created a child span for the second, but the second child's `gen_ai.tool.call.id` collided with the first because the provider reused a call-id under a known streaming quirk. The span processor's dedup-by-attribute logic silently merged the two children, dropping the second call's tokens from the child sum while the parent counter — sourced from the provider's authoritative usage block — retained them. The parent's total was *correct*; the children's sum was *deficient*; the residual looked like untracked reasoning tokens, which is a legitimate category, so no alarm fired. The failure is not that the numbers disagreed. The failure is that the disagreement was *plausibly explainable* by a benign cause (untracked reasoning tokens) and therefore passed every heuristic gate. The invariant that was violated is subtler: **a terminal span must be able to account for its residual, not merely tolerate it.** If the runtime cannot attribute the residual to a named bucket — reasoning tokens, system-prompt tokens, cache-read tokens — it must not emit the span as terminal. ## Condition of Validity The refusal-to-emit rule is valid only under the following conditions, and must be *suspended* otherwise: 1. **The provider supplies an authoritative usage block.** If the runtime is synthesizing token counts by local tokenization, the residual is meaningless and the invariant does not apply — local counts are advisory and must be tagged `gen_ai.usage.source=local_estimate`. 2. **Tool-call children are keyed by a stable call-id.** If the provider does not guarantee call-id uniqueness within a turn (several streaming APIs do not), the runtime must key children by `(call_id, ordinal)` and the reconciliation must run against the ordinal-keyed set. 3. **The slack bound is derived, not hardcoded.** Slack must be a function of `(provider, model, streaming_enabled, parallel_tool_calls)` — a fixed 5% is wrong for streaming providers whose usage block is finalized before argument streaming completes. 4. **The span is not already marked non-terminal.** Spans that are checkpointed and resumed (mid-task persistence) must carry `gen_ai.span.terminal=false` and are exempt; only the final close is subject to the invariant. If any condition fails, the correct behavior is to emit the span with `gen_ai.usage.reconciled=false` and a `gen_ai.usage.residual_unattributed` attribute, not to refuse. Refusal without these preconditions produces false negatives that are themselves a failure mode — agents that never close spans under flaky providers. ## Decision Boundary The boundary between "emit as terminal" and "refuse and quarantine" is a three-way test at close time: - **Reconciled:** `|parent_total - sum(children) - named_residual| <= slack(provider, model, streaming)`. Emit with `reconciled=true`. - **Attributable residual:** disagreement exists but every unit of residual maps to a named bucket present in the span (`gen_ai.usage.reasoning_tokens`, `gen_ai.usage.cache_read_tokens`, `gen_ai.usage.system_tokens`). Emit with `reconciled=true` and per-bucket attributes. - **Unattributable residual:** disagreement exceeds slack and residual cannot be mapped to a named bucket. **Do not emit as terminal.** Emit a `gen_ai.agent.close_failed` span event with the residual, set `status=ERROR` with `error.type=gen_ai.usage.reconciliation_failed`, and route the trace to a quarantine exporter. The boundary is *not* "does the number look wrong." It is "can the runtime name what the leftover tokens are." A runtime that cannot name the residual has either lost a tool call, double-counted a streamed delta, or is running against a provider whose usage semantics it does not model — and in all three cases the span is unfit to be a durable record. ## Operational Effect Enforcing the boundary changes three downstream behaviors. First, cost attribution stops silently absorbing orphaned tokens into the "reasoning" bucket — the quarantine exporter surfaces them, and per-tool cost dashboards become trustworthy because children are ordinal-keyed and never merged. Second, agent self-reflection loops that retrieve prior spans as context no longer ingest poisoned accounting, which removes a class of compounding error where an agent "learns" that its tool calls are cheaper than they are and over-schedules them. Third, provider integration becomes a gated operation: a new model or streaming mode cannot be promoted to terminal-span emission until its slack function is calibrated and its call-id uniqueness is verified — a one-time cost that prevents the silent-merge class of failure entirely. The residual risk is quarantine volume: a misconfigured slack function will quarantine every span. That is the correct failure direction — a quarantine storm is loud and diagnosable; laundered accounting is silent and corrupts memory. ```python from dataclasses import dataclass class GenAIUsageReconciliationError(RuntimeError): """Raised when a terminal GenAI span cannot account for its token residual.""" @dataclass(frozen=True) class UsageBlock: input_tokens: int output_tokens: int reasoning_tokens: int = 0 cache_read_tokens: int = 0 system_tokens: int = 0 @dataclass(frozen=True) class ProviderProfile: name: str streaming: bool parallel_tool_calls: bool def slack(self, parent_input: int) -> int: # Streaming providers finalize usage before argument streaming completes; # parallel tool calls widen the bound because call-id reuse is common. base = max(64, int(parent_input * 0.05)) if self.streaming: base += 128 if self.parallel_tool_calls: base += 256 return base def reconcile_terminal_span( parent: UsageBlock, child_sum: UsageBlock, profile: ProviderProfile, usage_source: str = "provider", ) -> None: if usage_source != "provider": # Local estimates are advisory; invariant does not apply. return parent_total = parent.input_tokens + parent.output_tokens child_total = child_sum.input_tokens + child_sum.output_tokens named_residual = ( parent.reasoning_tokens + parent.cache_read_tokens + parent.system_tokens ) residual = parent_total - child_total - named_residual slack = profile.slack(parent.input_tokens) if residual > slack: raise GenAIUsageReconciliationError( f"unattributable residual {residual} tokens exceeds slack {slack} " f"for provider={profile.name} streaming={profile.streaming} " f"parallel={profile.parallel_tool_calls}; " f"refusing to emit terminal span" ) if residual < -slack: raise GenAIUsageReconciliationError( f"children over-count parent by {-residual} tokens beyond slack {slack}; " f"possible duplicate tool-call spans" ) def close_agent_span( parent: UsageBlock, child_sum: UsageBlock, profile: ProviderProfile, usage_source: str = "provider", ) -> dict: try: reconcile_terminal_span(parent, child_sum, profile, usage_source) except GenAIUsageReconciliationError as exc: return { "status": "ERROR", "error.type": "gen_ai.usage.reconciliation_failed", "gen_ai.usage.reconciled": False, "gen_ai.agent.close_failed": str(exc), } return { "status": "OK", "gen_ai.usage.reconciled": True, "gen_ai.usage.input_tokens": parent.input_tokens, "gen_ai.usage.output_tokens": parent.output_tokens, } ```