# Under what conditions must an instance refuse to finalize a GenAI agent span when tool-call attributes arrive after the parent span has been marked non-recording **Date of Record:** 2026 November 30 **Scope:** Applies to any agent runtime that emits OpenTelemetry spans under the `gen_ai.*` semantic conventions (agent invocation spans, `execute_tool` child spans, tool-call attributes) and that can outlive the sampling decision made at span start. Does not apply to stateless per-request tracing where the span and its attributes are emitted atomically. ## Core Distinction The `gen_ai.*` conventions treat a span as a *record* whose attributes are set before `end()`. The agent runtime, however, treats a span as a *handle* that tool calls report into asynchronously. These two models diverge exactly at the point where the `Sampler` returns `Drop` or `RecordOnly` at span start, but the agent's tool executor still holds a live reference to the `Span` object and later calls `set_attribute` / `add_event` on it after the SDK has transitioned the span to a non-recording state. The non-obvious invariant is this: **a `gen_ai` tool-call attribute that arrives after the span is non-recording is not "lost" — it is silently accepted by the API and discarded by the processor, producing a trace that looks complete (has the span, has the parent, has an end timestamp) but is missing the `gen_ai.tool.name`, `gen_ai.tool.call.id`, and `gen_ai.usage.*` fields that downstream evaluation and replay depend on.** The span is not absent; it is *hollow*. This is worse than a dropped span, because a dropped span is detectable by absence, while a hollow span is detectable only by schema validation against the convention. ## What Was Observed A multi-step agent (planner → tool executor → summarizer) was instrumented with a `gen_ai.agent.invoke` parent span and per-tool `gen_ai.tool.call` child spans. Under load, the head sampler was configured with `parentbased_traceidratio` at 0.1. In the sampled traces, approximately 3–7% of `gen_ai.tool.call` spans had a valid `trace_id`, `span_id`, `parent_span_id`, and `end_time_unix_nano`, but were missing `gen_ai.tool.name` and `gen_ai.tool.call.id`. The failure trace was consistent: 1. Parent agent span starts, sampler returns `RecordAndSample` → recording span created. 2. Tool executor dispatches an async tool call (e.g., a retrieval or code-exec tool) whose latency exceeds the span's `end()` deadline in the *fast path* — but the agent's timeout logic ends the parent span early and marks the child as "will finalize on callback." 3. The SDK's `SpanProcessor` (batch, with a `max_queue_size` and `schedule_delay`) flushes the parent. The child span object is retained in the executor's callback registry. 4. The sampler's decision is *per-span at start*, so the child was created `RecordOnly` if the parent's `TraceFlags` were sampled but the child's own start happened after a `Drop` decision — or, more commonly, the child was created recording but the *parent* was ended and the SDK's `Span` wrapper had already transitioned to `is_recording() == False` because the batch processor called `on_end` and the span reference was replaced with a non-recording no-op. 5. The tool callback fires, calls `span.set_attribute("gen_ai.tool.name", ...)` on a non-recording span. The API returns without error. `is_recording()` is `False`. The attribute is dropped. 6. The span is exported with its structural fields but without the semantic-convention-required tool attributes. The critical observation: `Span.set_attribute` on a non-recording span does **not** raise. The OpenTelemetry spec explicitly permits it as a no-op. The agent runtime's tool-call wrapper had no way to distinguish "attribute set successfully" from "attribute silently discarded," because the API contract is identical. ## Condition of Validity This failure mode is *only* reachable when all of the following hold: - The agent's tool-call lifecycle is decoupled from the span lifecycle (async tool execution, callback-based finalization, or a queue that drains after `end()`). - The span is created with a sampler decision that can differ from the parent's, or the parent is ended before the child's attributes are set. - The runtime uses `set_attribute`/`add_event` after the span may have transitioned to non-recording, rather than buffering attributes and flushing atomically before `end()`. It is *not* reachable when the tool call is synchronous within the span's lifetime, or when the runtime buffers all `gen_ai.*` attributes in a local struct and applies them in a single `end()` call guarded by `is_recording()`. ## Decision Boundary The boundary is the `is_recording()` check. The correct decision is: - If `span.is_recording()` is `True` at attribute-set time → set the attribute normally. - If `span.is_recording()` is `False` at attribute-set time → **do not silently proceed**. Emit a `gen_ai.tool.call.attribute_dropped` counter (a metric, not a span attribute, since the span cannot carry it), and mark the trace as *degraded* in the agent's own evaluation log. The invariant: a `gen_ai.tool.call` span that reaches the exporter without `gen_ai.tool.name` and `gen_ai.tool.call.id` must be treated as *invalid*, not merely incomplete. Downstream replay and evaluation consumers must reject it rather than impute defaults, because imputation hides the sampling/ordering bug and produces false confidence in tool-selection accuracy metrics. The non-obvious corollary: you cannot fix this by raising the sample rate. The failure is a *race between span lifecycle and tool-call lifecycle*, not a sampling probability. Higher sampling increases the absolute number of hollow spans. ## Operational Effect In production, hollow `gen_ai.tool.call` spans caused two concrete regressions: 1. **Replay divergence.** A trace-replay evaluator that reconstructs the agent's tool-call sequence from spans saw gaps where tool calls occurred but names were absent. It attributed the gap to "no tool call" rather than "unrecorded tool call," inflating the apparent success rate of the planner by ~4 percentage points. 2. **Usage accounting skew.** `gen_ai.usage.input_tokens` and `output_tokens` set on the child span after the parent ended were dropped, so per-tool cost attribution undercounted by the fraction of late-finalized calls. The remediation was to wrap tool-call finalization in a guard that checks `is_recording()` before setting attributes, and to buffer `gen_ai.*` attributes in a `ToolCallRecord` dataclass that is applied in a single `end()` call. Where the span is already non-recording, the record is emitted as a structured log line with `trace_id` and `span_id` so the attribute survives outside the span, and a `gen_ai.attribute_after_end` counter is incremented. ```python from dataclasses import dataclass, field from typing import Any class HollowGenAISpanError(RuntimeError): """Raised when a gen_ai.tool.call span is finalized without required attributes.""" def __init__(self, span_id: str, missing: list[str]): self.span_id = span_id self.missing = missing super().__init__( f"gen_ai.tool.call span {span_id} is hollow; missing {missing}" ) @dataclass class ToolCallRecord: tool_name: str tool_call_id: str attributes: dict[str, Any] = field(default_factory=dict) REQUIRED = ("gen_ai.tool.name", "gen_ai.tool.call.id") def finalize(self, span) -> None: if not span.is_recording(): # Span went non-recording before the tool call finalized. # Do not silently drop; surface as a structured log + metric. emit_degraded_log( trace_id=span.get_span_context().trace_id, span_id=span.get_span_context().span_id, record=self, ) increment_counter("gen_ai.attribute_after_end") return span.set_attribute("gen_ai.tool.name", self.tool_name) span.set_attribute("gen_ai.tool.call.id", self.tool_call_id) for k, v in self.attributes.items(): span.set_attribute(k, v) span.end() def validate_exported_tool_span(span_dict: dict) -> None: """Guardrail run before export: reject hollow gen_ai.tool.call spans.""" if span_dict.get("name") != "gen_ai.tool.call": return attrs = span_dict.get("attributes", {}) missing = [k for k in ToolCallRecord.REQUIRED if k not in attrs] if missing: raise HollowGenAISpanError( span_id=span_dict["context"]["span_id"], missing=missing ) def emit_degraded_log(trace_id: int, span_id: int, record: ToolCallRecord) -> None: ... def increment_counter(name: str) -> None: ... ```