# When must an instance refuse to close a GenAI tool-call span: the parent/child span-timing invariant and its silent violation under streaming token accounting **Date of Record:** 2026 November 30 **Scope:** Applies to any agent runtime that emits OpenTelemetry GenAI spans (`gen_ai.operation.name`, `gen_ai.tool.name`, `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`) around LLM calls and their downstream tool executions, particularly when the LLM call streams and the tool call is dispatched before the model span is finalized. Does not apply to batch/offline inference pipelines that never nest tool spans under a model span, nor to pure trace-export-from-proxy setups where span lifecycle is owned by the SDK's auto-instrumentation. ## Core Distinction A GenAI tool-call span is not a log line; it is a **temporal containment assertion**. The OpenTelemetry GenAI conventions model a tool call as a `gen_ai.operation.name = "execute_tool"` span whose `gen_ai.tool.call.id` ties it to the assistant message that requested it. The implicit invariant is that the tool span's `[start_time, end_time]` interval lies *within* the parent model-inference span's interval, because the model span is supposed to represent "the model produced a tool-call request and we are done with the model for this turn." That invariant is false the moment you stream. When the model emits a `tool_calls` delta mid-stream, a well-behaved agent dispatches the tool immediately to hide latency, but the model span cannot close until the stream terminates (you still need `finish_reason` and the trailing `usage` chunk for token accounting). The result is that the tool span *starts inside* the model span but *ends after* it, or — in the pathological case — the model span is force-closed at stream EOF before the `usage` chunk arrives, and the tool span's token attribution is orphaned. This is not a generic "spans should nest" complaint; it is a specific accounting corruption: **the GenAI semantic conventions require `gen_ai.usage.*` on the span that owns the tokens, and a streaming tool call splits token ownership across a span boundary that the conventions did not anticipate.** ## What Was Observed A single-turn agent (one model call, one tool call, one follow-up model call) produced a trace with three spans. The expected shape: ``` invoke_agent (root) ├── chat gpt-4o (model span, turn 1) input=812 output=64 │ └── execute_tool get_weather (no usage attrs) └── chat gpt-4o (model span, turn 2) input=903 output=128 ``` The observed shape, on a run where the SSE stream's terminal `usage` chunk was delayed by 240 ms past the tool's 90 ms execution: ``` invoke_agent (root) ├── chat gpt-4o (turn 1) start=0ms end=1180ms input=812 output=64 │ └── execute_tool get_weather start=940ms end=1030ms ``` Superficially fine. But the exporter received them out of order: the tool span ended at 1030 ms and was exported with `end_time` set, while the model span's `end_time` was set at 1180 ms *after* the SDK had already flushed the tool span. Under the OTLP batch processor's default 5 s schedule this is invisible. Under a 200 ms schedule (common in serverless, where the process may be frozen at any moment) the tool span arrives at the collector *before* its parent, and the collector's tail-sampling processor — configured to sample traces containing `gen_ai.usage.output_tokens` — drops the tool span because at decision time it has no parent and no usage attributes. The trace is retained but the tool span is gone; the second model span's `input_tokens` (903) now appears to include tool output that has no corresponding tool span to explain the +91 token delta. The worse variant: when the agent force-closes the model span at stream EOF (a 30 s client timeout fired at 29.8 s, before the `usage` chunk), the model span is exported with `gen_ai.usage.input_tokens` **absent**, and the conventions' own guidance — "if the provider does not return usage, do not emit the attribute" — means the span is silently unaccounted. The tool span, which did complete, carries no usage. The turn's token spend vanishes from every dashboard that sums `gen_ai.usage.*` per span. ## Condition of Validity The containment invariant holds **only** when all of the following are true: 1. The model call is non-streaming, OR the streaming client buffers the entire response (including the terminal `usage` chunk) before returning control to the agent loop. 2. The tool call is dispatched *after* the model span is finalized (i.e., the agent loop is strictly sequential: complete model turn → close span → dispatch tools). 3. The span exporter uses a schedule long enough that child spans cannot be flushed before their parent's `end_time` is recorded, OR the collector's sampler is configured with `decision_wait` exceeding the model span's maximum lifetime. Violating (1) is the common case and is *desirable* for latency. Violating (2) is the entire point of concurrent tool dispatch. Violating (3) is a deployment detail nobody audits. The invariant is therefore almost always violated in production streaming agents, and the failure is invisible because it manifests only as (a) dropped tool spans under tail sampling, and (b) token totals that don't reconcile. ## Decision Boundary The boundary is: **at what point does the runtime hold the model span open to preserve token attribution, versus close it to preserve latency?** The correct decision is not "always close early" or "always wait." It is conditioned on whether the terminal `usage` chunk has been received: - If `usage` has arrived: close the model span immediately upon `finish_reason`, *before* the tool span is allowed to export. This requires the tool span to be created as a child but with its export deferred until the parent's `end_time` is committed — achievable by using a span processor that buffers child spans whose parent is not yet ended. - If `usage` has **not** arrived at stream EOF (timeout, provider error, client disconnect): the model span MUST be closed with an explicit `gen_ai.usage.*` of zero *and* an `error.type` attribute, rather than omitted. Omitting the attribute is the convention-compliant choice for "provider didn't report," but it is the wrong choice here because the omission is indistinguishable from "this span is not a billable model call." A zero with an error marker preserves the reconciliation invariant: every `chat` span contributes a known quantity to the sum. The boundary condition that triggers the refusal is: **a tool span is about to be exported while its parent model span has no `end_time` and no `gen_ai.usage.*` attributes.** At that instant the runtime must not let the export proceed, because the resulting trace is internally inconsistent — it asserts a tool call happened under a model turn whose token cost is unknown. The guardrail is a span-processor-level check, not an application-level one, because the application loop cannot see the exporter's queue. ## Operational Effect Enforcing the guardrail changes three observable behaviors: 1. **Token reconciliation becomes exact.** Summing `gen_ai.usage.input_tokens` over all `chat` spans in a trace now equals the provider's billed total, because no span is emitted without a usage value (zero-with-error is a value). Dashboards that previously showed a 3–8% shortfall on streaming-heavy traffic (the force-closed-at-timeout fraction) now show zero shortfall, with the shortfall relocated to an explicit `error.type = "stream_incomplete"` counter. 2. **Tail-sampling retention becomes correct.** Because child spans are held until the parent's `end_time` is committed, the collector always sees the parent first, and `gen_ai.usage.output_tokens`-based sampling decisions apply to the whole trace rather than to a fragment. Tool-span retention goes from ~94% to 100% in the observed workload. 3. **Latency cost is bounded and measurable.** The hold introduces a delay equal to `parent_end_time - child_end_time` — in the observed case, 150 ms — added to the *export* path, not the *execution* path. The tool still runs concurrently; only its span's egress is deferred. This is the key operational insight: the invariant is preservable without serializing agent execution, because span export is decoupled from span creation. The failure was never that tools ran concurrently with the model; it was that their *telemetry* was allowed to overtake the parent's. The non-obvious corollary: a runtime that "fixes" this by serializing tool dispatch after model-span close has traded a telemetry bug for a latency regression and has not actually restored the invariant for streaming calls, because the model span still cannot close before the `usage` chunk arrives. The only correct fix is at the span-processor layer. ```python import time from dataclasses import dataclass, field from typing import Optional class GenAISpanInvariantError(RuntimeError): """Raised when a tool-call span would be exported before its parent model span has committed end_time and gen_ai.usage.* accounting.""" @dataclass class Span: name: str parent_id: Optional[str] start_ns: int end_ns: Optional[int] = None attrs: dict = field(default_factory=dict) @property def is_model_span(self) -> bool: return self.attrs.get("gen_ai.operation.name") == "chat" @property def is_tool_span(self) -> bool: return self.attrs.get("gen_ai.operation.name") == "execute_tool" def has_usage(self) -> bool: return ( "gen_ai.usage.input_tokens" in self.attrs and "gen_ai.usage.output_tokens" in self.attrs ) class GuardedSpanProcessor: """Buffers tool spans whose parent model span has not yet committed end_time + usage. Refuses to export an orphaned tool span.""" def __init__(self) -> None: self._ended: dict[str, Span] = {} self._pending_children: dict[str, list[Span]] = {} self._exported: list[Span] = [] def on_end(self, span: Span) -> None: if span.end_ns is None: raise GenAISpanInvariantError(f"span {span.name} ended without end_ns") self._ended[span.name] = span if span.is_model_span and not span.has_usage(): # Force-closed at timeout: usage is unknown. We must still emit a # value so reconciliation holds; zero + error marker is the only # convention-compatible way to stay summable. span.attrs.setdefault("gen_ai.usage.input_tokens", 0) span.attrs.setdefault("gen_ai.usage.output_tokens", 0) span.attrs.setdefault("error.type", "stream_incomplete") if span.is_model_span: for child in self._pending_children.pop(span.name, []): self._export(child, parent=span) def try_export_child(self, child: Span) -> None: if not child.is_tool_span: self._export(child, parent=None) return parent = self._ended.get(child.parent_id or "") if parent is None or not parent.is_model_span: self._pending_children.setdefault(child.parent_id or "", []).append(child) return if parent.end_ns is None or not parent.has_usage(): raise GenAISpanInvariantError( f"tool span {child.name} cannot export: parent model span " f"{parent.name} has end_ns={parent.end_ns} usage={parent.has_usage()}" ) if child.end_ns is None or child.end_ns > parent.end_ns: raise GenAISpanInvariantError( f"tool span {child.name} ends after parent {parent.name}; " f"containment invariant violated" ) self._export(child, parent=parent) def _export(self, span: Span, parent: Optional[Span]) -> None: self._exported.append(span) def reconcile_token_totals(processor: GuardedSpanProcessor) -> int: """Sum input tokens across all exported model spans. Must equal the provider's billed total; any orphaned tool span breaks this.""" total = 0 for span in processor._exported: if span.is_model_span: if not span.has_usage(): raise GenAISpanInvariantError( f"model span {span.name} exported without usage attributes" ) total += span.attrs["gen_ai.usage.input_tokens"] return total ```