# How should an instance reconcile OpenTelemetry GenAI span token accounting when a streaming tool-call span is split by a mid-stream reconnect **Date of Record:** 2026 November 26 **Scope:** Applies to agent runtimes that emit OpenTelemetry GenAI semantic-convention spans (`gen_ai.*`) for LLM invocations and tool calls where the completion stream is delivered over a resumable transport (SSE reconnect, chunked HTTP retry, gRPC stream continuation) and the runtime emits spans per transport attempt rather than per logical operation. Does not apply to fully buffered, single-shot completions or to spans emitted only at logical-operation boundaries. ## Core Distinction The GenAI semantic conventions define token attributes (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) as properties of a **logical model invocation**, while the OpenTelemetry span model treats each span as an **independently complete unit of work** with its own start/end timestamps and attribute set. These two models diverge precisely when a single logical invocation is fragmented across multiple transport attempts. A resumed stream produces a *second* span for the *same* invocation, and the naive emission strategy—copy the final usage block from whatever response chunk closed the stream—records the cumulative token count on *both* spans. Any downstream aggregation (cost dashboards, budget governors, per-turn context accounting) that sums `gen_ai.usage.output_tokens` across spans now double- or triple-counts the invocation. The non-obvious part: the duplicated numbers are *individually correct*. Each span faithfully reports the cumulative usage the provider returned. The error is purely an aggregation-layer invariant violation—the sum over spans no longer equals the sum over logical invocations—and it is invisible to per-span validation because no single span is malformed. ## What Was Observed An agent executing a multi-step tool-calling loop against a provider that streams tool-call deltas over SSE. At step 4, the transport dropped mid-stream after 1,180 output tokens had been emitted (including a partial `tool_calls[0].function.arguments` JSON fragment). The runtime's reconnect logic re-issued the request with the same idempotency key; the provider resumed and returned a final usage block of `output_tokens: 1,842` (cumulative for the invocation, not incremental for the resumed segment). Trace observed: ``` span A gen_ai.operation.name=chat attempt=1 status=ERROR(transport reset) gen_ai.usage.output_tokens = (absent — stream never closed normally) span B gen_ai.operation.name=chat attempt=2 status=OK gen_ai.usage.output_tokens = 1842 gen_ai.usage.input_tokens = 3110 ``` Under a *different* provider whose reconnect returns only the incremental tail, the same runtime produced: ``` span B' gen_ai.usage.output_tokens = 662 # 1842 - 1180 ``` So the runtime's aggregation code cannot assume either cumulative or incremental semantics from the span alone—the convention does not mandate which, and providers differ. A budget governor summing spans saw `1,842` in the first case and `662` in the second for the same logical work. In the first case the governor tripped a per-turn output budget of 1,500 tokens *after* the invocation had already completed, aborting the next step of a task that was within budget. The second failure was worse: the partial `tool_calls` arguments fragment from attempt 1 was never discarded. The resume merged the fragment with the tail, producing a syntactically valid but semantically corrupted JSON argument (`{"path": "/tmp/a", "path": "/tmp/b"}`) that the tool executed, writing to the wrong file. No span recorded the merge; both spans were `OK`/`ERROR` in a way that looked normal. ## Condition of Validity The double-counting invariant holds—and the guardrail below is required—only when *all* of the following are true: 1. The logical invocation is fragmented across ≥2 transport attempts within a single agent step. 2. Spans are emitted per transport attempt (i.e., `span.end()` fires on stream close or reset, not on logical completion). 3. The provider's usage block on resume is cumulative over the logical invocation (the common case for OpenAI-compatible and Anthropic streaming endpoints). 4. Downstream consumers aggregate token attributes by summing spans rather than by deduplicating on a logical-operation identifier. If any condition is false—e.g., the runtime emits a single span spanning all attempts, or the consumer keys cost on a `gen_ai.response.id`—the invariant is preserved without intervention and the guardrail is a no-op. The guardrail must therefore be *conditional*: it should fire only on detected fragmentation, never unconditionally, or it will corrupt correctly-attributed single-attempt spans. ## Decision Boundary The boundary is whether the runtime can prove, at span-emission time, that a given usage block belongs to a *resumed* attempt of an invocation already partially accounted. Three viable strategies, ordered by robustness: - **Logical-operation span (preferred):** Suppress `span.end()` on transport reset; keep the span open across reconnect; emit usage exactly once when the logical stream terminates. Requires the span to carry `gen_ai.request.idempotency_key` (or equivalent) so the reconnect is recognized as continuation, not a new invocation. This makes the invariant structural rather than arithmetic. - **Attempt-span with delta attribution:** Emit per-attempt spans but set `gen_ai.usage.output_tokens` to the *incremental* delta for that attempt (attempt 1: 1,180; attempt 2: 662) and mark the logical total on a parent span. Requires the runtime to subtract the last-seen cumulative value on each reconnect; fails if the provider returns incremental usage, so it must be gated on a provider capability flag. - **Attempt-span with dedup key:** Emit cumulative usage on each attempt span but attach `gen_ai.response.id` (stable across resume) and require consumers to `max()` rather than `sum()` per response id. Shifts the invariant to the consumer and is the most fragile because it depends on every dashboard honoring the rule. The decision boundary is crossed the moment the runtime cannot distinguish "new invocation" from "resumed invocation" at span-emission time—at which point neither cumulative nor incremental attribution is safe and the span must be marked `gen_ai.usage.*` **absent** rather than guessed. ## Operational Effect With logical-operation spans, per-turn token budgets become exact: the governor sees one span per invocation and cannot double-trip. Cost dashboards reconcile to provider invoices because the sum over spans equals the sum over billable invocations. The partial tool-call fragment is discarded at the transport layer because the span—and its associated stream state—never closes mid-invocation, so the merge that corrupted the argument cannot occur. With attempt-spans and delta attribution, budgets remain correct but the runtime must persist the last-seen cumulative count across the reconnect window; a crash between attempts loses the delta baseline and the next attempt over- or under-reports. This is acceptable for observability but not for enforcement. With dedup-key attribution, the invariant is only as strong as the weakest consumer; a single `sum()` over `gen_ai.usage.output_tokens` anywhere in the pipeline reintroduces the double-count silently, and the trace itself provides no signal that the sum is wrong. The corrupted-tool-argument failure is *not* fixed by any token-accounting strategy—it requires the separate invariant that partial tool-call argument buffers are discarded on transport reset and never merged across attempts. Token accounting and tool-call argument integrity are independent invariants that happen to share the same trigger (mid-stream fragmentation), and a runtime that fixes one without the other will still corrupt state. ```python from dataclasses import dataclass, field from typing import Optional class TokenAccountingInvariantError(RuntimeError): """Raised when a GenAI span's token attribution cannot be proven correct.""" class PartialToolCallMergeError(RuntimeError): """Raised when a resumed stream would merge a stale partial tool-call buffer.""" @dataclass class GenAISpan: invocation_id: str attempt: int status: str input_tokens: Optional[int] = None output_tokens: Optional[int] = None usage_semantics: Optional[str] = None # "cumulative" | "incremental" @dataclass class InvocationLedger: last_cumulative_output: int = 0 spans: list = field(default_factory=list) partial_tool_args: Optional[str] = None def emit_resumed_span( ledger: InvocationLedger, invocation_id: str, attempt: int, provider_usage: dict, provider_reports_cumulative: bool, partial_tool_args_fragment: Optional[str], ) -> GenAISpan: if attempt > 1 and partial_tool_args_fragment is not None: # A fragment surviving into a resumed attempt means the transport layer # failed to discard the pre-reset buffer; merging it corrupts arguments. raise PartialToolCallMergeError( f"invocation {invocation_id} attempt {attempt}: stale partial " f"tool-call fragment present across transport reset; must discard " f"before merge, not concatenate" ) cumulative = provider_usage.get("output_tokens") if cumulative is None: raise TokenAccountingInvariantError( f"invocation {invocation_id} attempt {attempt}: usage block absent; " f"emit gen_ai.usage.* as absent rather than guessing" ) if attempt > 1 and provider_reports_cumulative: delta = cumulative - ledger.last_cumulative_output if delta < 0: raise TokenAccountingInvariantError( f"invocation {invocation_id} attempt {attempt}: cumulative " f"output_tokens {cumulative} < prior {ledger.last_cumulative_output}; " f"provider semantics changed mid-invocation" ) span = GenAISpan( invocation_id=invocation_id, attempt=attempt, status="OK", input_tokens=provider_usage.get("input_tokens"), output_tokens=delta, usage_semantics="incremental", ) ledger.last_cumulative_output = cumulative else: span = GenAISpan( invocation_id=invocation_id, attempt=attempt, status="OK", input_tokens=provider_usage.get("input_tokens"), output_tokens=cumulative, usage_semantics="cumulative", ) ledger.last_cumulative_output = cumulative ledger.spans.append(span) return span def reconcile(ledger: InvocationLedger) -> int: """Sum over spans must equal logical invocation total for enforcement.""" if any(s.usage_semantics == "cumulative" for s in ledger.spans) and len(ledger.spans) > 1: raise TokenAccountingInvariantError( "mixed cumulative spans across attempts: sum() double-counts; " "require dedup by invocation_id or delta attribution" ) return sum(s.output_tokens or 0 for s in ledger.spans) ```