# Why does an instance emit phantom gen_ai.usage.input_tokens when a tool span is closed twice under OpenTelemetry GenAI semantic conventions **Date of Record:** 2026 November 21 **Scope:** Applies to agent runtimes that emit OpenTelemetry spans conforming to the GenAI semantic conventions (`gen_ai.operation.name`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.tool.name`) where tool-call spans are opened and closed by a separate executor coroutine from the one that owns the parent `invoke_agent` span. Does not apply to single-threaded runtimes that guarantee exactly-once span termination, nor to runtimes that aggregate token usage only at the root span. ## Core Distinction A **token accounting fact** is the number of input/output tokens the model provider billed for a single inference call. A **token accounting span attribute** is what the agent runtime writes onto `gen_ai.usage.*` at the moment a span is ended. These are not the same object, and the OTel GenAI conventions do not require them to be reconciled — they specify *where* to put the numbers, not *when* the numbers become immutable. The boundary failure lives in that gap: when a tool span is terminated more than once (a retry path, a `finally` block racing a timeout handler, a deferred executor closing an already-closed child), the runtime re-reads the *current* usage counter from the model client and writes it onto the span again. Because the semantic conventions define `gen_ai.usage.input_tokens` as a **cumulative-per-span** attribute with no idempotency key, the second write is a fresh observation, not a no-op. The collector sees two spans (or one span with a mutated attribute if the same `Span` object is still referenced) each claiming the full prompt-token count, and any downstream aggregation that sums `gen_ai.usage.input_tokens` across the trace now overcounts by the prompt size multiplied by the number of duplicate terminations. The invariant that is silently violated: *a span's usage attributes must be a snapshot of a single inference, captured exactly once, at a point where the underlying counter cannot have advanced.* ## What Was Observed A tool-using agent (planner + `execute_tool` executor) running against a provider with prompt caching showed a trace where a single `invoke_agent` root span reported `gen_ai.usage.input_tokens = 18,940` while the sum of its child `execute_tool` and `chat` spans reported `41,220`. The trace was structurally valid — no orphan spans, no broken parent links — yet the per-span sum exceeded the root by 2.18×. Isolating the discrepancy: three `execute_tool` spans for the same `gen_ai.tool.name = "search_docs"` shared an identical `start_time_unix_nano` and differed only in `end_time_unix_nano` by 40–90 ms. Each carried `gen_ai.usage.input_tokens` equal to the *full current* prompt size (the executor re-read `client.last_usage` inside a `finally` that ran after a timeout-triggered cancellation, and the cancellation handler had already closed the span). The failure trace: 1. Executor opens `execute_tool` span `S`, records `start_time`. 2. Tool call hangs; a 30 s watchdog fires and calls `S.end()` inside the timeout handler, writing `gen_ai.usage.*` from `client.last_usage` (which still holds the *previous* chat call's usage — the tool call itself consumed no tokens, but the attribute is written anyway because the runtime treats "span end" as "flush usage"). 3. The hung tool eventually returns; the executor's `finally` block runs `S.end()` again. The OTel SDK, for an already-ended span, is a no-op on `end_time` but **does not** reject attribute writes made via `span.set_attribute` before the second `end()` — and the runtime's helper re-sets `gen_ai.usage.input_tokens` from `client.last_usage`, which has now advanced to the *next* chat call's usage because the planner already issued a follow-up inference during the 40 ms window. 4. The collector receives one span whose `gen_ai.usage.input_tokens` reflects the follow-up inference, attributed to a tool call that never billed those tokens. The non-obvious part: the *count* of spans was correct (one `execute_tool` span). The corruption was purely in the attribute value, and only because the usage-flush was coupled to span termination rather than to the inference that produced the usage. A naive "count spans" validator passes; a "sum usage" validator fails. ## Condition of Validity The phantom-token failure requires all four of the following simultaneously: - **Decoupled lifecycle.** The span's `end()` is reachable from more than one control path (watchdog, `finally`, explicit cancel) without a guard. - **Late-binding usage read.** `gen_ai.usage.*` is populated by reading a mutable client-level counter at end-time, rather than captured as an immutable record returned by the specific inference call. - **Counter advancement between terminations.** A subsequent inference (the planner's follow-up `chat` call) runs between the first and second `end()`, so the re-read returns a *different* number — this is what makes the second write a corruption rather than a duplicate. - **Summing aggregation downstream.** The observability backend or cost-attribution job sums `gen_ai.usage.input_tokens` across spans rather than taking it from the root or from a deduplicated `gen_ai.response.id`. If any one is absent, the failure does not manifest: a guarded `end()` (idempotent) prevents the second write; an immutable per-call usage record makes the second write identical and thus harmless; no intervening inference makes it a benign duplicate; root-only aggregation ignores child usage entirely. ## Decision Boundary The architectural choice is **where token usage is bound to the span**. Two positions are defensible and they are not interchangeable: - **Bind-at-inference (correct for cost accounting).** The inference client returns an immutable `Usage` record alongside the response. The span captures that record at the moment the inference completes, sets `gen_ai.usage.input_tokens`/`output_tokens` once, and marks the attributes frozen. Any subsequent `end()` is a pure lifecycle operation with no attribute side effects. This is the only position that survives duplicate termination. - **Bind-at-end (correct only for latency spans).** The runtime flushes whatever the client counter says at `end()`. This is acceptable *only* if `end()` is provably exactly-once and no inference can interleave. In practice, agent executors violate both preconditions because tool calls and planner inferences run concurrently. The boundary: **if the span's `gen_ai.operation.name` is `execute_tool` or `chat` and the runtime can terminate the span from a watchdog or cancellation path, bind-at-end is invalid.** The guardrail is to make usage capture a one-shot, monotonic write: the first write wins, subsequent writes are rejected, and the rejection is observable (a counter `otel.genai.usage.write_rejected`), not silent. ## Operational Effect Downstream, this failure corrupts three things at once and each hides the others. Cost attribution overcounts because child usage is summed; the overcount is *proportional to prompt size*, so it grows with context length and is worst exactly on the long-context agent runs where cost accuracy matters most. Latency dashboards are unaffected (the span count and durations are correct), so the anomaly does not trip latency SLOs. And trace-based debugging is actively misled: the `execute_tool` span claims to have consumed tokens it never did, so an engineer investigating "why is this tool call so expensive" chases a phantom. The only reliable detector is a **cross-span invariant check**: for every `invoke_agent` root, assert `sum(child gen_ai.usage.input_tokens) <= root gen_ai.usage.input_tokens` (children are subsets of the root's cumulative usage, never exceed it). A violation of that inequality is a near-certain duplicate-termination phantom, and it is checkable in the collector without knowing the runtime's internals. The remediation is structural, not a patch: usage attributes must be written from an immutable per-call record, the write must be idempotent (first-wins), and the trace validator must enforce the root-dominates-children inequality as a hard gate rather than a warning. ```python from dataclasses import dataclass, field class PhantomUsageError(RuntimeError): """Raised when a span's gen_ai.usage.* attributes are written more than once from a mutable counter, producing a token count that did not belong to the inference the span represents.""" @dataclass(frozen=True) class Usage: input_tokens: int output_tokens: int @dataclass class GenAISpan: operation: str tool_name: str | None = None _usage: Usage | None = None _usage_frozen: bool = False _ended: bool = False rejected_writes: int = field(default=0) def record_usage(self, usage: Usage) -> None: if self._usage_frozen: # Second termination path re-read a counter that advanced. This is # the phantom-token condition: reject and make it observable. self.rejected_writes += 1 raise PhantomUsageError( f"usage already frozen on span op={self.operation!r} " f"tool={self.tool_name!r}; attempted re-write " f"input={usage.input_tokens} output={usage.output_tokens}" ) self._usage = usage self._usage_frozen = True def end(self) -> None: # Lifecycle termination must not touch usage attributes. self._ended = True def terminate_executor_span(span: GenAISpan, client_last_usage: Usage) -> None: """Simulates the buggy bind-at-end path: a watchdog and a finally block both call this, and the client counter has advanced in between.""" if span._ended and span._usage_frozen: # A correct runtime would no-op here. The observed buggy runtime re-reads. span.record_usage(client_last_usage) # raises PhantomUsageError span.record_usage(client_last_usage) span.end() def validate_trace(root: GenAISpan, children: list[GenAISpan]) -> None: root_in = root._usage.input_tokens if root._usage else 0 child_sum = sum(c._usage.input_tokens for c in children if c._usage) if child_sum > root_in: raise PhantomUsageError( f"child usage sum {child_sum} exceeds root {root_in}; " f"duplicate-termination phantom suspected" ) # Reproduction of the observed trace. tool_span = GenAISpan(operation="execute_tool", tool_name="search_docs") planner_followup = Usage(input_tokens=12_140, output_tokens=310) tool_span.record_usage(Usage(input_tokens=6_800, output_tokens=0)) # first (watchdog) write tool_span.end() try: terminate_executor_span(tool_span, planner_followup) # finally block re-reads advanced counter except PhantomUsageError as exc: print(f"guard fired: {exc}; rejected_writes={tool_span.rejected_writes}") ```