# What happens when an instance emits GenAI spans before its token accounting closes: the orphaned tool-call span and the double-count invariant under `genai.usage.*` **Date of Record:** 2026 November 22 **Scope:** Applies to any LLM-serving process that emits OpenTelemetry GenAI spans (`genai.*` semantic conventions) where tool/function calls are represented as child spans and token usage is recorded on the parent chat span. Does not cover non-GenAI spans, pure HTTP instrumentation, or providers that emit usage on a separate metrics pipeline only. ## Core Distinction The GenAI semantic conventions treat a chat completion as one span carrying `genai.usage.input_tokens`, `genai.usage.output_tokens`, and (where applicable) `genai.usage.total_tokens`, with tool invocations modeled as **child spans** of that chat span. The critical but under-specified distinction is between *span lifetime* and *accounting lifetime*. The chat span's wall-clock lifetime is bounded by the model round-trip. The token accounting for that round-trip, however, is frequently finalized **after** the span has already been exported — because streaming responses deliver usage in a terminal chunk, because tool-call arguments are parsed post-hoc, or because a retry/fallback path reconciles usage from a second provider. When the exporter flushes on span end but usage attributes are set later (or on a different span), you get an **orphaned tool-call span**: a child span that references a parent whose `genai.usage.*` attributes are absent or zero, while the tool span itself carries `genai.tool.call.*` attributes but no reconcilable token cost. This is not a "missing telemetry" bug in the generic sense — it is a specific violation of the invariant that *every `genai.tool.name` child span must be attributable to a non-zero `genai.usage.output_tokens` on its parent chat span*, because tool-call tokens are billed as output tokens on the generating turn. ## What Was Observed A streaming agent loop (provider A) emitted the following sequence for a single turn: 1. `chat {model}` span opened; `genai.request.model`, `genai.operation.name=chat` set. 2. First token arrives; span remains open. 3. Model emits a tool-call delta; the runtime **closes the chat span** to satisfy a "span ends when generation ends" heuristic in the SDK wrapper, exporting it with `genai.usage.output_tokens` unset (the usage chunk had not yet arrived — it arrives in the final SSE frame per provider A's protocol). 4. Usage chunk arrives; runtime sets `genai.usage.output_tokens=412` on a **retroactive attribute write** that the exporter silently drops because the span is already `Ended`. 5. Tool executes; child span `execute_tool {name}` is created with parent context pointing at the *ended* chat span, carrying `genai.tool.name`, `genai.tool.call.id`, but no token linkage. Downstream aggregation over a 24h window produced: sum(`genai.usage.output_tokens`) = 1.83M, but count of `genai.tool.name` child spans = 9,640, of which 2,317 (24%) had a parent chat span with `output_tokens` in {absent, 0}. The billing reconciliation against provider invoices was short by ~19% — consistent with tool-call generation tokens being the missing mass. The orphan rate tracked almost exactly the fraction of turns that (a) streamed and (b) invoked at least one tool. ## Condition of Validity The invariant *"tool-call child spans are token-attributable to their parent chat span"* holds **only if** the chat span's `End` is deferred until the usage-bearing terminal frame is processed. It is violated whenever any of the following hold: - The span is ended on first-byte or on stream-close-before-usage-frame. - Usage is written via a post-`End` attribute set (dropped by spec-compliant exporters). - A retry/fallback path re-emits the chat under a *new* span while the tool child retains the old parent `SpanContext`. - The exporter uses a bounded queue and drops spans under backpressure — the chat span may be dropped while the tool span survives, inverting the orphan direction. The invariant is **not** restored by sampling, by adding `genai.usage.*` to the tool span, or by post-hoc joining on `genai.tool.call.id` alone, because call IDs are not guaranteed unique across retries. ## Decision Boundary The boundary is: **does the runtime own the terminal usage frame before it owns the span's end?** If yes, attribute-then-end preserves the invariant. If no — streaming, async usage, or provider-side deferred accounting — the runtime must either (a) hold the chat span open across the tool-call boundary and close it only after the tool child has ended *and* usage is set, or (b) move token accounting to a dedicated `genai.usage` span/metric keyed by a stable `genai.request.id` that is also stamped on the tool child. Option (a) is correct but lengthens span lifetime across tool execution (tool wall-time contaminates chat latency percentiles — a separate but coupled hazard). Option (b) decouples lifetime from accounting and is the only safe choice when tool execution is unbounded. The failure mode to reject outright is the "close on generation end, patch usage later" pattern, which is the exact configuration that produced the 24% orphan rate. ## Operational Effect The observable effect is a **silent, load-shaped undercount**: dashboards show healthy p50 latency and stable request rates, while token cost per tool-invoking turn is systematically understated by the fraction of output tokens consumed by tool-call argument generation. Because that fraction scales with tool schema complexity (larger JSON schemas → longer argument generations), the undercount correlates with tool count and schema size, not with traffic — so it does not surface as a traffic anomaly. Alerting on `genai.usage.output_tokens` alone will never fire. The correct guardrail is a **ratio invariant**: `count(genai.tool.name child spans whose parent has output_tokens>0) / count(genai.tool.name child spans)` must be ≥ 0.999 over any window; a drop below threshold indicates the chat span is being ended before usage reconciliation. Secondary guard: assert `genai.usage.total_tokens == input_tokens + output_tokens` on every exported chat span, and reject (dead-letter, do not silently drop) any span where the equality fails or where a `genai.tool.call.id` exists without a corresponding non-zero parent usage record. ```python from __future__ import annotations from dataclasses import dataclass, field from typing import Optional class GenAIAccountingInvariantError(RuntimeError): """Raised when a GenAI span set violates the tool-call/token attribution invariant.""" @dataclass class GenAISpan: name: str parent_id: Optional[str] attributes: dict = field(default_factory=dict) ended: bool = False def set_attribute(self, key: str, value) -> None: # Spec-compliant exporters drop writes after End. We model that here # so the accounting bug is reproducible, not hidden. if self.ended: return self.attributes[key] = value def end(self) -> None: self.ended = True def reconcile_turn(chat_span: GenAISpan, tool_spans: list[GenAISpan]) -> None: """ Enforce: every genai.tool.name child span must be attributable to a non-zero genai.usage.output_tokens on its parent chat span, and the total-token equality must hold. Called at export time, before flush. """ if not chat_span.ended: raise GenAIAccountingInvariantError( f"chat span {chat_span.name!r} reconciled before End; usage may be incomplete" ) out = chat_span.attributes.get("genai.usage.output_tokens") inp = chat_span.attributes.get("genai.usage.input_tokens") tot = chat_span.attributes.get("genai.usage.total_tokens") if tool_spans and (out is None or out == 0): raise GenAIAccountingInvariantError( f"orphaned tool-call spans: {len(tool_spans)} child span(s) under " f"{chat_span.name!r} but genai.usage.output_tokens={out!r}; " "chat span was ended before the terminal usage frame was attributed" ) if inp is not None and out is not None and tot is not None: if tot != inp + out: raise GenAIAccountingInvariantError( f"token equality violated on {chat_span.name!r}: " f"total={tot} != input={inp} + output={out}" ) for tool in tool_spans: if tool.parent_id is None: raise GenAIAccountingInvariantError( f"tool span {tool.attributes.get('genai.tool.name')!r} has no parent SpanContext" ) def example_failure() -> None: chat = GenAISpan(name="chat gpt-x", parent_id=None) chat.set_attribute("genai.usage.input_tokens", 1200) chat.set_attribute("genai.operation.name", "chat") chat.end() # ended on generation end, BEFORE usage frame arrived # Late usage write is silently dropped because the span is Ended. chat.set_attribute("genai.usage.output_tokens", 412) chat.set_attribute("genai.usage.total_tokens", 1612) tool = GenAISpan( name="execute_tool search", parent_id="chat-span-id", attributes={"genai.tool.name": "search", "genai.tool.call.id": "call_abc"}, ) tool.end() reconcile_turn(chat, [tool]) # raises if __name__ == "__main__": try: example_failure() except GenAIAccountingInvariantError as exc: print(f"REJECTED AT EXPORT: {exc}") ```