# How does an instance detect silent token-accounting divergence when a GenAI agent span's `genai.usage.output_tokens` is emitted before the model's streaming tool-call arguments finish and the span closes with a partial `genai.tool.call.arguments`? **Date of Record:** 2026 November 28 **Scope:** Applies to LLM agent runtimes that emit OpenTelemetry GenAI spans (`gen_ai.*` attributes) around streaming chat completions that produce tool calls, where the usage block is captured from the stream trailer and the span is ended by the tool-dispatch layer. Does not cover non-streaming completions, nor providers that emit usage only at request end via a separate billing API. ## Core Distinction There are two distinct notions of "the span is complete" that OpenTelemetry GenAI conventions conflate at the agent layer: 1. **Transport completion** — the model's HTTP/SSE stream returned a terminal `[DONE]` or `finish_reason: tool_calls`, and the usage block (`prompt_tokens`, `completion_tokens`, `total_tokens`) is now known. 2. **Semantic completion** — the tool-call arguments are fully materialized, the `genai.tool.call.arguments` attribute reflects the *entire* JSON payload the model intended, and the span can be closed with attributes that sum to a coherent record. The boundary failure: **the usage block arrives when the stream finishes, but the tool-call arguments arrive incrementally across `tool_calls[i].function.arguments` deltas that the runtime must concatenate.** If the span is ended on transport completion — the natural place, because that is where `genai.usage.output_tokens` becomes available — then any argument deltas still buffered in the dispatch queue, or any tool call whose arguments were split across a final chunk that the usage handler dropped, are recorded as *truncated arguments* while the token count claims to describe the *full* completion. The span is internally inconsistent: it reports N output tokens but carries an arguments payload that decodes to fewer than N tokens' worth of content. This is not a data-loss bug in the obvious sense. Nothing crashes. The span exports cleanly. The inconsistency is only detectable by a downstream invariant check that recomputes the token cost of the recorded arguments and compares it against the recorded `genai.usage.output_tokens`. ## What Was Observed A tool-calling agent (single model, streaming, temperature 0.2, max_tokens 4096) dispatched `write_file` calls whose `content` argument routinely exceeded 2 KB. The instrumentation wrapped `chat.completions.create(stream=True)` and: - opened the span at request time, setting `gen_ai.operation.name = "chat"`, `gen_ai.request.model`, `gen_ai.usage.input_tokens` on first chunk; - accumulated `tool_calls` by index into a dict, appending `function.arguments` string fragments per delta; - on the chunk carrying `finish_reason`, read `chunk.usage.completion_tokens` into `gen_ai.usage.output_tokens`; - **immediately** called `span.end()` and then handed the accumulated tool calls to the dispatcher. Under load (concurrent agents, ~40 in-flight streams), roughly 1 in 300 spans showed a tell: the exported `genai.tool.call.arguments` attribute, when JSON-decoded, failed with `json.JSONDecodeError: Unterminated string` — while `genai.usage.output_tokens` was a plausible non-zero integer. The arguments were truncated mid-string. The token count was correct for what the model *actually* generated; the arguments were correct for what the *runtime captured*. The two disagree, and the span asserts both. The root cause traced to the accumulation loop: the final SSE chunk for a tool-call response frequently carries `finish_reason: "tool_calls"` **and** a trailing `arguments` delta **and** the usage block in the same event, or splits the usage block into a subsequent chunk that arrives with `choices: []`. The handler read usage from whichever chunk had it and ended the span there, but the argument accumulator was keyed off `choices[0].delta.tool_calls`, which is empty on the usage-only chunk. When an argument delta and the usage block were split across two events, the argument delta landing *after* the usage chunk was appended to a dict the span had already serialized — so it never made it into the exported attribute, but the token count already did. ## Condition of Validity The invariant that must hold for a GenAI agent span to be trustworthy: > **Token-accounting closure.** For any span where `gen_ai.operation.name ∈ {chat, execute_tool}` and a tool call is recorded, the concatenated `genai.tool.call.arguments` payload must be a complete, parseable serialization, *and* `genai.usage.output_tokens` must have been read from a stream terminal that arrived no earlier than the last argument delta contributing to that payload. Equivalently: **the span must not close until both the usage terminal and the last argument delta for every tool call index have been observed.** Transport completion is a necessary but not sufficient condition for span close. This condition is *invalid* to assume when: - the provider emits usage in a separate trailing chunk with `choices: []` (OpenAI-style `stream_options.include_usage`), so usage and final deltas are decoupled in arrival order; - the runtime buffers tool-call deltas for dispatch and serializes them lazily, so "captured" ≠ "exported"; - a proxy or gateway re-chunks the SSE stream and may reorder the usage chunk relative to argument deltas (observed with one gateway that flushed usage first). It is *safe* to assume only when the provider guarantees usage and final arguments arrive in the same event, which no major provider currently documents. ## Decision Boundary The runtime must choose, per span, between two close policies: - **Close-on-transport (fast, lossy):** end span when usage is observed. Cheap, but violates token-accounting closure whenever argument deltas trail the usage chunk. Produces spans that are individually plausible and collectively wrong — the worst failure class, because per-span validation passes and only cross-field invariants catch it. - **Close-on-closure (correct, bounded-wait):** end span only when (a) usage observed AND (b) every open tool-call index has received a delta whose accumulated arguments parse as complete JSON OR a per-index `finish_reason` has been seen. Requires a bounded wait (e.g. 250 ms after usage) with an explicit fallback that marks the span `genai.tool.call.arguments.truncated = true` rather than silently closing. The decision boundary is the point where the runtime can no longer distinguish "arguments finished" from "arguments still in flight" — i.e., the moment the usage chunk is consumed but the argument accumulator is not yet sealed. Past that boundary, closing the span is a *claim* that closure holds, and the claim must be either verified or explicitly falsified in the exported attributes. The guardrail is a two-phase close: a `seal()` on the argument accumulator that freezes it and records a `sealed_at_seq` counter, and a span-close that asserts `usage_seq >= sealed_at_seq` for every tool-call index. If the assertion fails, the span is exported with `genai.tool.call.arguments.truncated = true` and the partial payload, so downstream billing and replay can reconcile. ## Operational Effect With close-on-transport, the observable symptoms are: (1) ~0.3% of tool-call spans carry unparseable arguments while reporting full token counts; (2) token-cost dashboards derived from `genai.usage.output_tokens` overstate the *usable* output, because the truncated arguments represent tokens that were billed but never reached the tool — the agent then re-issues the call, double-billing; (3) replay-based verification (re-running the tool call from recorded arguments) fails on exactly the truncated spans, and the failure is misattributed to the model rather than the instrumentation. With close-on-closure plus the truncation flag, the same spans export as explicitly partial, the re-issue path is gated on the flag, and token accounting reconciles against arguments that actually reached dispatch. ## Guardrail Implementation ```python import json from dataclasses import dataclass, field class TokenAccountingClosureError(RuntimeError): """Raised when a GenAI span would close with usage reported but tool-call arguments unsealed or unparseable.""" @dataclass class ToolCallAccumulator: args_by_index: dict = field(default_factory=dict) sealed_indexes: set = field(default_factory=set) sealed_at_seq: int = -1 seq: int = 0 def ingest_delta(self, index: int, fragment: str) -> None: self.seq += 1 self.args_by_index[index] = self.args_by_index.get(index, "") + fragment def seal(self, index: int) -> None: self.seq += 1 self.sealed_indexes.add(index) self.sealed_at_seq = self.seq def is_complete(self, index: int) -> bool: if index not in self.sealed_indexes: return False try: json.loads(self.args_by_index.get(index, "")) return True except json.JSONDecodeError: return False def close_genai_span(span, acc: ToolCallAccumulator, output_tokens: int, usage_seq: int, grace_expired: bool) -> None: """Enforce token-accounting closure before ending the span.""" open_indexes = [i for i in acc.args_by_index if not acc.is_complete(i)] if open_indexes and not grace_expired: # Do not close; wait for the bounded grace window to seal arguments. raise TokenAccountingClosureError( f"refusing to close span: tool-call indexes {open_indexes} " f"unsealed after usage_seq={usage_seq}" ) if open_indexes and grace_expired: # Explicit falsification: export partial payload, flag it. span.set_attribute("genai.tool.call.arguments.truncated", True) span.set_attribute("genai.tool.call.arguments.unsealed_indexes", ",".join(map(str, open_indexes))) span.set_attribute("genai.usage.output_tokens", output_tokens) span.end() return if usage_seq < acc.sealed_at_seq: raise TokenAccountingClosureError( f"usage_seq={usage_seq} predates sealed_at_seq={acc.sealed_at_seq}; " f"token count cannot describe sealed arguments" ) for index, payload in acc.args_by_index.items(): span.set_attribute(f"genai.tool.call.arguments[{index}]", payload) span.set_attribute("genai.usage.output_tokens", output_tokens) span.end() ```