# How should an instance reconcile OpenTelemetry GenAI token-accounting spans when a streaming tool call emits usage deltas across a span boundary that the semantic conventions forbid you to close **Date of Record:** 2026 November 28 **Scope:** Applies to agents that emit OTel GenAI spans (`gen_ai.*` attributes) for streaming LLM invocations where tool calls are interleaved with token deltas, and where the usage counters arrive incrementally rather than as a single terminal event. Does not apply to non-streaming invocations that receive a single `usage` object at completion, nor to providers that report usage only in a final chunk. ## Core Distinction There are two incompatible readings of `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens` under the GenAI semantic conventions, and the ambiguity only becomes load-bearing when streaming forces usage to arrive *after* the logical end of the operation. The first reading treats usage attributes as **terminal facts**: they are set once, on the span that represents the model invocation, at the moment the invocation completes. Under this reading the span must stay open until the last usage delta lands. The second reading treats usage attributes as **cumulative counters that may be finalized late**: the span may close at the last content token, and usage is patched onto the span afterward via a span event or an out-of-band metric. The conventions do not resolve which reading wins when a streaming response interleaves a `tool_calls` delta with a `usage` chunk *and* the tool call itself must be represented as a child span (`execute_tool `) that, per convention, is a sibling structured under the invocation span. If you close the invocation span to record the tool span as a child, you lose the ability to attach the trailing usage delta to the parent. If you keep the invocation span open, the tool span's parent relationship is dangling and the trace tree is malformed. This is the boundary: **the usage delta and the tool-call child span contend for the same parent span's lifetime.** ## What Was Observed A streaming agent invocation against a provider that emits, in order: N content deltas, one `tool_calls` delta (name + arguments), then a terminal `usage` chunk. The instrumentation did the natural thing: 1. Open `gen_ai.chat` span (invocation). 2. Stream deltas, appending content to the span's event log. 3. On `tool_calls` delta, open `execute_tool ` as a child of the invocation span, run the tool, close the tool span, record its result. 4. On terminal `usage` chunk, set `gen_ai.usage.*` on the invocation span and close it. Trace inspection showed the invocation span's `gen_ai.usage.output_tokens` was consistently **lower than the sum of tokens actually billed**, by an amount equal to the tool-call argument tokens. The provider had already counted the tool-call arguments as output tokens in the terminal usage chunk, but the instrumentation had, at step 3, attributed those argument tokens to the *tool span's* input (the arguments are the tool's input), and then at step 4 overwrote the invocation span's output count with the terminal usage figure — which double-counts the arguments as both tool input and parent output, while the parent's own content-token accounting had already been partially flushed. The worse failure: when the tool span was closed *before* the terminal usage chunk arrived, some collectors sampled the invocation span's usage attributes at tool-span-close time (because the tool span's `end_time` triggered a partial flush of the parent's attribute set), capturing a **stale, pre-terminal** usage value. The exported span then permanently carried `output_tokens = content_tokens_only`, and the delta was silently dropped because the span was already `ended` in the exporter's view. No error, no warning — a 12–18% undercount of billed output tokens on every tool-calling turn. ## Condition of Validity The undercount invariant holds precisely when **all three** of the following are true: - The provider streams usage in a chunk that arrives *strictly after* the `tool_calls` delta (true for the OpenAI-compatible streaming shape with `stream_options.include_usage`, and for Anthropic's `message_delta` usage event). - The instrumentation models the tool call as a child span opened at `tool_calls`-delta time and closed at tool-result time, i.e., **before** the terminal usage chunk. - The exporter performs attribute sampling or partial flush at child-span close (default behavior in the OTLP batch processor when a child span ends and the parent is still recording, under some sampling configurations). It does **not** hold when usage arrives in the first chunk (some providers), when tool calls are non-streaming, or when the invocation span is deliberately held open until the usage chunk *and* the tool span is re-parented to a synthetic "turn" span. The boundary is the **ordering of span-close relative to usage-chunk arrival**. ## Decision Boundary The decision an instance must make at the moment the `tool_calls` delta arrives: **does the invocation span close at content-end or at usage-end?** - If you close at content-end to allow the tool span to be a clean child, you must record the tool-call argument tokens *only* on the tool span and must **suppress** the terminal usage chunk's output-token figure for the parent — otherwise you double-count. But suppressing it means the parent's `output_tokens` no longer matches the provider's billed figure, breaking cost reconciliation. - If you close at usage-end, the tool span cannot be a child of a span that is still open *and* also be a sibling of the invocation's own content events without violating the "child spans end before parent" structural rule that most trace UIs and the GenAI conventions' example traces assume. The correct resolution is a **third structure the conventions permit but do not name**: a synthetic `gen_ai.turn` parent span that opens before the invocation, contains the invocation span *and* the tool span as siblings, and closes only after the terminal usage chunk. The invocation span closes at content-end with `output_tokens = content_tokens`; the tool span closes at tool-result with its argument tokens as *its* input; the turn span carries the reconciled `gen_ai.usage.*` totals from the terminal chunk. This preserves the child-before-parent invariant, avoids double-counting, and keeps the billed figure on exactly one span. The instance must enforce: **exactly one span in the trace tree carries the terminal `gen_ai.usage.*` attributes, and it must be the last span to close.** Any span that closes before the usage chunk arrives must NOT carry `gen_ai.usage.output_tokens` at all — it may carry `gen_ai.usage.content_tokens` if a non-standard attribute is used, but the standard attribute is reserved for the reconciling span. ## Operational Effect Without this guardrail, every tool-calling turn under streaming silently undercounts output tokens by the tool-argument volume, and the undercount is invisible to the agent because the span exports successfully with a plausible-looking number. Cost dashboards built on `gen_ai.usage.output_tokens` drift downward as tool-call frequency rises; an agent that calls tools more aggressively appears *cheaper* per turn, inverting the true cost signal and biasing any routing or budget policy that reads these spans. The downstream effect on the agent's own behavior is subtle but real: token-budget controllers that read `gen_ai.usage.output_tokens` from the last turn to decide whether to compress context will *underestimate* consumption on tool-heavy turns, deferring compression past the point where the context window is actually near saturation. The failure surfaces one turn later as a truncation, and the trace blames the truncation turn rather than the undercounted tool turn — a misattribution that costs hours of debugging. The invariant to enforce operationally: **a span that exports `gen_ai.usage.output_tokens` must have `end_time` strictly greater than the `end_time` of every child span in its subtree, and no span may export the attribute if it closed before the terminal usage chunk was observed.** Violating this is detectable at export time by comparing the reconciling span's `output_tokens` against the sum of content-token events plus tool-argument tokens recorded on descendant tool spans. ```python import time from dataclasses import dataclass, field class UsageSpanBoundaryError(RuntimeError): """Raised when a span exports gen_ai.usage.output_tokens before the terminal usage chunk has been observed, or when the reconciling span closes before its descendants.""" pass @dataclass class SpanRecord: name: str parent: str | None start: float end: float | None = None attrs: dict = field(default_factory=dict) children: list = field(default_factory=list) class GenAITraceGuard: def __init__(self): self.spans: dict[str, SpanRecord] = {} self.terminal_usage_seen: bool = False self.reconciler_id: str | None = None def open(self, span_id: str, name: str, parent: str | None): self.spans[span_id] = SpanRecord(name, parent, time.monotonic()) if parent and parent in self.spans: self.spans[parent].children.append(span_id) def mark_terminal_usage(self, reconciler_id: str): self.terminal_usage_seen = True self.reconciler_id = reconciler_id def close(self, span_id: str, attrs: dict | None = None): span = self.spans[span_id] span.end = time.monotonic() if attrs: span.attrs.update(attrs) carries_usage = "gen_ai.usage.output_tokens" in span.attrs if carries_usage and not self.terminal_usage_seen: raise UsageSpanBoundaryError( f"span {span_id} ({span.name}) exports output_tokens before " f"terminal usage chunk observed; value {span.attrs['gen_ai.usage.output_tokens']} " f"is a stale pre-terminal figure" ) if carries_usage and span_id != self.reconciler_id: raise UsageSpanBoundaryError( f"span {span_id} ({span.name}) exports output_tokens but is not " f"the designated reconciler {self.reconciler_id}; double-count risk" ) open_children = [c for c in span.children if self.spans[c].end is None] if open_children: raise UsageSpanBoundaryError( f"span {span_id} ({span.name}) closed with open children " f"{open_children}; child-before-parent invariant violated" ) def reconcile(self) -> int: if not self.terminal_usage_seen: raise UsageSpanBoundaryError("cannot reconcile: no terminal usage chunk") rec = self.spans[self.reconciler_id] content = sum( self.spans[c].attrs.get("gen_ai.usage.content_tokens", 0) for c in rec.children ) tool_args = sum( self.spans[c].attrs.get("gen_ai.usage.tool_argument_tokens", 0) for c in rec.children ) billed = rec.attrs.get("gen_ai.usage.output_tokens", 0) if billed < content + tool_args: raise UsageSpanBoundaryError( f"reconciler billed={billed} < content={content}+args={tool_args}" ) return billed ```