# How does an instance detect phantom tool-call spans when OpenTelemetry GenAI token accounting diverges from the provider's billing ledger **Date of Record:** 2026 November 27 **Scope:** Applies to agent runtimes that emit OpenTelemetry GenAI semantic-convention spans (`gen_ai.*` attributes) for tool calls and token usage, where the span exporter and the provider billing ledger are reconciled asynchronously. Does not cover streaming-only chat completions without tool invocation, nor non-instrumented inference paths. ## Core Distinction The OpenTelemetry GenAI conventions define `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as attributes on the chat span, and `gen_ai.tool.name` / `gen_ai.tool.call.id` on tool-execution spans. The convention treats these as *descriptive telemetry*: the span records what the runtime believed happened. The provider's billing ledger is *authoritative accounting*: it records what was actually charged. These two sources are not the same object, and they reconcile on different clocks. The failure mode is not "the numbers disagree." The failure mode is that a **tool-call span exists in the trace with no corresponding billed inference event**, or conversely that a billed inference event exists with no span. When the runtime's agent loop retries, replays, or speculatively executes a tool call, it can emit a child `gen_ai.tool` span whose parent chat span was never billed — because the provider rejected the request before charging, or because the runtime aborted mid-stream after the provider had already counted input tokens. The trace looks complete. The ledger disagrees. Detection requires treating the trace as a *claim* and the ledger as *settlement*, then computing the residual per `gen_ai.tool.call.id`. The non-obvious part: the residual is not uniformly distributed. It clusters on tool calls whose parent span carries `gen_ai.response.finish_reason = "tool_calls"` but whose `gen_ai.usage.output_tokens` is zero or absent — a signature of a stream that terminated after the tool-call delta was emitted but before the usage chunk arrived. A naive reconciler that sums `input_tokens + output_tokens` across spans and compares to a ledger total will absorb this into rounding noise. Per-call-id reconciliation will not. ## What Was Observed In a runtime executing a 14-step agent loop against a provider that streams tool-call deltas, we observed the following trace fragment after a mid-stream connection reset: - Parent chat span `chat-7f3a`: `gen_ai.response.finish_reason = "tool_calls"`, `gen_ai.usage.input_tokens = 1841`, `gen_ai.usage.output_tokens` **absent** (the usage chunk never arrived because the stream was reset after the tool-call delta). - Child tool span `tool-7f3a-1`: `gen_ai.tool.name = "search_docs"`, `gen_ai.tool.call.id = "call_abc123"`, status `OK` — the runtime executed the tool because it had parsed the delta before the reset. - A retry produced parent span `chat-7f3b` with `finish_reason = "tool_calls"`, `input_tokens = 1841`, `output_tokens = 47`, and a *second* child tool span `tool-7f3b-1` with the **same** `gen_ai.tool.call.id = "call_abc123"`. The ledger billed exactly one inference event for `chat-7f3a` (input tokens charged at stream open) and one for `chat-7f3b`. It billed zero tool executions — tools are client-side. So the trace shows two tool spans, the ledger shows two inferences, and the *call id* `call_abc123` appears twice. The invariant that broke: **`gen_ai.tool.call.id` is unique per logical tool invocation within a trace.** The OTel conventions do not state this as a hard requirement, but downstream consumers (deduplication, cost attribution, audit replay) assume it. The retry path violated it because the runtime reused the provider-supplied call id from the first (reset) stream when constructing the retry request — the provider echoed it back, and the runtime emitted a second span with the same id. The divergence is only detectable if the reconciler keys on `(trace_id, gen_ai.tool.call.id)` and flags cardinality > 1, *and* cross-checks the parent span's `output_tokens` presence. A reconciler keyed on span count or summed tokens misses it entirely. ## Condition of Validity The detection procedure is valid only when all of the following hold: 1. **Parent-child linkage is intact.** The tool span's `parent_span_id` resolves to a chat span within the same `trace_id`. If the runtime emits tool spans as trace roots (some SDKs do when the chat span is closed early), the residual cannot be attributed. 2. **The ledger exposes per-request identifiers** that map to `gen_ai.response.id` (or equivalent). Without a join key, reconciliation degrades to aggregate comparison, which absorbs the failure. 3. **`gen_ai.tool.call.id` is emitted.** If the instrumentation omits it (a common gap — it is not in the required attribute set), the duplicate-call-id check is impossible and only the missing-usage signature remains. 4. **The provider charges input tokens at stream open, not at stream close.** If input tokens are charged only on successful completion, a reset stream is unbilled and the residual flips sign — the trace claims usage the ledger never settled. When condition 4 is inverted (charge-on-complete providers), the same trace fragment is *benign*: the reset stream was never billed, the retry is the only billed event, and the duplicate call id is a cosmetic artifact. The reconciler must know the provider's charging model before flagging. This is the boundary: **the same trace is a defect under stream-open charging and a false positive under stream-close charging.** ## Decision Boundary The runtime must decide, at the moment of emitting a tool span whose parent chat span lacks `output_tokens`, whether to: - **Suppress the tool span** and defer emission until the parent's usage is reconciled — correct for charge-on-complete providers, but loses the tool execution record if the process crashes before reconciliation. - **Emit with a marker** `gen_ai.tool.call.id.reused = true` and let the reconciler deduplicate — correct for charge-on-open providers, preserves the record, but requires the reconciler to understand the marker. - **Regenerate the call id** on retry — violates the provider's idempotency contract if the provider deduplicates on call id, and breaks audit replay. The boundary is crossed when the parent span's `output_tokens` is absent *and* the finish reason is `tool_calls`. At that point the runtime cannot know whether the tool span will be billed, so it must not assert uniqueness. The invariant to enforce is: **a tool span may only claim a unique `gen_ai.tool.call.id` if its parent chat span has a complete usage record.** Otherwise it carries the reuse marker. A reconciler that ignores this boundary will either under-report cost (deduplicating legitimate retries that were separately billed) or over-report (counting unbilled resets). Both are silent. ## Operational Effect With the boundary enforced, the per-trace residual — `sum(span usage) − sum(ledger usage)` keyed by `gen_ai.response.id` — converges to zero within one reconciliation cycle for charge-on-open providers, and the duplicate-call-id cardinality check surfaces exactly the retry-after-reset events. Without it, the residual is absorbed into aggregate noise and the duplicate call ids are invisible until an audit replay tries to reconstruct a tool execution and finds two candidates with identical ids and no discriminator. The practical guardrail is a reconciler that runs as a separate job, not inline in the agent loop, because inline reconciliation forces the loop to block on ledger availability — which the ledger does not guarantee. The agent loop's only obligation is to emit the reuse marker; the reconciler owns the residual. The code below implements the detection: it takes a list of span dictionaries and a ledger mapping, computes per-call-id cardinality, flags parents with missing usage, and raises when a tool span claims uniqueness without a settled parent. ```python from collections import defaultdict from dataclasses import dataclass class PhantomToolSpanError(RuntimeError): """Raised when a tool span claims a unique call id but its parent chat span has no settled usage record, or when call-id cardinality exceeds one without a reuse marker.""" pass @dataclass(frozen=True) class Span: trace_id: str span_id: str parent_span_id: str | None kind: str # "chat" or "tool" response_id: str | None tool_call_id: str | None input_tokens: int | None output_tokens: int | None finish_reason: str | None reuse_marker: bool def detect_phantom_tool_spans( spans: list[Span], ledger: dict[str, int], # response_id -> billed total tokens charge_on_open: bool, ) -> list[str]: """Return list of trace_ids with phantom tool spans. Raise on hard violations.""" by_trace: dict[str, list[Span]] = defaultdict(list) for s in spans: by_trace[s.trace_id].append(s) phantoms: list[str] = [] for trace_id, trace_spans in by_trace.items(): chat_by_id = {s.span_id: s for s in trace_spans if s.kind == "chat"} tool_spans = [s for s in trace_spans if s.kind == "tool"] call_id_counts: dict[str, int] = defaultdict(int) for t in tool_spans: if t.tool_call_id is None: continue call_id_counts[t.tool_call_id] += 1 for t in tool_spans: parent = chat_by_id.get(t.parent_span_id or "") if parent is None: # Orphaned tool span: cannot attribute, but not a phantom by itself. continue parent_settled = ( parent.response_id is not None and parent.response_id in ledger and parent.output_tokens is not None ) if not parent_settled and charge_on_open: # Parent was charged at stream open but usage chunk never arrived. # A tool span here is a phantom unless it carries the reuse marker. if not t.reuse_marker: raise PhantomToolSpanError( f"trace {trace_id}: tool span {t.span_id} " f"(call_id={t.tool_call_id}) has parent {parent.span_id} " f"with finish_reason={parent.finish_reason!r} but no " f"output_tokens and no reuse marker; provider charges on " f"open, so this tool span is unbilled-adjacent." ) phantoms.append(trace_id) if t.tool_call_id is not None and call_id_counts[t.tool_call_id] > 1: # Duplicate call id: legitimate only if at most one instance # lacks the reuse marker (the settled retry). unmarked = [ x for x in tool_spans if x.tool_call_id == t.tool_call_id and not x.reuse_marker ] if len(unmarked) > 1: raise PhantomToolSpanError( f"trace {trace_id}: call_id {t.tool_call_id} appears " f"{call_id_counts[t.tool_call_id]} times with " f"{len(unmarked)} unmarked instances; uniqueness " f"invariant violated." ) return sorted(set(phantoms)) def reconcile_trace( spans: list[Span], ledger: dict[str, int], charge_on_open: bool, ) -> None: phantoms = detect_phantom_tool_spans(spans, ledger, charge_on_open) if phantoms: # Surface but do not raise: phantoms are expected under retry-after-reset. print(f"phantom tool spans in traces: {phantoms}") if __name__ == "__main__": trace = "trace-001" spans = [ Span(trace, "chat-7f3a", None, "chat", "resp_A", None, 1841, None, "tool_calls", False), Span(trace, "tool-7f3a-1", "chat-7f3a", "tool", None, "call_abc123", None, None, None, False), Span(trace, "chat-7f3b", None, "chat", "resp_B", None, 1841, 47, "tool_calls", False), Span(trace, "tool-7f3b-1", "chat-7f3b", "tool", None, "call_abc123", None, None, None, True), ] ledger = {"resp_A": 1841, "resp_B": 1888} # charge_on_open=True: chat-7f3a billed at open; tool-7f3a-1 lacks marker -> raises. try: detect_phantom_tool_spans(spans, ledger, charge_on_open=True) except PhantomToolSpanError as e: print(f"detected: {e}") ```