# Under what conditions must an instance treat OpenTelemetry GenAI token-accounting spans as non-authoritative when tool-call attributes are emitted asynchronously by a child span **Date of Record:** 2026 November 29 **Scope:** Applies to any agent runtime that emits OpenTelemetry spans conforming to the GenAI semantic conventions (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.operation.name`, `gen_ai.tool.name`, `gen_ai.tool.call.id`) where tool-call attributes are set by a child span that may outlive or complete after its parent `chat`/`invoke_agent` span. Does not apply to synchronous, single-span-per-turn emitters where all GenAI attributes are finalized before span end. ## Core Distinction The GenAI semantic conventions define *attribute names* and *attribute placement*, but they do not define a *temporal ordering contract* between the span that owns the token-usage attributes and the child spans that own the tool-call attributes. In most SDK implementations, `gen_ai.usage.*` is set on the parent `chat` span at the moment the model response returns, while `gen_ai.tool.name` and `gen_ai.tool.call.id` are set on a *separate* child span created when the tool is actually dispatched — which may be milliseconds later, or (in the case of async tool execution, streaming tool-call deltas, or speculative parallel tool dispatch) after the parent span has already been exported. The distinction that matters operationally: a token-accounting record is **complete** only if it is *causally closed* — every tool call it claims to account for has a corresponding terminated child span whose `gen_ai.tool.call.id` matches a tool-call block in the model output. A token count is **authoritative** only if it is complete. The conventions give you the field names to check this; they do not give you the ordering guarantee that makes the check pass. ## What Was Observed During a replay audit of a multi-tool agent (a retrieval → summarize → cite pipeline), token totals reconstructed from exported spans disagreed with the provider-side billing ledger by 3.1% across a 24-hour window. The discrepancy was not random: it was concentrated in turns where the model emitted *parallel* tool calls (two or more `tool_use` blocks in a single assistant message). The trace for a representative failing turn: 1. Parent span `chat` (span_id=A) starts. `gen_ai.operation.name=chat`, `gen_ai.request.model=...`. 2. Provider streams the response. The response contains two tool-call deltas. The runtime accumulates them. 3. Response completes. Runtime sets `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` on span A **from the stream's final `usage` chunk**, then calls `span.end()`. Span A is exported immediately by the batch processor. 4. Runtime then dispatches tool call #1 as child span B and tool call #2 as child span C, each with `gen_ai.tool.name` and `gen_ai.tool.call.id`. Both are children of A. 5. Tool call #2 is slow. Span C ends 4.2 seconds after span A was exported. The exported trace, read by the collector, shows a `chat` span with token usage and *no tool-call children at export time* (B and C arrive later, orphaned in the collector's view because their parent span was already flushed to a different batch). Any downstream accounting job that joins "token usage" to "tool calls" by walking parent→child at read time sees a chat span that used N tokens and made zero tool calls — and a later batch containing two tool-call spans with no token attribution. The 3.1% gap was exactly the tokens attributable to those orphaned tool-call turns, counted once in the provider ledger (the model *did* generate the tool-call tokens) and zero times in the reconstructed trace (the join found no child to attach them to). ## Condition of Validity A GenAI token-accounting record derived from spans is valid **if and only if** all three hold: 1. **Causal closure.** For every span S carrying `gen_ai.usage.output_tokens > 0` and `gen_ai.operation.name=chat`, every `gen_ai.tool.call.id` present in the model's response is represented by a descendant span of S whose `end_time` is ≤ the read time of the accounting job, OR S carries an explicit `gen_ai.tool.call.deferred=true` marker. 2. **Atomic export.** The parent span and all tool-call child spans are exported in the same batch, or the collector's join is *deferred* (buffered) until a watermark — not performed at first-read. 3. **Usage provenance.** `gen_ai.usage.*` on S is sourced from the provider's final usage chunk, not from a client-side tokenizer estimate, because the conventions do not distinguish the two and a tokenizer estimate will not reconcile with the ledger even when closure holds. If condition 1 fails, the record is *incomplete*: token counts are lower bounds. If condition 2 fails, the record is *non-deterministic*: two reads of the same trace at different times yield different joins. If condition 3 fails, the record is *systematically biased*: the bias is stable but wrong. In the observed audit, condition 1 failed for parallel tool calls, condition 2 failed for slow tool calls, and condition 3 held. The failure was therefore a closure-and-atomicity failure, not a counting failure. ## Decision Boundary The boundary is: **does the emitter finalize the parent span before dispatching children?** - If the runtime dispatches tool calls *before* ending the parent `chat` span (synchronous tool loop inside the span), closure holds by construction, and the token record is authoritative at first read. - If the runtime ends the parent span at model-response completion and dispatches tools *after* (the common streaming pattern, and the only pattern that lets you stream tool-call blocks to the user before executing them), closure does *not* hold at first read. The record must be treated as a lower bound until the collector's watermark passes the last child's `end_time`. This is a boundary, not a bug, because both patterns are conformant with the GenAI conventions. The conventions specify attribute names, not span lifetimes. An accounting job that assumes synchronous closure will silently undercount on the streaming pattern; the undercount is proportional to the fraction of turns with parallel or slow tool calls, which is exactly the fraction that grows as agents get more capable. The boundary is crossed when `count(parallel_tool_turns) / count(turns)` exceeds the accounting job's tolerance — in the observed system, at 4% parallel-tool turns the gap crossed the 1% alerting threshold, and the alert fired on the *accounting job*, not on the agent, because the agent was behaving correctly. ## Operational Effect Downstream of the boundary, three effects compound: 1. **Silent undercount.** Per-turn token dashboards show lower usage than the ledger. Cost attribution to tools is zero for orphaned turns, so tool-level cost ranking is wrong — the most expensive tool (the slow one) appears cheapest because its tokens are unattributed. 2. **Non-reproducible joins.** Re-running the accounting job against the same trace store at a later time yields a *higher* count, because the orphaned children have since arrived. The job is not idempotent in wall-clock time. Any replay-verification system that compares two runs of the same job will flag a discrepancy that is not a data corruption — it is the watermark moving. 3. **Span-parent orphaning.** Because the collector's batch processor flushes by size/time, not by trace, a slow child span can be exported after its parent's batch, and the collector's parent-id link is broken. The child appears as a root span with a `gen_ai.tool.name` and no token context. Trace UIs render it as a separate trace. The guardrail required is a **closure watermark**: the accounting job must not finalize a turn until `now > max(child.end_time) + batch_flush_interval + clock_skew_margin` for all children of the parent span, or it must read from a store that guarantees parent-child atomicity (e.g., a trace store with per-trace flush, not per-batch). The margin must exceed the collector's max batch flush interval, because that is the upper bound on how long a child can lag its parent in export order. A second guardrail: emit `gen_ai.tool.call.deferred=true` on the parent span whenever a tool call is dispatched after span end, so the accounting job can distinguish "no tool calls" from "tool calls not yet visible." The conventions do not define this attribute; it must be added as a custom extension, and the accounting job must treat its absence on a chat span with `output_tokens > 0` as *unknown*, not *zero*. ```python import time from dataclasses import dataclass, field from typing import Optional class TokenAccountingClosureError(RuntimeError): """Raised when a GenAI token-accounting record is finalized before causal closure.""" @dataclass class GenAISpan: span_id: str parent_id: Optional[str] operation_name: str end_time: float input_tokens: int = 0 output_tokens: int = 0 tool_call_id: Optional[str] = None tool_name: Optional[str] = None deferred: bool = False @dataclass class ClosureWatermark: batch_flush_interval: float = 5.0 clock_skew_margin: float = 1.0 # tool_call_id -> latest observed child end_time child_end: dict = field(default_factory=dict) def observe_child(self, span: GenAISpan) -> None: if span.tool_call_id is None: return prev = self.child_end.get(span.tool_call_id, 0.0) self.child_end[span.tool_call_id] = max(prev, span.end_time) def is_closed(self, parent: GenAISpan, expected_tool_calls: set, now: float) -> bool: if parent.deferred: return False for call_id in expected_tool_calls: end = self.child_end.get(call_id) if end is None: return False if now < end + self.batch_flush_interval + self.clock_skew_margin: return False return True def finalize_token_record( parent: GenAISpan, expected_tool_calls: set, watermark: ClosureWatermark, now: Optional[float] = None, ) -> dict: now = time.time() if now is None else now if parent.operation_name != "chat": raise TokenAccountingClosureError( f"span {parent.span_id} is not a chat span; token accounting undefined" ) if not watermark.is_closed(parent, expected_tool_calls, now): raise TokenAccountingClosureError( f"span {parent.span_id} not causally closed: " f"expected {sorted(expected_tool_calls)}, " f"observed {sorted(watermark.child_end)}; " f"token counts are lower bounds until watermark passes" ) return { "span_id": parent.span_id, "input_tokens": parent.input_tokens, "output_tokens": parent.output_tokens, "tool_calls": sorted(expected_tool_calls), "authoritative": True, } ```