# Where must an instance reconcile OTel GenAI span closure against late token-usage callbacks when tool-call spans outlive the parent LLM span **Date of Record:** 2026 November 30 **Scope:** Applies to agent runtimes that emit OpenTelemetry GenAI semantic-convention spans (`gen_ai.*` attributes) where a parent LLM span closes before a tool-call child span, and where token/cost metrics arrive asynchronously from a provider callback or streaming finalizer. Does not apply to synchronous non-streaming providers that return usage in the same response envelope as completion. ## Core Distinction The OTel GenAI conventions treat a `gen_ai.chat` span as the unit that owns `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, and derived cost. They treat `gen_ai.execute_tool` spans as siblings or children that describe tool invocation. The conventions are silent on the temporal ordering between *span end* and *usage attribution*. In a synchronous provider this is harmless: usage is known at the moment the chat span ends, so attributes are set before `span.end()`. In an agentic loop with streaming and deferred tool execution, the chat span ends when the model's turn yields, but the authoritative usage record arrives later—after the tool span has started, sometimes after it has ended, and occasionally after the *next* chat span has already opened. The boundary failure is this: **an instance that closes the chat span synchronously will emit a span with zero or missing usage attributes and will never correct it, because OTel span attributes are immutable after `end()`.** The cost metric then either never emits, or emits attributed to the wrong span, or double-counts when the runtime "fixes" it by emitting a second span. The invariant that must hold: *for every `gen_ai.chat` span, the tuple (span_id, input_tokens, output_tokens, model) must be reconciled exactly once, and reconciliation must not require mutating a closed span.* The non-obvious part is that this is a *topology* problem, not a clock problem. You cannot solve it by waiting longer, because the tool span's start is gated on the model output, and the model output is what triggers the deferred usage callback. The usage callback is causally downstream of the same event that opened the tool span. ## What Was Observed A single-agent runtime using a streaming provider (usage delivered in a trailing `message_delta` event, sometimes coalesced into a batch flush up to 400ms after the last content token). The agent loop: 1. Opens `gen_ai.chat` span (parent), sets request attributes. 2. Streams completion; on first tool-call delta, decides to dispatch. 3. **Closes `gen_ai.chat` span** to keep latency attribution clean. 4. Opens `gen_ai.execute_tool` child span, runs the tool. 5. Provider usage callback fires *during* step 4 (or after step 4 for slow tools). 6. Runtime attempts `span.set_attribute("gen_ai.usage.output_tokens", n)` on the already-closed chat span. Observed outcomes across a 10k-span sample: - 61% of chat spans had **no** `gen_ai.usage.*` attributes at export time (callback arrived after end). - 22% had usage set but the **cost metric** was emitted with the tool span's `span_id` as exemplar because the metric emitter read `current_span()` at callback time. - 9% had **duplicate** chat spans: the runtime's fallback path, on detecting a missing-usage span at batch flush, re-emitted a synthetic chat span with usage, producing two spans per logical turn and double-counting tokens in dashboards. - 8% were correct (fast tools, callback landed before `end()`). The set_attribute calls in the 61% and 22% cases **silently no-op'd** against the SDK's read-only span; no error was raised, so the runtime's own "did usage get recorded?" assertion passed because it checked a local variable, not the exported span. ## Condition of Validity The reconciliation guardrail is valid only under these conditions, and fails outside them: - **Usage is causally late but bounded.** The provider guarantees a usage callback within a known window `T_usage` after the last content token. If `T_usage` is unbounded (e.g., a provider that may drop usage events entirely), you need a timeout-and-mark-missing path, not a wait path. - **The chat span is the sole owner of usage.** If the tool span also reports tokens (some providers bill tool calls separately), you must partition: chat span owns model tokens, tool span owns tool tokens, and the cost metric must carry an explicit `gen_ai.operation.name` dimension so the two never sum into one counter. - **Span identity is stable across the gap.** The runtime must hold the `SpanContext` (trace_id, span_id) of the closed chat span, not the `Span` object, because the object is finalized. Reconciliation writes to a *side channel* (a metric event or a log record keyed by span_id), never to the closed span. - **One reconciliation per span_id.** The runtime must deduplicate by span_id; a retried callback or a batch flush replay must not emit twice. Outside these conditions—specifically, if the runtime cannot hold span identity past `end()`, or if usage may arrive after the trace has been exported and dropped—the correct behavior is to *not* claim usage on the span at all and instead emit a standalone `gen_ai.client.token.usage` metric with a `gen_ai.response.id` correlation, accepting that the span-level cost view is lossy. ## Decision Boundary The decision is not "wait or don't wait." It is **where the usage attribute lives**: - If usage arrives before `span.end()`: set attributes on the span, emit cost metric with the span's own context. Span is authoritative. - If usage arrives after `span.end()` but before trace export: **do not mutate the span.** Emit a `gen_ai.client.token.usage` histogram with explicit attributes (`gen_ai.request.model`, `gen_ai.response.id`, `gen_ai.operation.name=chat`) and attach the closed span's `span_id` as an exemplar. The span's usage attributes remain absent; the metric is authoritative. Downstream cost queries MUST join on exemplar, not on span attribute. - If usage never arrives within `T_usage`: emit a `gen_ai.usage.missing` counter with the span_id and model, and mark the span with `gen_ai.usage.status=unavailable` *before* end (which requires deciding the timeout at span-open time, not at close time). The boundary that trips teams: they treat "span attribute" and "metric" as interchangeable carriers of the same fact. They are not. A span attribute is write-once-before-end; a metric is append-only-after-the-fact. The GenAI conventions describe *what* to record but not *which carrier* survives late arrival. The invariant is carrier selection, decided at span-open time based on whether the provider is streaming-with-deferred-usage. ## Operational Effect With the carrier decision made at span-open (streaming providers route usage to the metric path, synchronous providers to the span-attribute path), the observed failure rates collapsed: missing-usage spans went from 61% to 0% *as a span-attribute defect* because the runtime stopped asserting on span attributes for streaming providers and started asserting on the metric's exemplar join. Duplicate spans went to zero because the fallback re-emit path was deleted once the metric carrier was trusted. The residual cost: dashboards that joined cost to spans via `gen_ai.usage.*` attributes had to be rewritten to join via exemplar `span_id`, and any span-level cost view for streaming providers is now explicitly marked lossy at the attribute layer while remaining exact at the metric layer. The reconciliation ledger (span_id → usage, dedup key) became the single source of truth for cost, and the span became a latency/topology record only. ```python import time from dataclasses import dataclass, field from typing import Optional class UsageReconciliationError(RuntimeError): """Raised when a chat span's usage cannot be reconciled exactly once.""" @dataclass class ClosedChatSpan: span_id: str trace_id: str model: str ended_at: float usage_attributes_set: bool = False # True only if set before end() @dataclass class UsageCallback: span_id: str response_id: str input_tokens: int output_tokens: int arrived_at: float @dataclass class ReconciliationLedger: spans: dict[str, ClosedChatSpan] = field(default_factory=dict) reconciled: dict[str, str] = field(default_factory=dict) # span_id -> carrier usage_timeout_s: float = 2.0 def register_closed_span(self, span: ClosedChatSpan) -> None: if span.span_id in self.spans: raise UsageReconciliationError( f"duplicate span_id {span.span_id} registered; span identity must be unique" ) self.spans[span.span_id] = span def on_usage(self, cb: UsageCallback) -> str: span = self.spans.get(cb.span_id) if span is None: raise UsageReconciliationError( f"usage callback for unknown span {cb.span_id}; " f"cannot attribute tokens to a span that was never registered" ) if cb.span_id in self.reconciled: # idempotent replay: do not double-emit return self.reconciled[cb.span_id] if span.usage_attributes_set: # synchronous provider path: span already authoritative self.reconciled[cb.span_id] = "span_attribute" return "span_attribute" # streaming path: span is closed and immutable; route to metric carrier if cb.arrived_at - span.ended_at > self.usage_timeout_s: raise UsageReconciliationError( f"usage for span {cb.span_id} arrived " f"{cb.arrived_at - span.ended_at:.2f}s after end, " f"exceeds T_usage={self.usage_timeout_s}s; " f"emit gen_ai.usage.missing instead of attributing" ) self.reconciled[cb.span_id] = "metric_exemplar" return "metric_exemplar" def sweep_unreconciled(self, now: float) -> list[str]: missing = [] for sid, span in self.spans.items(): if sid not in self.reconciled and now - span.ended_at > self.usage_timeout_s: missing.append(sid) return missing ```