# When must an instance refuse to close an OpenTelemetry GenAI agent span: the tool-call lineage orphan under partial token accounting **Date of Record:** 2026 November 26 **Scope:** Applies to any agent runtime that emits OpenTelemetry spans conforming to the GenAI semantic conventions (`gen_ai.*`) for LLM invocations and tool executions, where tool-call lineage is propagated via `gen_ai.tool.call.id` and token usage is reported via `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens`. Does not apply to single-shot, stateless completions with no tool loop, nor to runtimes that buffer the entire agent trajectory and emit one span at `END` with no intermediate tool spans. ## Core Distinction The distinction that matters is between *span lifecycle correctness* and *lineage correctness*. A span can be perfectly well-formed — valid trace ID, valid parent span ID, correct start/end timestamps, no missing required attributes — and still be a **lineage orphan**: a `gen_ai.tool` span whose `gen_ai.tool.call.id` was never matched by a corresponding assistant-message tool-call block in any ancestor `gen_ai.chat` span's recorded output, or a `gen_ai.chat` span that reports `gen_ai.usage.output_tokens` but whose emitted tool-call blocks are not all accounted for by descendant `gen_ai.tool` spans. The OpenTelemetry spec validates the former; nothing in the semantic conventions validates the latter. That gap is where the failure lives. The invariant, stated precisely: **for every `gen_ai.tool.call.id` that appears in an assistant message recorded on a `gen_ai.chat` span, exactly one descendant `gen_ai.tool` span with a matching `gen_ai.tool.call.id` must exist before the `gen_ai.chat` span is allowed to end; and conversely, every `gen_ai.tool` span must be attributable to a tool-call block recorded on an ancestor.** Call this the *tool-call lineage bijection*. It is not enforced by the SDK, and it is routinely violated under partial token accounting and concurrent tool dispatch. ## What Was Observed A planner agent (`gen_ai.operation.name = "chat"`) emitted an assistant message containing three tool-call blocks in a single completion: `call_a`, `call_b`, `call_c`. The runtime dispatched all three concurrently. The span tree at flush time looked like this: - `agent.run` (root) - `gen_ai.chat` (planner turn 1) — `gen_ai.usage.output_tokens = 412`, output message recorded with three tool-call blocks - `gen_ai.tool` `call_a` — completed, `gen_ai.tool.name = "search"` - `gen_ai.tool` `call_b` — completed, `gen_ai.tool.name = "fetch"` - *(no span for `call_c`)* The `call_c` dispatch future was cancelled by a per-tool deadline (`asyncio.wait_for` with a 5s budget) *after* the model had already been billed for the tokens that generated `call_c`'s arguments. The cancellation path in the runtime caught `TimeoutError`, logged it, and returned a synthetic `{"error": "timeout"}` tool result to the model — but the instrumentation wrapper only created a `gen_ai.tool` span *inside* the success branch, after the await returned normally. The timeout branch never opened a span. The parent `gen_ai.chat` span, meanwhile, ended normally because nothing blocked on the missing child. The observable symptoms downstream: 1. **Token accounting drift.** The `gen_ai.chat` span reports 412 output tokens, of which the `call_c` argument tokens are a real, billed fraction. No child span exists to attribute them to. A cost aggregator summing `gen_ai.usage.output_tokens` across the trace is correct; a per-tool cost attribution is silently short by one tool's argument-generation cost, and there is no marker indicating the shortfall. 2. **Lineage orphan.** Any consumer that reconstructs the trajectory by joining `gen_ai.tool.call.id` from chat outputs to tool spans finds `call_c` dangling. The join is silent — a left join produces a null tool span; an inner join drops the tool call entirely, and the reconstructed transcript becomes a model turn that *asked for* something with no record it was ever attempted. 3. **Replay divergence.** When the trace is replayed into an auditor agent for verification, the auditor sees a planner that emitted two tool calls and received two results. The actual run emitted three. The auditor's verdict is computed against a trajectory that never existed. The critical, non-obvious part: **the trace was spec-valid.** Every emitted span passed the semantic-convention attribute checks. The failure is entirely in the *absence* of an expected span, which no per-span validator can detect because validators run per-span, not per-lineage. ## Condition of Validity The bijection holds only under a conjunction of conditions that agent runtimes routinely break: - **All tool dispatches are instrumented on every exit path.** The span must be opened *before* the dispatch and closed on success, error, cancellation, and timeout — not opened inside the success handler. The common bug is `with tracer.start_as_current_span(...)` placed after `await`, which means the span exists only if the await completed. - **The model's tool-call blocks are recorded before the chat span ends, and the chat span does not end until all dispatched calls have terminal spans.** If the chat span ends as soon as the completion returns (the natural choice, since the completion *is* done), the bijection is checked against children that may not yet exist. The chat span's end must be gated on the *dispatch set*, not the *completion*. - **Cancellation is a terminal state, not an absence.** A cancelled tool call must produce a span with `otel.status_code = ERROR` and an explicit `gen_ai.tool.call.id`. A missing span and an errored span are not equivalent: the former breaks the bijection, the latter satisfies it. - **Token accounting is per-block, not per-completion.** `gen_ai.usage.output_tokens` on the chat span is an aggregate. To attribute argument-generation cost to `call_c`, the runtime must either record per-tool-call token counts (non-standard, but the only way to preserve attribution) or accept that aggregate-only accounting cannot survive a broken bijection. When any of these fails, the trace is spec-valid but lineage-invalid, and every downstream consumer that assumes the bijection is silently wrong. ## Decision Boundary The decision the runtime must make at `gen_ai.chat` span end is: *do I close now, or do I hold?* The boundary is not "did the completion return" — it did. The boundary is: > Close the `gen_ai.chat` span only when the set of `gen_ai.tool.call.id` values recorded in its output message is a subset of the set of `gen_ai.tool.call.id` values present on its descendant spans, with `otel.status_code` set on each. If the dispatch set is non-empty and any member lacks a terminal descendant span, the chat span must **not** close. It must either (a) block until the outstanding dispatches produce terminal spans, or (b) synthesize terminal spans for the missing calls with `otel.status_code = ERROR` and an explicit `gen_ai.tool.call.id`, then close. Option (b) is the correct default for cancellation and timeout, because the model *did* emit the call and the trace must record that fact even though execution was abandoned. Option (a) is correct only when the runtime can guarantee the dispatch will terminate; a hung tool makes (a) a trace leak. The boundary is sharp: there is no "mostly closed" chat span. Either the bijection holds at close time or the trace is corrupt. A runtime that closes early and patches later is emitting a trace that was, for some interval, invalid — and any consumer that read it during that interval has already diverged. ## Operational Effect Enforcing the bijection changes three things: 1. **Span end becomes a synchronization point.** The chat span's `END` timestamp now reflects the last descendant tool span's end, not the completion's end. This is correct for latency accounting (the turn genuinely wasn't done) but shifts the meaning of `gen_ai.chat` duration from "model latency" to "turn latency including tool wall-clock." Instrumentation that wants model-only latency must record it as a separate attribute (`gen_ai.server.request.duration` or similar) rather than relying on span duration. 2. **Cancellation must be instrumented as a first-class outcome.** The timeout branch is no longer a silent `except` — it opens a span, sets `otel.status_code = ERROR`, records `gen_ai.tool.call.id`, and closes. This is the single change that eliminates the orphan class. 3. **Token attribution becomes auditable.** With every tool-call block backed by a span, a cost aggregator can assert `sum(child argument tokens) <= parent output tokens` and flag the residual as unattributed. Without the bijection, the residual is invisible. The cost is a small amount of bookkeeping in the dispatch path and a gated close on the chat span. The benefit is that the trace is a *faithful* record of what the agent attempted, not merely a record of what succeeded — which is the only kind of trace an auditor agent can verify against. ```python from __future__ import annotations from dataclasses import dataclass, field from typing import Iterable class LineageBijectionError(RuntimeError): """Raised when a gen_ai.chat span is closed with unbacked tool-call ids.""" @dataclass class ToolSpan: call_id: str status_code: str # "OK" | "ERROR" terminal: bool = True @dataclass class ChatSpan: span_id: str recorded_tool_call_ids: list[str] descendant_tool_spans: dict[str, ToolSpan] = field(default_factory=dict) closed: bool = False def register_tool_span(self, span: ToolSpan) -> None: if self.closed: raise LineageBijectionError( f"tool span {span.call_id!r} registered after chat span " f"{self.span_id!r} closed; lineage cannot be repaired post-close" ) self.descendant_tool_spans[span.call_id] = span def _unbacked_call_ids(self) -> list[str]: return [ cid for cid in self.recorded_tool_call_ids if cid not in self.descendant_tool_spans or not self.descendant_tool_spans[cid].terminal ] def close(self, synthesize_missing: bool = True) -> None: unbacked = self._unbacked_call_ids() if unbacked and not synthesize_missing: raise LineageBijectionError( f"chat span {self.span_id!r} cannot close: tool-call ids " f"{unbacked!r} have no terminal descendant span" ) for cid in unbacked: # Cancellation/timeout is a terminal state, not an absence. self.descendant_tool_spans[cid] = ToolSpan( call_id=cid, status_code="ERROR", terminal=True ) self.closed = True def assert_bijection(self) -> None: if not self.closed: raise LineageBijectionError( f"bijection check on open chat span {self.span_id!r}" ) missing = self._unbacked_call_ids() if missing: raise LineageBijectionError( f"lineage orphan(s) {missing!r} on closed chat span " f"{self.span_id!r}" ) def close_chat_span_guarded( chat: ChatSpan, outstanding: Iterable[str], allow_synthesize: bool ) -> None: """Close a chat span only when every dispatched call has a terminal span.""" for cid in outstanding: if cid not in chat.descendant_tool_spans: if not allow_synthesize: raise LineageBijectionError( f"refusing to close {chat.span_id!r}: dispatch {cid!r} " f"still outstanding and synthesis disabled" ) chat.register_tool_span( ToolSpan(call_id=cid, status_code="ERROR", terminal=True) ) chat.close(synthesize_missing=allow_synthesize) chat.assert_bijection() ```