# When must an instance refuse to emit a GenAI span: the `gen_ai.operation.name` / `gen_ai.usage.*` non-atomicity boundary in OpenTelemetry LLM invocation spans **Date of Record:** 2026 November 27 **Scope:** Applies to any agent runtime that emits OpenTelemetry GenAI semantic-convention spans for LLM invocations, tool executions, or agent-to-agent handoffs, where a single logical operation may be split across streaming deltas, retries, or child tool spans. Does not apply to pure batch offline evaluation pipelines that never emit spans. ## Core Distinction The GenAI semantic conventions define *attribute-level* contracts (`gen_ai.operation.name`, `gen_ai.request.model`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.response.finish_reasons`, `gen_ai.tool.name`, `gen_ai.agent.id`) but they do **not** define an atomicity invariant across the lifetime of the span. A span is opened, attributes are set incrementally as the model streams and as tools fire, and the span is closed. The failure mode is that **a span can be closed—and exported—in a state where its attribute set is internally contradictory or semantically incomplete, yet still structurally valid per the schema.** The collector, the backend, and any downstream auditor that replays these spans will accept the span. There is no schema-level rejection. The contradiction is only visible to a consumer that knows the invariant the producer was supposed to maintain. The non-obvious boundary: **`gen_ai.usage.output_tokens` is monotonically increasing across stream deltas, but `gen_ai.response.finish_reasons` is terminal and single-valued. A span that is closed before the terminal finish reason arrives will carry a token count that is consistent with a *completed* generation but a finish-reason attribute that is either absent or reflects an intermediate state (e.g., `tool_calls` that were never dispatched).** The span looks complete. It is not. ## What Was Observed A tool-using agent (model → `search_web` tool → model) emitted, for a single user turn, the following span sequence in a production trace: 1. Span `llm.invoke` (parent), `gen_ai.operation.name = "chat"`, `gen_ai.request.model = "claude-sonnet"`. 2. Child span `tool.search_web`, `gen_ai.operation.name = "execute_tool"`, `gen_ai.tool.name = "search_web"`. 3. The parent span closed with `gen_ai.usage.input_tokens = 1841`, `gen_ai.usage.output_tokens = 212`, `gen_ai.response.finish_reasons = ["tool_calls"]`. The trace *appears* to describe a completed tool-calling turn. But the downstream auditor that replays spans to reconstruct the conversation saw `finish_reasons = ["tool_calls"]` on the parent and **no second `llm.invoke` span continuing the turn**. The agent runtime had crashed between dispatching the tool span and issuing the follow-up model call. The tool span was exported. The parent span was exported with a *terminal-looking* finish reason. The follow-up invocation span was never created. The observable symptom in the backend: token accounting for the turn was correct (1841 + 212), the tool call was correctly attributed, and the finish reason was a legal enum value. **Every individual GenAI attribute was valid. The span set was semantically incoherent.** A replay-based verifier that checks "did every `finish_reasons = tool_calls` span have a matching subsequent `llm.invoke` child or sibling?" would have caught it. No such check exists in the semantic conventions, and the collector does not perform it. A second, subtler variant was observed under streaming: the runtime set `gen_ai.usage.output_tokens` on each delta as a running total (correct per the convention's intent for final values), but on a mid-stream connection reset it closed the span with the *last observed* running total (e.g., 87 tokens) and `finish_reasons = ["stop"]` because the SDK's default close path wrote `stop` when no explicit reason was set. The span claimed a completed generation of 87 tokens. The actual generation was truncated at 87 of an intended ~400. The token count was truthful; the finish reason was a lie manufactured by the default. ## Condition of Validity The invariant that must hold for a GenAI invocation span to be *semantically* valid (not merely schema-valid) is: > **A span with `gen_ai.operation.name = "chat"` and a terminal `gen_ai.response.finish_reasons` value must be accompanied, in the same trace, by either (a) a subsequent `chat` span that consumes the tool results, or (b) an explicit `gen_ai.response.finish_reasons = ["error"]` / absent finish reason indicating non-completion. `finish_reasons = ["tool_calls"]` is *not* terminal for the agent turn; it is a *handoff* marker.** The semantic conventions do not encode this. The convention treats `finish_reasons` as a property of a single model invocation, not of an agent turn. The boundary condition is precisely where the model invocation ends but the agent turn does not: the span must either (1) not be closed until the turn resolves, or (2) be closed with an attribute that explicitly marks it as an unresolved handoff (e.g., a custom `gen_ai.agent.turn.state = "awaiting_tool_result"`), or (3) be closed with no finish reason at all so that a consumer's "terminal" predicate fails closed. The condition of validity is therefore a **producer-side discipline**, not a schema constraint. The span is only trustworthy if the emitter guarantees that the finish reason written at close time reflects the *turn's* terminal state, not the *invocation's* last observed state. This is a continuity invariant across the span lifecycle, and it is violated by any code path that closes the span in a `finally` block without reconciling the finish reason against the turn state machine. ## Decision Boundary The decision an emitter must make at span close is: - **If the invocation ended with `tool_calls` and the tool dispatch has not yet produced a follow-up invocation:** do not write a terminal finish reason. Either leave `gen_ai.response.finish_reasons` unset (and let the consumer treat absence as non-terminal), or write a non-standard `gen_ai.agent.turn.state = "awaiting_tool_result"`. Do not write `["tool_calls"]` and then close, because a consumer cannot distinguish "tool calls dispatched and turn continues" from "tool calls dispatched and turn died." - **If the invocation was truncated by transport failure (stream reset, timeout, cancellation):** write `gen_ai.response.finish_reasons = ["error"]` or omit it. Never let the SDK default to `["stop"]`. The default is the single most common source of this failure. - **If the invocation completed normally:** write the terminal finish reason and the final token counts atomically in the same attribute-set operation, immediately before `span.end()`. The boundary is sharp: **a finish reason is a claim about turn state, not about invocation state.** Any emitter that conflates the two will produce spans that pass schema validation and fail replay verification. The cost of the wrong choice is silent: the span is exported, indexed, and counted, and only a downstream auditor that reconstructs turn topology will notice the orphaned `tool_calls`. ## Operational Effect The practical consequence is that **GenAI span sets are not self-verifying.** A trace with N `chat` spans and M `execute_tool` spans can be internally inconsistent in ways that no single span reveals. An agent that uses its own exported spans as episodic memory (a common pattern: "read my last turn's trace to resume") will read a `finish_reasons = ["tool_calls"]` span, conclude the turn is mid-flight, and attempt to resume by re-dispatching the tool—producing a duplicate tool execution against a side-effecting endpoint. This is the state-continuity failure: the trace is the memory, the memory is wrong, and the wrongness is invisible at the attribute level. The guardrail is a **replay-time invariant checker** that runs over the span set before it is trusted for resume or audit: for every `chat` span with `finish_reasons` containing `tool_calls`, assert the existence of a subsequent `chat` span in the same trace that references the tool result (via `gen_ai.tool.call.id` linkage or trace ordering). If absent, the turn is marked `incomplete` and resume is refused rather than re-dispatched. The checker is cheap (a single pass over the trace's spans) and catches the exact failure the schema cannot. ```python from dataclasses import dataclass, field from typing import Optional class IncompleteGenAITurnError(RuntimeError): """Raised when a GenAI trace claims a tool-calling turn that never resolved.""" @dataclass class GenAISpan: span_id: str operation_name: str # gen_ai.operation.name finish_reasons: Optional[list[str]] = None # gen_ai.response.finish_reasons tool_call_id: Optional[str] = None # gen_ai.tool.call.id linkage output_tokens: Optional[int] = None # gen_ai.usage.output_tokens @dataclass class TurnReplay: spans: list[GenAISpan] = field(default_factory=list) def assert_turn_resolved(self) -> None: """Enforce: every chat span with finish_reasons containing 'tool_calls' must be followed by a chat span that consumes the tool result.""" for i, span in enumerate(self.spans): if span.operation_name != "chat": continue reasons = span.finish_reasons or [] if "tool_calls" not in reasons: continue # Look forward for a chat span that carries the tool result linkage. resolved = any( later.operation_name == "chat" and later.tool_call_id is not None for later in self.spans[i + 1:] ) if not resolved: raise IncompleteGenAITurnError( f"chat span {span.span_id} closed with finish_reasons=" f"{reasons} but no follow-up chat span consumed the tool " f"result; turn is unresolved and must not be resumed or " f"re-dispatched. output_tokens={span.output_tokens} " f"describes a completed invocation, not a completed turn." ) def replay_and_verify(spans: list[GenAISpan]) -> TurnReplay: replay = TurnReplay(spans=spans) replay.assert_turn_resolved() return replay ```