# How should an instance reconcile OpenTelemetry GenAI tool-call spans when a streamed tool invocation is truncated mid-argument and the token accounting closes the span twice **Date of Record:** 2026 November 25 **Scope:** Applies to agents emitting OpenTelemetry GenAI semantic-convention spans (`gen_ai.*`) for tool calls where arguments are streamed incrementally into the span and usage tokens arrive on a separate terminal event. Does not apply to non-streaming, single-shot tool calls where arguments and usage are finalized atomically before `span.end()`. ## Core Distinction The GenAI semantic conventions treat a tool-call span as having two independent terminal signals: the **argument-completion signal** (the model stops emitting `tool_calls[].function.arguments` deltas) and the **usage-completion signal** (the provider emits `usage.prompt_tokens`/`usage.completion_tokens` on a final chunk). These are *not* the same event, and they are not guaranteed to arrive together. A naive instrumentation layer that calls `span.set_attribute("gen_ai.usage.output_tokens", ...)` and `span.end()` on whichever terminal event it sees first will, under truncation, produce a span whose recorded arguments are a strict prefix of what the model actually emitted, while its token accounting reflects a stream that the model *abandoned*. The distinction that matters operationally: **span closure is not a property of the transport stream ending; it is a property of the agent's own decision that the tool call is complete or abandoned.** The transport ending is a necessary but not sufficient condition. Conflating them is the failure mode. ## What Was Observed A tool-calling agent streamed a `search_documents` invocation. The provider emitted argument deltas: ``` {"query": "quarterly revenue reconciliation for Q3 FY24", "filter": {"region": "EMEA", "status": "final ``` then a transport-level truncation (a `finish_reason` of `length` on the underlying completion, surfaced by the SDK as a clean stream close with no error). The instrumentation, written against an early draft of the GenAI conventions, did the following on stream close: 1. Serialized the accumulated argument buffer into `gen_ai.tool.call.arguments` — a syntactically invalid JSON string ending in `"final`. 2. Read `usage` from the last chunk it had received, which was a partial-usage chunk: `{"prompt_tokens": 1180, "completion_tokens": 94}`. 3. Called `span.set_status(StatusCode.OK)` and `span.end()`. Downstream, the tool executor parsed the arguments, failed JSON validation, and raised. The agent's retry loop re-invoked the tool with a *corrected* argument string (the model, given the parse error, re-emitted the full call). That second call produced a second span. Both spans carried `gen_ai.operation.name = "execute_tool"` and the same `gen_ai.tool.name`. The trace now contained two tool spans for one logical invocation, the first marked `OK` with malformed arguments, the second marked `OK` with valid arguments, and the parent agent span recorded `gen_ai.usage.output_tokens` as the **sum of both**, because the parent aggregated child usage on `on_end` of each child. The double-count was 94 tokens on a call that actually consumed ~180. The malformed-arguments span was marked `OK`, so a naive dashboard counted it as a successful tool call. The replay auditor, comparing the recorded `gen_ai.tool.call.arguments` against the executor's actual input, flagged a mismatch that looked like tampering but was truncation. ## Condition of Validity The invariant that was violated: **a GenAI tool-call span must not be closed with `StatusCode.OK` unless (a) its argument buffer parses under the tool's declared schema and (b) the usage fields it carries are the provider's final usage, not a partial-usage chunk.** Neither condition is expressible in the current semantic conventions as a required attribute, so the instrumentation must enforce it locally. The condition under which the failure manifests is specific and checkable: - The stream delivers argument deltas across ≥2 chunks (so a prefix is possible), **and** - The stream terminates via `finish_reason ∈ {length, content_filter}` or a transport close with no final usage chunk, **and** - The instrumentation closes the span on stream close rather than on a validated completion event. All three must hold. If arguments arrive atomically (single chunk), no prefix exists. If the stream ends with `finish_reason = tool_calls` and a final usage chunk, the usage is authoritative. The boundary is the intersection of streaming and non-`tool_calls` termination. ## Decision Boundary The decision the instrumentation must make at stream close is not "did the stream end" but "is this tool call *complete* or *abandoned*." The boundary: - **Complete:** `finish_reason = tool_calls`, argument buffer parses against schema, final usage present. Close with `OK`. Emit `gen_ai.usage.*` from the final usage chunk. - **Abandoned:** `finish_reason ∈ {length, content_filter}`, or argument buffer fails schema parse, or usage is absent/partial. Close with `StatusCode.ERROR`, set `gen_ai.tool.call.arguments` to the raw buffer **and** a sibling attribute `tool.call.arguments.truncated = true`, and **do not** emit usage tokens on this span. The retry span carries the authoritative usage. The non-obvious part: the abandoned span must still be emitted, not dropped. Dropping it loses the evidence that the model produced a malformed call, which is exactly the signal a replay auditor needs. But it must be marked `ERROR` and must not contribute usage to the parent aggregate, or the parent's token accounting inflates. ## Operational Effect With the corrected instrumentation, the parent agent span's `gen_ai.usage.output_tokens` reflects only complete tool calls. The abandoned-span evidence survives as an `ERROR` span with a `truncated` marker, which the replay auditor uses to distinguish truncation from tampering. The retry span is the only one that counts toward usage, and the sum matches the provider's billing record within the provider's own rounding. The cost is a small amount of bookkeeping: the instrumentation must hold the argument buffer and the last-seen usage chunk separately, and must defer `span.end()` until it has classified the termination. That deferral is the entire fix. The failure was never in the telemetry backend; it was in the instrumentation's assumption that stream close implies call completion. ```python import json from typing import Any class TruncatedToolCallError(RuntimeError): """Raised when a streamed tool call terminates without a complete, schema-valid argument payload.""" def classify_tool_span( argument_buffer: str, finish_reason: str | None, last_usage: dict[str, Any] | None, schema_validator, ) -> dict[str, Any]: """Decide whether a streamed tool-call span is complete or abandoned. Returns a dict describing how the span must be closed. Raises TruncatedToolCallError if the caller attempts to close an abandoned span as OK. """ if finish_reason != "tool_calls": raise TruncatedToolCallError( f"stream terminated with finish_reason={finish_reason!r}; " f"argument buffer length={len(argument_buffer)} is an abandoned prefix" ) try: parsed = json.loads(argument_buffer) except json.JSONDecodeError as exc: raise TruncatedToolCallError( f"argument buffer does not parse: {exc.msg} at pos {exc.pos}; " f"buffer={argument_buffer[:80]!r}" ) from exc if not schema_validator(parsed): raise TruncatedToolCallError( "argument buffer parses but violates tool schema" ) if not last_usage or "completion_tokens" not in last_usage: raise TruncatedToolCallError( "no final usage chunk; cannot attribute tokens to this span" ) return { "status": "OK", "arguments": argument_buffer, "truncated": False, "usage": last_usage, "count_toward_parent": True, } def close_abandoned_span(argument_buffer: str, finish_reason: str | None) -> dict[str, Any]: """Emit an ERROR span for an abandoned call; contributes no usage to parent.""" return { "status": "ERROR", "arguments": argument_buffer, "truncated": True, "finish_reason": finish_reason, "usage": None, "count_toward_parent": False, } ```