# What happens when an instance emits an OpenTelemetry GenAI span for a tool call that never resolves: the orphaned-span invariant and its silent corruption of agent trace continuity **Date of Record:** 2026 November 26 **Scope:** Applies to LLM agent runtimes that emit OpenTelemetry GenAI semantic-convention spans (`gen_ai.operation.name`, `gen_ai.tool.name`, `gen_ai.tool.call.id`, `gen_ai.usage.*`) around tool invocations, particularly when a tool call is dispatched but the span's end event is lost to timeout, cancellation, or process death. Does not apply to purely in-process metric-only instrumentation or to spans that are never exported. ## Core Distinction A tool-call span is not a log line. It is a *bracketed* temporal object: it asserts that an interval existed, that the interval began at a known time, and that the interval *closed*. The GenAI semantic conventions make this bracketing load-bearing by attaching `gen_ai.tool.call.id` to the span and expecting that the same call ID will appear on any subsequent span that consumes the tool's result (e.g., a follow-up `gen_ai.operation.name: chat` span whose prompt embeds the tool output). The distinction that matters operationally is between a **tool call that failed** (span closes with `error.type` set, `otel.status_code = ERROR`) and a **tool call whose span never closed** (the span is orphaned: it was started, exported once at start or on a periodic flush, and then the exporter never received the end event). The first is a recorded failure; the second is an *absence that looks like a success* because a start-only span with no status is indistinguishable, at the collector, from a span still in flight. This is non-obvious because the OpenTelemetry SDK's batch span processor will happily flush a started span *before* it ends if the process is killed, the event loop is blocked, or the span is dropped from the active-span map. The wire format has no "I am still open" flag. A start-only span and a completed span with all-empty attributes both serialize to a `Span` protobuf with `end_time_unix_nano = 0` or a start-equal end. Downstream trace assemblers that key on `gen_ai.tool.call.id` will treat the orphan as a legitimate predecessor and will *join* the follow-up chat span to a tool call that, from the agent's perspective, never returned a value. ## What Was Observed A single-agent runtime using a ReAct-style loop emitted, per turn, one `gen_ai.operation.name: execute_tool` span and one `gen_ai.operation.name: chat` span, linked by `gen_ai.tool.call.id`. The runtime wrapped each tool dispatch in `tracer.start_as_current_span(...)` with a `contextvars`-based current-span stack. On turn 7, the tool (an HTTP fetch) exceeded its 30s deadline. The agent's deadline handler raised a `TimeoutError`, which propagated through the tool wrapper *before* the `with span:` block's `__exit__` ran, because the wrapper used `asyncio.wait_for` around a coroutine that had already begun the span but whose cancellation path did not enter the span's context manager. The trace exported as follows: - `execute_tool` span, `gen_ai.tool.name: http_fetch`, `gen_ai.tool.call.id: call_7f3a`, `start_time: T`, **no end event, no `otel.status_code`**. - `chat` span, turn 8, `start_time: T+31s`, prompt containing the string `Tool call call_7f3a did not return a result.`, **no link to `call_7f3a`** because the agent's link emitter only linked to call IDs it had *received results for*. The collector received the orphaned `execute_tool` span on a periodic flush 12 seconds after `T`, i.e. *while the tool was still running*. A trace-joiner (a downstream service that rebuilt the agent's causal graph from span parent/child and tool-call-ID edges) saw a completed-looking tool span, then saw the turn-8 chat span with no tool-call link, and concluded the agent had *skipped* the tool call on turn 8 rather than *timed out* on turn 7. The joiner's "tool-call coverage" metric — the fraction of chat spans that had a linked tool span — therefore read 6/8 instead of 7/8, and an on-call operator spent 40 minutes investigating a phantom "agent bypassed its tools" regression. The root cause is not the timeout. It is that the span's *existence* on the wire was decoupled from its *completion*, and the semantic conventions provide no attribute that distinguishes "this tool call is still running" from "this tool call completed with zero duration and no status." ## Condition of Validity The orphaned-span failure is bounded by three conditions, all of which must hold for the corruption to propagate: 1. **The span is exported before it ends.** This happens under batch processors with a short `schedule_delay_millis`, under synchronous `SimpleSpanProcessor` on a start event, or under any exporter that flushes on a context switch. If spans are only exported on end, the orphan never reaches the collector and the failure is a local leak, not a trace corruption. 2. **A downstream consumer keys causal joins on span presence rather than on `otel.status_code` or a completion attribute.** Trace joiners, SLO calculators, and eval harnesses that reconstruct "did the agent call the tool" from span existence are the vulnerable consumers. Consumers that require `end_time_unix_nano > 0` and a non-empty `otel.status_code` are immune. 3. **The tool-call ID is not reused or superseded.** If the runtime retries with the same `gen_ai.tool.call.id`, the orphan and the retry's completed span collide on the join key, and the joiner must pick one — typically the first-arrived, i.e. the orphan. If the runtime mints a fresh call ID per attempt (the correct behavior), the orphan remains a distinct, unjoinable node. The invariant that must hold to prevent propagation is: **for every `gen_ai.tool.call.id` observed at the collector, exactly one span carries a terminal status (`OK` or `ERROR`), and any span carrying that ID without a terminal status is treated as in-flight-or-abandoned, never as completed.** This is a *set* invariant over the trace, not a per-span property, which is why per-span validation (JSON-schema checks on attributes) never catches it. ## Decision Boundary The boundary is between *treating span arrival as evidence of completion* and *treating terminal status as evidence of completion*. Concretely: - **Below the boundary (safe):** The agent runtime guarantees that every started `execute_tool` span is closed in a `finally` block, and on cancellation it sets `otel.status_code = ERROR`, `error.type = "timeout"`, and `gen_ai.tool.call.id` is preserved. The joiner requires `status_code ∈ {OK, ERROR}` to count a tool call. An orphan is then a *visible* defect (a span with no status) that a linter can flag. - **Above the boundary (corrupting):** The runtime closes spans only on the happy path; cancellation, `asyncio.CancelledError`, `KeyboardInterrupt`, and process OOM all bypass `__exit__`. The joiner counts span presence. Orphans silently inflate or deflate coverage metrics and mis-attribute causality. The decision an operator must make when they observe a start-only `execute_tool` span is *not* "is this a bug in the tool" but "does my join layer require terminal status?" If it does not, the trace is already untrustworthy and the correct action is to quarantine the trace, not to debug the tool. ## Operational Effect The practical consequences, in order of severity: 1. **Causal mis-attribution.** A follow-up `chat` span that consumed a timeout message is joined to no tool call, so the agent's reasoning appears to have hallucinated a tool result rather than having received a timeout. Post-mortems chase the model instead of the deadline handler. 2. **Coverage-metric drift.** Tool-call coverage ratios computed from span presence drift downward under load (more timeouts ⇒ more orphans ⇒ lower coverage) and are misread as the agent "learning" to skip tools. 3. **Retry-key collision.** If the runtime retries with the same `gen_ai.tool.call.id` (a common shortcut), the orphan and the retry's terminal span collide; joiners that "first match wins" bind the chat span to the orphan and lose the retry's actual result. 4. **Cost and token accounting skew.** `gen_ai.usage.input_tokens` on the *chat* span that follows an orphan is attributed to a turn with no tool input, so per-tool token attribution undercounts the tool's prompt cost. The guardrail is twofold: a runtime-side `finally`-close discipline with explicit `error.type` on cancellation, and a collector-side join rule that refuses to treat a span without terminal status as a completed tool call. The second is the invariant; the first is the hygiene that makes the invariant cheap to satisfy. ```python import time from dataclasses import dataclass, field from typing import Optional class OrphanedToolSpanError(RuntimeError): """Raised when a tool-call span is closed without a terminal status, or when a trace joiner is asked to treat an orphan as completed.""" pass @dataclass class GenAIToolSpan: tool_name: str call_id: str start_ns: int end_ns: Optional[int] = None status_code: Optional[str] = None # "OK" | "ERROR" | None (orphan) error_type: Optional[str] = None def close(self, status_code: str, error_type: Optional[str] = None) -> None: if status_code not in ("OK", "ERROR"): raise OrphanedToolSpanError( f"invalid terminal status {status_code!r} for call {self.call_id}" ) if self.end_ns is not None: raise OrphanedToolSpanError( f"double-close of tool span {self.call_id}" ) self.end_ns = time.time_ns() self.status_code = status_code self.error_type = error_type @property def is_terminal(self) -> bool: return self.end_ns is not None and self.status_code in ("OK", "ERROR") def join_chat_to_tool( chat_call_id: str, spans_by_call_id: dict[str, list[GenAIToolSpan]], ) -> GenAIToolSpan: candidates = spans_by_call_id.get(chat_call_id, []) if not candidates: raise OrphanedToolSpanError( f"no tool span found for call_id {chat_call_id}" ) terminal = [s for s in candidates if s.is_terminal] if not terminal: # The critical guard: presence is not completion. raise OrphanedToolSpanError( f"tool call {chat_call_id} has {len(candidates)} span(s) but none " f"terminal; refusing to treat orphan as completed tool call" ) if len(terminal) > 1: raise OrphanedToolSpanError( f"tool call {chat_call_id} has {len(terminal)} terminal spans; " f"call_id reused across retries — cannot join deterministically" ) return terminal[0] def close_span_on_cancellation(span: GenAIToolSpan, exc: BaseException) -> None: """Must be called from a finally block; the whole point is that the happy path is not the only path that closes the span.""" if span.is_terminal: return if isinstance(exc, (TimeoutError,)): span.close("ERROR", error_type="timeout") elif isinstance(exc, BaseException): span.close("ERROR", error_type=type(exc).__name__) else: raise OrphanedToolSpanError( f"close_span_on_cancellation called with no exception for {span.call_id}" ) ```