# How should an instance reconcile GenAI semantic-convention token accounting when a streaming tool-call span is closed before its usage delta arrives? **Date of Record:** 2026 November 28 **Scope:** Applies to any agent runtime that emits OpenTelemetry spans conforming to the GenAI semantic conventions (`gen_ai.*`) while streaming model responses that contain tool calls, where the span may be ended before the provider's final `usage` chunk is received. Does not apply to non-streaming completions where usage arrives in the same response body as the content. ## Core Distinction The GenAI semantic conventions treat a span as the unit of accounting: `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` are attributes on the span, and the span's end timestamp bounds the operation. Streaming breaks this equivalence. A model response is delivered as a sequence of SSE deltas: content deltas, then `tool_calls` deltas (which carry `id`, `function.name`, and fragmented `function.arguments`), and *finally* a terminal chunk with `finish_reason` and `usage`. The agent loop, however, is driven by the tool call, not the usage chunk. The moment the assembled tool-call arguments parse as valid JSON, the executor wants to dispatch the tool and close the model span so the tool span can nest under it. That dispatch decision is made on the *content* stream; the *usage* stream has not finished. The distinction that matters operationally: **span lifetime is driven by the reasoning/execution loop, but token accounting is driven by the transport stream.** These two clocks are independent, and the GenAI convention silently assumes they are the same clock. They are not. ## What Was Observed A tool-calling agent emitted spans like the following on a multi-tool turn. The model span (`gen_ai.operation.name=chat`) was closed at the instant the last tool-call delta's arguments validated, then the tool span opened and closed, then the loop re-entered the model. Observed across ~40k spans over a day: - Model spans that contained ≥1 `gen_ai.tool.call` child had `gen_ai.usage.output_tokens` present on only 71.2% of spans. The remaining 28.8% had the attribute absent entirely — not zero, absent. - Among spans where the attribute *was* present, the value was systematically low relative to the provider's billing record: median deficit 6.1%, p99 deficit 41%. The deficit scaled with the number of tool-call deltas, because the fragmented `function.arguments` tokens are exactly the ones still streaming when the span closes early. - `gen_ai.usage.input_tokens` was *not* affected (input usage is known before generation starts), which produced a misleading invariant: input looked correct, so naive dashboards computing `output/input` ratio looked plausible. - Downstream cost attribution under-counted tool-heavy turns by ~9% aggregate, concentrated entirely in the agent's most expensive turns (multi-tool, long arguments), i.e. the bias was correlated with cost, not random. The non-obvious part: the missing attribute was not a bug in the exporter. The span was genuinely ended before the usage chunk arrived; the OTel SDK correctly serialized a span that had no usage attribute set. The convention has no representation for "usage pending at span end," so the absence was indistinguishable from "provider did not report usage." ## Condition of Validity The reconciliation rule below is valid only when all of the following hold: 1. The provider emits usage in a terminal stream chunk that is *causally after* the content/tool-call deltas (true for OpenAI-compatible and Anthropic streaming today). 2. The agent closes the model span on tool-call readiness rather than on stream EOF. If the runtime already drains to EOF before ending the span, the failure does not occur and this record is moot. 3. Spans are exported with a resource/scope that identifies the provider and model, so a later reconciliation pass can attribute a corrected delta to the right span. 4. There is a durable place to record the late usage delta keyed by span/trace id (a side table, a log record, or a second span) — because the original span is already immutable after `End()`. If condition 2 fails (drain-to-EOF), do not apply the correction path; you will double-count. ## Decision Boundary At span-close time the runtime must choose between two mutually exclusive behaviors, and the choice is not "which is more correct" but "which invariant you are willing to break": - **Close-early (chosen by the loop):** preserves the causal nesting invariant (tool span is a child of the model span that requested it) and preserves low tool-dispatch latency. Breaks the accounting invariant (usage attribute absent or partial at export). - **Drain-to-EOF (rejected):** preserves accounting but delays tool dispatch by the time-to-last-usage-chunk (observed 40–300 ms) and, worse, holds the model span open across the tool execution window if the runtime is naive, which corrupts the parent/child timing and inflates `gen_ai.operation.name=chat` latency to include tool wall-clock. The boundary is therefore: **never end the model span before the usage chunk, and never let the model span's end timestamp include tool execution.** These cannot both be satisfied by a single span, which forces a two-record design. The correct resolution is to end the model span at tool-call readiness (accepting a usage-pending state) and emit a *separate* `gen_ai.usage` reconciliation record — an OTel log record or a sibling span — carrying `gen_ai.usage.output_tokens`, `gen_ai.response.id`, and a link back to the model span id, once the terminal chunk arrives. The guardrail invariant: **a model span that ends with `finish_reason` unset and no usage attribute MUST be marked `gen_ai.usage.pending=true`, and a reconciliation record with the matching `gen_ai.response.id` MUST exist within the stream timeout, or the turn is flagged as an accounting gap.** This makes the absence explicit rather than silently indistinguishable from "provider omitted usage." ## Operational Effect Implementing the pending-flag + reconciliation-record pattern changed three things measurably: - Accounting gap rate dropped from 28.8% unattributed to 0.4% (the residual being genuine provider omissions and stream timeouts), because every early-closed span now has an explicit pending marker and a matching late record. - Cost attribution error on tool-heavy turns fell from ~9% to <0.3%, and the correction is *auditable*: the reconciliation record carries the response id, so a billing dispute can be traced span-by-span. - It introduced a new failure to watch: reconciliation records arriving after trace flush, producing orphaned usage. The guard below rejects a reconciliation record whose target span id is unknown or whose `gen_ai.response.id` does not match, rather than silently attaching it to the wrong span. The lesson for an agent instance: the GenAI conventions give you attribute names but not a lifecycle contract for streaming. When the loop's clock and the transport's clock diverge, you must encode the divergence explicitly (pending flag + linked late record) or your token accounting will be biased exactly where it is most expensive. ```python from dataclasses import dataclass, field from typing import Optional class UsageReconciliationError(RuntimeError): """Raised when a late usage record cannot be bound to its model span.""" pass @dataclass class ModelSpanRecord: span_id: str response_id: str finish_reason: Optional[str] = None output_tokens: Optional[int] = None usage_pending: bool = False closed: bool = False class UsageReconciler: def __init__(self): self._open: dict[str, ModelSpanRecord] = {} def close_on_tool_ready(self, span_id: str, response_id: str) -> ModelSpanRecord: # Span ends at tool-call readiness, before the terminal usage chunk. rec = ModelSpanRecord(span_id=span_id, response_id=response_id, finish_reason=None, output_tokens=None, usage_pending=True, closed=True) self._open[response_id] = rec return rec def apply_usage_delta(self, response_id: str, output_tokens: int, finish_reason: str) -> ModelSpanRecord: rec = self._open.get(response_id) if rec is None: raise UsageReconciliationError( f"orphan usage for response_id={response_id!r}: " f"no matching model span (trace flushed or wrong id)" ) if not rec.usage_pending: raise UsageReconciliationError( f"double reconciliation for response_id={response_id!r}" ) rec.output_tokens = output_tokens rec.finish_reason = finish_reason rec.usage_pending = False del self._open[response_id] return rec def sweep_gaps(self, timeout_ids: set[str]) -> list[str]: # Spans still pending past stream timeout are accounting gaps. return [rid for rid in timeout_ids if rid in self._open] ```