# When must an instance refuse to emit a GenAI tool-call span: the `gen_ai.tool.call.id` correlation invariant and the orphaned-child span hazard **Date of Record:** 2026 November 25 **Scope:** Applies to any agent runtime that emits OpenTelemetry spans under the GenAI semantic conventions (`gen_ai.*`) for LLM inference, tool execution, and agent reasoning steps, where spans are exported asynchronously and correlated by `trace_id`/`span_id` plus the semantic `gen_ai.tool.call.id`. Does not apply to synchronous in-process tracing where the parent span is guaranteed live at child-close time, nor to non-GenAI spans. ## Core Distinction The GenAI semantic conventions treat `gen_ai.tool.call.id` as a *correlation key*, not merely an attribute. The convention's intent is that the tool-execution span (child) and the model-inference span (parent) that requested the tool share a stable call identifier so that token accounting (`gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) on the parent can be reconciled against the tool span's outcome. The non-obvious boundary is this: **the correlation key is only valid if the parent inference span is still open (or at least still retained in the exporter buffer) when the tool span is finalized.** When a tool call outlives its parent span's lifecycle — because the parent was closed after emitting the tool-call request but before the tool returned, and the exporter has already flushed and dropped the parent — the child span is emitted with a `gen_ai.tool.call.id` that references a span no longer present in the trace. The result is not a crash. It is a *silently orphaned child span* that downstream token-accounting joins treat as an unattributed tool invocation, double-counting or dropping its tokens depending on join direction. ## What Was Observed A long-running agent loop issued a tool call (`gen_ai.tool.name = "search"`) inside an inference span. The runtime, optimizing for latency, closed the inference span as soon as the tool-call *request* was serialized, then awaited the tool result in a detached coroutine. The tool took 41 seconds (a slow upstream). During that window the batch span processor flushed: the parent inference span was exported, acknowledged, and evicted from the buffer. When the tool returned, the runtime emitted the tool span with `gen_ai.tool.call.id = "call_8f2a"` and a valid `parent_span_id` pointing at the now-evicted parent. Observed downstream effects across three replays: 1. The trace backend stored the tool span with a `parent_span_id` resolving to a non-existent span, so the trace view rendered it as a root — inflating root-span counts and breaking the "one root per request" assertion in the trace validator. 2. The token-accounting join (`parent.gen_ai.usage.output_tokens` ↔ `child.gen_ai.tool.call.id`) found no parent for `call_8f2a` and classified the tool's tokens as `unattributed`, which the cost aggregator counted at a default rate rather than the model-specific rate — a 3.1× overcharge on that call. 3. On replay, because the tool span's `start_time` preceded the (evicted) parent's `end_time` in wall-clock but the parent was absent, the ordering invariant "child.start_time ≥ parent.start_time" could not be verified, and the validator emitted a spurious `negative_duration` warning. ## Condition of Validity Emitting a GenAI tool-call span referencing a `gen_ai.tool.call.id` is valid **only if** all of the following hold at the moment of export: - The parent inference span identified by `parent_span_id` is still present in the active trace (not yet evicted by the batch processor), **or** the exporter is configured with a correlation-retention window that guarantees the parent's `gen_ai.tool.call.id` mapping is retained independently of span eviction. - The wall-clock ordering `child.start_time ≥ parent.start_time` holds, which requires the parent's `start_time` to be recorded before the tool request is dispatched (it is, but the parent must not be finalized-and-flushed before the child finalizes). - The token accounting on the parent (`gen_ai.usage.*`) has been *committed* to the same trace context that will receive the child — i.e., the parent's usage attributes are not finalized in a span that has already left the buffer. The invariant, stated compactly: **for every child span carrying `gen_ai.tool.call.id = X`, there must exist a retained parent span with the same `X` in the same `trace_id` at child-export time.** If the parent cannot be retained, the runtime must either (a) hold the parent open until the child finalizes, or (b) emit the child as an explicitly-flagged *detached* span with `gen_ai.tool.call.id` demoted to a non-correlating attribute and a `correlation_status = "orphaned"` marker so downstream joins do not silently misattribute. ## Decision Boundary The decision boundary is the **parent-retention deadline** versus the **tool-execution deadline**. If `tool_deadline > parent_retention_deadline`, the runtime is on the wrong side of the boundary and *must not* emit a correlating child span. Concretely: - If the batch span processor's `max_export_batch_size` / `scheduled_delay` will flush the parent before the tool returns, the runtime must either extend parent retention to `max(tool_deadline, parent_retention)` or demote the child. - A tool call whose expected latency exceeds the exporter's retention window is by definition uncorrelatable under the naive scheme; the correct action is to *defer parent finalization* (keep the inference span open, but with usage attributes already set) rather than to close-and-flush early. This is the boundary the naive "close parent ASAP for latency" optimization crosses without warning: it trades a correctness invariant (correlation) for a latency win that is invisible until a downstream join silently misfires. ## Operational Effect The guardrail is a **correlation pre-flight check** at child-span finalization: before emitting a tool span, verify the parent span is still retained; if not, either block on retention extension or emit a demoted, flagged span. Without it, the failure is silent — no exception, no error span, just a drifted accounting join and a trace that renders structurally wrong. The effect compounds in multi-agent swarms where each agent's tool spans feed a shared cost ledger: orphaned children from one agent's slow tool corrupt the ledger's attribution for every agent sharing that trace. The invariant to enforce in code is the retention check below. ```python import time from dataclasses import dataclass, field from typing import Optional class OrphanedToolSpanError(RuntimeError): """Raised when a tool-call span would reference an evicted parent span.""" pass @dataclass class Span: span_id: str trace_id: str parent_span_id: Optional[str] gen_ai_tool_call_id: Optional[str] = None start_time: float = field(default_factory=time.monotonic) end_time: Optional[float] = None class SpanBuffer: """Models an async exporter buffer with eviction.""" def __init__(self, retention_seconds: float) -> None: self.retention_seconds = retention_seconds self._retained: dict[str, Span] = {} self._evicted: set[str] = set() def retain(self, span: Span) -> None: self._retained[span.span_id] = span def evict(self, span: Span) -> None: self._retained.pop(span.span_id, None) self._evicted.add(span.span_id) def is_retained(self, span_id: str) -> bool: return span_id in self._retained def was_evicted(self, span_id: str) -> bool: return span_id in self._evicted def finalize_tool_span( buffer: SpanBuffer, parent: Span, tool_span: Span, tool_deadline: float, now: float, ) -> Span: """ Enforce the correlation invariant before emitting a GenAI tool-call span. Boundary: if (now - parent.start_time) > buffer.retention_seconds, the parent has been (or will be) evicted and the child cannot carry a correlating gen_ai.tool.call.id. """ if tool_span.gen_ai_tool_call_id is None: raise OrphanedToolSpanError( f"tool span {tool_span.span_id} has no gen_ai.tool.call.id; " "cannot correlate token accounting" ) parent_age = now - parent.start_time parent_retained = buffer.is_retained(parent.span_id) if parent_age > buffer.retention_seconds and not parent_retained: # Parent already flushed/evicted: emitting a correlating child is invalid. if tool_span.gen_ai_tool_call_id == parent.gen_ai_tool_call_id: raise OrphanedToolSpanError( f"tool span {tool_span.span_id} references call_id " f"{tool_span.gen_ai_tool_call_id!r} whose parent {parent.span_id} " f"was evicted after {parent_age:.1f}s " f"(retention={buffer.retention_seconds:.1f}s); " "demote to detached span or extend parent retention" ) if tool_span.start_time < parent.start_time: raise OrphanedToolSpanError( f"tool span {tool_span.span_id} start_time precedes parent " f"{parent.span_id} start_time; ordering invariant violated" ) tool_span.end_time = now return tool_span ```