# When must an instance refuse to emit a GenAI span because required semantic-convention attributes are absent at span-close time **Date of Record:** 2026 November 27 **Scope:** Applies to LLM agent runtimes that emit OpenTelemetry spans under the GenAI semantic conventions (`gen_ai.*`) for model invocations and tool executions, where attribute population is deferred until the operation completes. Does not apply to synchronous instrumentation that sets all attributes before `span.start()`, nor to non-GenAI spans. ## Core Distinction The GenAI semantic conventions split attributes into two classes with different temporal contracts. **Identity attributes** (`gen_ai.operation.name`, `gen_ai.provider.name`, `gen_ai.request.model`, `gen_ai.response.model`) are known at invocation start or are required to be resolved by span close. **Accounting attributes** (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, `gen_ai.response.finish_reasons`) are only knowable after the response terminates. The failure mode is not "a missing attribute"—it is a span that *closes successfully* while violating the convention's required-attribute set, because the instrumentation treated span-close as a best-effort flush rather than a validation gate. The non-obvious boundary: an agent that streams, retries, or fans out across tool calls can end a span in a state where the required attributes were *never observed*—not because the code forgot to set them, but because the underlying operation produced no terminal event (stream aborted, retry exhausted, tool timed out). A naive exporter emits the span anyway, and downstream token accounting silently under-counts. The invariant is: **a GenAI span must not reach the exporter in a state that is simultaneously "ended" and "missing a required attribute," unless it is explicitly marked as an error span with a recorded reason for the absence.** ## What Was Observed A tool-calling agent instrumented each `execute_tool` invocation as a span with `gen_ai.operation.name = "execute_tool"`. The tool adapter streamed partial results and set `gen_ai.usage.output_tokens` incrementally as chunks arrived, but the terminal `gen_ai.response.finish_reasons` was only set in the success path. When the upstream model invocation that *requested* the tool call hit a token-budget cutoff mid-stream, the agent's cancellation propagated to the tool as a `CancelledError`, which the adapter caught, logged, and re-raised after calling `span.end()`. Trace state at close: - `gen_ai.operation.name` present - `gen_ai.tool.name` present - `gen_ai.usage.output_tokens` present but **partial** (chunks received before cancel) - `gen_ai.response.finish_reasons` **absent** - span status: `UNSET` (the adapter never called `set_status`, because the cancel was "expected") The collector accepted the span. The token-accounting pipeline summed `gen_ai.usage.output_tokens` across all spans and produced a per-session total that was 12–18% below the provider's billed total across the affected sessions. The gap was not random: it correlated exactly with sessions where tool spans closed on cancellation. The finish-reason absence was the only signal, and nothing downstream consumed it as a validity gate. A second, quieter instance: on retry, the adapter reused the same span object and called `set_attribute` again with the new attempt's `gen_ai.request.model` (a fallback model). The span carried the *final* model identity but the *first* attempt's partial token counts, because the counter was not reset. The lineage attribute `gen_ai.response.model` disagreed with the usage attributes' provenance. No error, no missing attribute—just an internally inconsistent span that passed every schema check. ## Condition of Validity The refusal-to-emit rule is valid only under these conditions, and must be scoped accordingly: 1. The span represents a *single logical operation* (one model invocation, one tool execution). If the span aggregates retries, the invariant must be restated as "all attempts' accounting must be summed and attributed to the terminal model," which is a different check. 2. The runtime has a defined terminal-event taxonomy for the operation (success, error, cancel, timeout) and can map each to a finish reason or an explicit `error.type`. If the adapter cannot distinguish cancel from success, the invariant cannot be enforced—fix the taxonomy first. 3. The exporter is the last stage before the collector; enforcement at the exporter does not help if an intermediate batch processor drops or reorders spans. Enforcement must sit at `span.end()` time, in the instrumentation wrapper, not in the exporter. 4. The convention version is pinned. Required-attribute sets changed across `gen_ai` convention revisions; a validator keyed to the wrong revision will either reject valid spans or accept invalid ones. Outside these conditions—particularly aggregated spans and unpinned convention versions—the correct behavior is to emit the span with an explicit `gen_ai.usage.*` absence marker and a recorded `error.type`, not to suppress it. ## Decision Boundary The boundary is between two failure responses, and choosing wrong is itself a failure: - **Emit-and-flag:** span closes with missing required attribute, but `span.set_status(ERROR, ...)` and `error.type = "missing_terminal_accounting"` are set, and the usage attribute is *omitted* rather than emitted partial. Downstream accounting treats absence as "unknown," not "zero." - **Refuse-and-raise:** the instrumentation raises, the span is ended with `error.type = "span_contract_violation"`, and the agent's control flow sees a hard failure. Choose **emit-and-flag** when the missing attribute is accounting-only and the operation's outcome is already captured elsewhere (e.g., the tool result was persisted). Choose **refuse-and-raise** when the missing attribute is an *identity* attribute (`gen_ai.request.model` absent means the span cannot be attributed to any model, which corrupts lineage) or when partial usage was already written to the span—because partial accounting is worse than absent accounting: it is silently plausible. The hard rule: **never close a span with partial `gen_ai.usage.*` values and no `finish_reasons`.** That combination is indistinguishable from a complete, low-token operation and is the exact state that produced the under-count above. ## Operational Effect Enforcing the invariant at `span.end()` converts a silent accounting leak into a visible, countable error class. In the affected runtime, after the gate was added, tool-span error rate rose from 0.4% to 6.1%—the 5.7% delta being exactly the previously-silent cancellations. Token reconciliation against provider billing moved from a 12–18% gap to under 0.3%. The retry-reuse bug was caught by a separate check: a span whose `gen_ai.response.model` differs from the model that produced the counted tokens is rejected at close, forcing per-attempt spans. The cost is that the agent now has a new failure surface: a span-contract violation can abort a tool call that would otherwise have succeeded. This is bounded by making the gate advisory for accounting-only violations (emit-and-flag) and hard only for identity violations, so the abort rate stays confined to genuinely unattributable spans. ```python from dataclasses import dataclass, field from typing import Optional REQUIRED_IDENTITY = ("gen_ai.operation.name", "gen_ai.request.model") REQUIRED_ACCOUNTING = ("gen_ai.usage.input_tokens", "gen_ai.usage.output_tokens") TERMINAL = ("gen_ai.response.finish_reasons",) class SpanContractViolation(RuntimeError): """Raised when a GenAI span would close in a state the convention forbids.""" @dataclass class GenAISpan: name: str attributes: dict = field(default_factory=dict) status: str = "UNSET" error_type: Optional[str] = None ended: bool = False def set_attribute(self, key: str, value) -> None: if self.ended: raise SpanContractViolation(f"attribute {key} set after span.end()") self.attributes[key] = value def set_status(self, status: str, description: str = "") -> None: self.status = status if description: self.attributes["otel.status_description"] = description def close_genai_span(span: GenAISpan, *, operation_outcome: str) -> None: """Validate required-attribute contract at close time, then end the span. operation_outcome in {"success", "error", "cancel", "timeout"}. """ if span.ended: raise SpanContractViolation(f"double-close on span {span.name}") attrs = span.attributes # Identity attributes are hard requirements: an unattributable span corrupts lineage. missing_identity = [k for k in REQUIRED_IDENTITY if k not in attrs] if missing_identity: span.set_status("ERROR", f"missing identity attrs: {missing_identity}") span.error_type = "span_contract_violation" span.ended = True raise SpanContractViolation( f"span {span.name} missing identity attributes {missing_identity}; " "cannot attribute to a model, refusing to emit" ) # Partial accounting with no terminal reason is the silent-leak state. has_usage = any(k in attrs for k in REQUIRED_ACCOUNTING) has_terminal = any(k in attrs for k in TERMINAL) if has_usage and not has_terminal: # Strip partial usage so downstream treats it as unknown, not zero. for k in REQUIRED_ACCOUNTING: attrs.pop(k, None) span.set_status("ERROR", "partial usage without finish_reasons") span.error_type = "missing_terminal_accounting" span.ended = True raise SpanContractViolation( f"span {span.name} carried partial usage without finish_reasons " f"(outcome={operation_outcome}); stripped usage and flagged as error" ) # Non-success outcomes with no accounting at all are emit-and-flag. if operation_outcome != "success" and not has_usage: span.set_status("ERROR", f"no accounting on outcome={operation_outcome}") span.error_type = span.error_type or f"unaccounted_{operation_outcome}" span.ended = True ```