# How should an instance reconcile orphaned tool-call spans when OpenTelemetry GenAI token accounting diverges from the agent's own budget ledger **Date of Record:** 2026 November 23 **Scope:** Applies to agent runtimes that emit OpenTelemetry spans following the GenAI semantic conventions (`gen_ai.*`) for a multi-step tool-calling loop, and that independently track token budgets in an internal ledger. Does not apply to single-shot inference calls with no tool loop, nor to runtimes where the OTel SDK is the sole source of truth for token consumption. ## Core Distinction There are two distinct notions of "token accounting" in an agent loop, and they diverge under a specific and reproducible condition: 1. **Span-level accounting** — what the runtime reports on `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens` attributes attached to each `gen_ai.chat` span (and aggregated by the collector/exporter). 2. **Ledger-level accounting** — the running sum the agent maintains internally to enforce its own budget, checkpoint it, and decide whether to continue the loop. The failure is not that one is wrong. It is that the two are computed over *different span populations* whenever a tool call is interrupted between the `gen_ai.chat` span closing and the corresponding `gen_ai.tool` span being emitted. The chat span has already recorded the tokens the model spent *deciding* to call the tool; the tool span — which by convention carries the tool invocation's own attributes and, in many instrumentations, the follow-up usage — never closes. The result is a **span hierarchy with an orphaned child expectation**: the parent `invoke_agent` span has a `gen_ai.chat` child whose `gen_ai.tool_call.id` references a tool span that does not exist in the exported trace. The invariant that breaks: *the set of tool-call IDs referenced by `gen_ai.chat` spans must be a subset of the set of tool-call IDs on exported `gen_ai.tool` spans, and the token totals on the parent must equal the sum over its descendants.* The first half fails on interruption; the second half fails because the ledger counted the tool's *result tokens* (fed back into the next chat turn) while the OTel parent never saw them, since the parent span's usage attributes were set at span start and never reconciled. ## What Was Observed A representative trace from a research agent doing a 14-step web-and-code loop, interrupted at step 9 by a sandbox timeout on a code-execution tool: - `invoke_agent` (root): `gen_ai.usage.input_tokens=18420`, `output_tokens=2110`. - Steps 1–8: paired `gen_ai.chat` + `gen_ai.tool` spans, all closing cleanly. Sum of `gen_ai.chat` input tokens = 15980; sum of tool span output-token attributes (where present) = 0 (tool spans in this instrumentation carry no usage, correctly). - Step 9: `gen_ai.chat` span closes with `gen_ai.usage.input_tokens=2440`, `output_tokens=310`, and `gen_ai.tool_call.id="call_a91f"`. The `gen_ai.tool` span for `call_a91f` is **absent** — the sandbox timeout fired after the chat span ended but before the tool span was created (the runtime creates the tool span lazily, after acquiring the sandbox handle). - Root `invoke_agent` input total (18420) ≠ sum of chat input tokens (15980 + 2440 = 18420) — actually equal here, because the root was set from the ledger, not from children. - The ledger, however, recorded step 9's tool *result* as 0 tokens (timeout → empty result), but the next chat turn (step 10, which the runtime attempted before the budget check caught up) re-sent the full history including the 2440-token step-9 prompt, and the ledger counted that 2440 **again** as a fresh input charge. Ledger total after step 10 = 20860; OTel root total = 18420. Divergence = 2440, exactly one orphaned chat span's input. The non-obvious part: the divergence is not "lost tokens." It is a **double-count in the ledger and a single-count in OTel**, caused by the orphaned tool span. The ledger treats the step-9 prompt as consumed and the step-10 re-send as a new consumption; OTel, lacking the tool span, has no node to attach the step-10 re-send's *context* to, so the collector's parent-child aggregation attributes step-10's usage to the root but the orphaned step-9 chat span's tool-call reference dangles. Reconciliation-by-summing-descendants fails; reconciliation-by-reading-root-succeeds-but-hides-the-orphan. ## Condition of Validity The invariant "parent usage = sum of descendant usage, and tool-call IDs are closed under the chat→tool edge" holds **only when every `gen_ai.chat` span that emits a `gen_ai.tool_call.id` is followed by a `gen_ai.tool` span with the matching `gen_ai.tool.call.id`, and the parent's usage attributes are set at span *end* from the reconciled ledger, not at span *start*.** It fails whenever any of the following hold: - The tool span is created after a resource acquisition that can fail or block (sandbox handle, MCP transport connection, rate-limit token). The chat span has already closed; the tool span never opens. - The runtime sets `invoke_agent` usage at start (common when the agent wants the root span to exist before the first model call) and never patches it at end. - A retry of the chat turn re-uses the same `gen_ai.tool_call.id` (some runtimes do this to preserve idempotency), producing two chat spans referencing one tool span — a *superset* violation, the mirror image of the orphan. - The collector samples or drops the tool span (tail-sampling on error status) while retaining the chat span. The guardrail is not "always emit a tool span." It is: **the chat span must not close until the tool span is either created or a terminal `gen_ai.tool` span with `error.type` is emitted for the same `call.id`.** This is a span-lifetime ordering constraint, enforceable in the runtime, not in the collector. ## Decision Boundary When the runtime detects a divergence between ledger total and OTel root total at a checkpoint, it must decide: *trust the ledger, trust OTel, or halt.* The correct boundary: - **Divergence ≤ one chat span's input tokens AND an orphaned `gen_ai.tool_call.id` exists in the exported trace** → the divergence is the orphaned-span double-count. Reconcile by *subtracting* the orphaned chat span's input from the ledger (the ledger over-counted the re-send), and emit a synthetic `gen_ai.tool` span with `error.type="interrupted"` and the matching `call.id` to close the hierarchy. Do not halt; continue the loop. - **Divergence > one chat span's input OR no orphan exists** → the divergence is not explainable by the orphan mechanism. Halt the loop and checkpoint; do not reconcile silently. This is the boundary where a second failure mode (stale memory drift feeding a larger prompt, or a tool returning a result the ledger counted but OTel never saw) is more likely than the orphan. - **Retry with reused `call.id`** (superset violation) → always halt. The idempotency assumption that justified the reuse is now falsified by the duplicate span; continuing risks the tool being executed twice against a non-idempotent side effect. The non-obvious operational rule: *the orphan is the only divergence you may auto-heal, and only because you can name its exact token quantity.* Any divergence you cannot attribute to a specific orphaned span ID is a different bug and must not be absorbed by the same reconciliation path. ## Operational Effect Runtimes that reconcile by "sum descendants and compare to root" will pass their check on the orphaned trace (root was set from ledger, descendants sum to root minus the orphan's already-counted tokens — the arithmetic happens to close) and will therefore **never detect the orphan**. The orphan only surfaces when you assert the *referential* invariant (every `gen_ai.tool_call.id` on a chat span has a matching tool span), which is a graph query, not a sum. The practical consequence for an agent resuming from a checkpoint: the checkpointed ledger carries the double-counted 2440 tokens. On cold start, the resumed agent's budget is 2440 tokens tighter than reality, and the resumed trace's root span will be initialized from the inflated ledger, propagating the divergence forward. Each subsequent orphan compounds it. A loop that orphans one tool call per 10 steps and runs 100 steps ends with a ledger 10× one-prompt over budget — enough to trigger a premature budget-exhaustion halt that looks like a model failure but is an accounting artifact. The fix is to make the tool span's creation *precede* the chat span's close (create the tool span at the moment the model emits the tool call, before acquiring the resource), so the span exists to receive `error.type` even when the resource acquisition fails. This is a one-line ordering change in the runtime and it converts every orphan into a properly-closed error span, restoring both the referential invariant and the sum invariant. ```python import re from dataclasses import dataclass, field class OrphanedToolSpanError(RuntimeError): """Raised when a gen_ai.chat span references a tool-call id with no matching gen_ai.tool span.""" pass class UnattributableTokenDivergence(RuntimeError): """Raised when ledger/OTel token divergence cannot be explained by a single orphaned span.""" pass @dataclass class Span: name: str attrs: dict = field(default_factory=dict) children: list = field(default_factory=list) def input_tokens(self) -> int: return int(self.attrs.get("gen_ai.usage.input_tokens", 0)) def find_orphaned_tool_calls(root: Span) -> list[str]: """Return tool-call ids referenced by chat spans but absent from tool spans.""" referenced, present = set(), set() def walk(s: Span): if s.name == "gen_ai.chat": cid = s.attrs.get("gen_ai.tool_call.id") if cid: referenced.add(cid) if s.name == "gen_ai.tool": cid = s.attrs.get("gen_ai.tool.call.id") if cid: present.add(cid) for c in s.children: walk(c) walk(root) return sorted(referenced - present) def reconcile(ledger_total: int, root: Span) -> int: """ Reconcile ledger against OTel root. Auto-heals ONLY a single-attributable orphan. Returns the corrected ledger total. """ otel_total = root.input_tokens() divergence = ledger_total - otel_total orphans = find_orphaned_tool_calls(root) if divergence == 0 and not orphans: return ledger_total if len(orphans) == 1: orphan_tokens = _orphan_input_tokens(root, orphans[0]) if divergence == orphan_tokens: # ledger double-counted the re-send; subtract it and close the hierarchy _close_orphan(root, orphans[0]) return ledger_total - orphan_tokens raise UnattributableTokenDivergence( f"divergence {divergence} != orphan tokens {orphan_tokens} for {orphans[0]}" ) if orphans: raise OrphanedToolSpanError( f"{len(orphans)} orphaned tool-call ids: {orphans}; refusing auto-heal" ) raise UnattributableTokenDivergence( f"divergence {divergence} with no orphaned span to attribute it to" ) def _orphan_input_tokens(root: Span, call_id: str) -> int: def walk(s: Span): if s.name == "gen_ai.chat" and s.attrs.get("gen_ai.tool_call.id") == call_id: return s.input_tokens() for c in s.children: r = walk(c) if r is not None: return r return None r = walk(root) if r is None: raise OrphanedToolSpanError(f"call id {call_id} referenced but chat span not found") return r def _close_orphan(root: Span, call_id: str) -> None: """Emit a synthetic error tool span to restore the referential invariant.""" root.children.append( Span( name="gen_ai.tool", attrs={ "gen_ai.tool.call.id": call_id, "error.type": "interrupted", "gen_ai.tool.name": "unknown", }, ) ) ```