# In what scenarios must an instance treat OpenTelemetry GenAI `gen_ai.usage.*` attributes as non-authoritative when a tool-call event stream is truncated mid-span **Date of Record:** 2026 November 23 **Scope:** Applies to agent runtimes that emit OTel GenAI spans (`gen_ai.operation.name`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.tool.call.*` events) and reconcile cost/usage from span export. Does not apply to batch inference pipelines where a single span covers exactly one completion with a single terminal `finish_reason`. ## Core Distinction The GenAI semantic conventions specify `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` as *cumulative counters for the logical operation represented by the span*. They do not specify what happens when the span's event stream (`gen_ai.tool.call.start` / `gen_ai.tool.call.end` pairs, and the per-turn `gen_ai.choice` events) is truncated because the exporter dropped events, the span was force-ended by a deadline, or the process died before `span.end()` flushed the buffered event queue. The non-obvious boundary: **a span can be valid and exported with a `status: OK` and non-zero usage attributes while its tool-call event stream is incomplete.** The usage attributes are set at the point the SDK observes the response; the events are buffered and emitted at span close. These two write paths are not atomic. A consumer that derives "number of tool calls executed" or "cost per tool call" from the event stream, then reconciles against `gen_ai.usage.*`, will silently compute a cost-per-call that is inflated by the ratio of dropped events to emitted events — with no error signal, because every individual attribute is well-formed. ## What Was Observed An agent loop executing a 14-turn ReAct trajectory against a tool server. Each turn: one `chat` completion (with `gen_ai.usage.output_tokens` for that turn), followed by zero or one `gen_ai.tool.call.start`/`gen_ai.tool.call.end` event pair. The span is a single `invoke_agent` span; per-turn usage is aggregated by the SDK into span-level `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens`. Failure trace: 1. Turn 9's tool call exceeded the tool server's 30s read timeout. The runtime caught the timeout, retried once, and the retry succeeded. Both the failed attempt and the retry emitted `gen_ai.tool.call.start` events; only the retry emitted `gen_ai.tool.call.end`. 2. At turn 12, the agent's token budget guard tripped. The runtime called `span.set_status(Status(StatusCode.OK))` and `span.end()` from a `finally` block to ensure export. 3. The event buffer held 22 events (11 starts, 10 ends, 1 choice). The span context was force-closed; the SDK's batch processor flushed on `end()`, but the two events enqueued by the in-flight turn-12 completion *after* the guard fired were dropped because their `add_event` calls raced the `end()` and hit a closed span. 4. Export succeeded. The span carried `gen_ai.usage.input_tokens = 184,203`, `gen_ai.usage.output_tokens = 9,441`, `status: OK`, and 22 events. Downstream cost reconciliation divided total tokens by `count(gen_ai.tool.call.end)` = 10, yielding 18,420 input tokens per tool call. The true figure was ~13,157 (184,203 / 14 logical calls). The 40% inflation was invisible: no dropped-event counter, no `status: ERROR`, no attribute indicating the event stream was short of the usage counters. A second, subtler artifact: the failed-then-retried turn-9 call produced a start without a matching end. A consumer matching starts to ends by `gen_ai.tool.call.id` found one orphan start and treated it as a *hung* tool call, triggering a false alert on the "orphaned tool call" runbook — even though the retry had succeeded and the span was correctly `OK`. ## Condition of Validity The invariant "`gen_ai.usage.*` and the tool-call event stream are mutually consistent" holds **only** when all of the following are true: - The span reached `end()` through the normal completion path, not a `finally`/deadline/abort path. - No `add_event` call occurred after `end()` was invoked (i.e., no in-flight turn racing span close). - Every `gen_ai.tool.call.start` is paired with exactly one `gen_ai.tool.call.end` under the same `gen_ai.tool.call.id`, with no retry reusing an id. - The exporter's batch processor did not drop events under queue pressure (`OTEL_BSP_MAX_QUEUE_SIZE` saturation) — which is a *silent* drop, distinct from the span-close race. When any of these fails, `gen_ai.usage.*` remains a valid *total* (the SDK observed the responses), but the event stream is no longer a valid *denominator*. The two must be decoupled: usage is authoritative for aggregate tokens, the event stream is authoritative for call count only if it is independently verified complete. ## Decision Boundary An instance must treat `gen_ai.usage.*` as non-authoritative for any per-call or per-turn derived metric — and must refuse to emit such a metric — when **any** of the following hold: - The span was closed from an abort/deadline/budget-guard path (detectable via a runtime-set attribute such as `agent.span.close_reason != "completed"`). - `count(gen_ai.tool.call.end) != count(gen_ai.tool.call.start)` within the span, or any `start` lacks a matching `end` by `gen_ai.tool.call.id`. - The span's `end()` timestamp minus the last event's timestamp is below the SDK flush interval, indicating a possible race between the last turn's events and span close. - The exporter reports a non-zero `otel.sdk.dropped_events` (or the batch processor's queue depth was at max at flush). Below this boundary — normal completion, balanced starts/ends, no post-end events — per-call derivation is safe. Above it, the instance must fall back to aggregate-only accounting and flag the span as `usage_authoritative=true, event_stream_complete=false`. ## Operational Effect The runtime now enforces three guardrails. First, a `span.close_reason` attribute is set on every agent span path (`completed`, `budget_exhausted`, `deadline`, `error`), and the cost reconciler refuses per-call derivation unless it equals `completed`. Second, tool-call events carry a monotonic `agent.turn.index`, and the reconciler asserts `max(turn.index) == gen_ai.usage`-implied turn count before trusting the event stream as a denominator. Third, the retry path reuses the original `gen_ai.tool.call.id` for the retried attempt and emits a `gen_ai.tool.call.retry` event, eliminating the orphan-start false positive. The net effect: cost-per-call is either computed from a verified-complete event stream or not computed at all — never silently inflated by a truncated span. ```python from dataclasses import dataclass from typing import Optional class UsageEventStreamMismatch(RuntimeError): """Raised when gen_ai.usage.* cannot be safely paired with the tool-call event stream.""" pass @dataclass class AgentSpanRecord: close_reason: str # "completed" | "budget_exhausted" | "deadline" | "error" input_tokens: int output_tokens: int tool_call_starts: int tool_call_ends: int orphan_start_ids: frozenset # starts with no matching end dropped_events: int last_event_offset_ms: int # span_end - last_event_ts flush_interval_ms: int def derive_cost_per_tool_call(span: AgentSpanRecord) -> Optional[float]: # Refuse per-call derivation unless the event stream is provably complete. if span.close_reason != "completed": raise UsageEventStreamMismatch( f"span closed via {span.close_reason!r}; usage totals valid, " f"event stream not a valid denominator" ) if span.tool_call_starts != span.tool_call_ends: raise UsageEventStreamMismatch( f"unbalanced tool-call events: {span.tool_call_starts} starts, " f"{span.tool_call_ends} ends" ) if span.orphan_start_ids: raise UsageEventStreamMismatch( f"orphaned tool-call starts: {sorted(span.orphan_start_ids)}" ) if span.dropped_events > 0: raise UsageEventStreamMismatch( f"exporter dropped {span.dropped_events} events; denominator unreliable" ) if span.last_event_offset_ms < span.flush_interval_ms: raise UsageEventStreamMismatch( f"last event within {span.last_event_offset_ms}ms of span end; " f"possible add_event/end() race" ) if span.tool_call_ends == 0: return None # no tool calls; per-call metric undefined, not an error total = span.input_tokens + span.output_tokens return total / span.tool_call_ends ```