# Under what conditions must an instance refuse to emit a GenAI agent span until its parent tool-call span has been closed by the transport layer **Date of Record:** 2026 November 28 **Scope:** Applies to instrumented LLM agent runtimes that emit OpenTelemetry spans following the GenAI semantic conventions (`gen_ai.*` attributes) and that nest tool-execution spans beneath an agent/chat span, where tool results are delivered asynchronously by an external transport (MCP server, A2A peer, or a queued executor). Does not apply to fully synchronous in-process tool calls where the child span closes within the parent's execution frame. ## Core Distinction The GenAI semantic conventions model an agent turn as a parent span (`gen_ai.operation.name = "chat"` or `"invoke_agent"`) carrying `gen_ai.usage.input_tokens` / `gen_ai.usage.output_tokens`, with tool invocations represented either as span events or as child spans (`gen_ai.operation.name = "execute_tool"`) bearing `gen_ai.tool.name`, `gen_ai.tool.call.id`, and `gen_ai.tool.type`. The convention is silent on *temporal ordering* between a token-usage metric emission and the closure of a tool-call child span. This produces a boundary that is not about correctness of any single attribute but about **span-tree integrity under asynchronous completion**. When the agent's token-usage is flushed at end-of-turn but a tool-call child span is still open (because the transport has not yet delivered the result), the exporter serializes a parent span whose `end_time` precedes its child's `end_time`. Backends that reconstruct trees by timestamp — Jaeger's dependency graph, many OTLP-to-Parquet pipelines, and cost-attribution joins that bucket by parent `end_time` — will either orphan the child or attribute its duration and any `gen_ai.usage` carried on it to the wrong turn. The invariant that must hold: **a parent GenAI span may not be exported until every child tool-call span it owns has been closed and its `gen_ai.tool.call.id` reconciled against the `tool_calls` array in the parent's recorded completion.** ## What Was Observed In a runtime using an MCP stdio transport with a 30-second tool timeout, the agent loop emitted the parent `chat` span immediately after receiving the model's completion (which contained a `tool_calls` block), because the completion itself was the natural end-of-turn signal. The tool executor ran on a separate task and closed its `execute_tool` child span 200–4000 ms later. Under normal latency the parent had already been exported. The resulting OTLP batch contained: - Parent span `chat`, `end_time = T`, `gen_ai.usage.output_tokens = 412`, status unset. - Child span `execute_tool`, `start_time = T+12ms`, `end_time = T+830ms`, `gen_ai.tool.call.id = call_abc`, status `OK`. The parent's `tool_calls` array referenced `call_abc`, but the child span arrived with a later timestamp than its parent. Three downstream symptoms appeared: 1. **Orphaned children.** The trace assembler, which sorts spans by `start_time` and attaches a child to the nearest preceding span with a matching `trace_id` and `parent_span_id`, dropped the child because no open parent existed at `T+12ms`. The tool call vanished from the trace; only the parent remained. 2. **Cost double-count or loss.** A cost-attribution job summed `gen_ai.usage.input_tokens` over all spans with `gen_ai.operation.name` in `{chat, execute_tool}`. Because the child span inherited a copy of the request's `input_tokens` (a convenience the instrumentation added), the same prompt was counted twice when the child *did* attach, and zero times when it was orphaned. 3. **Status masking.** A tool that returned `isError: true` set the child span status to `ERROR`, but the parent — already exported — remained `UNSET`. Alerting keyed on parent status never fired for failed tool calls whose parent had closed first. The failure was intermittent: it depended on whether the tool result arrived before or after the exporter's batch flush interval (5 s). Tools slower than the flush interval reliably orphaned; tools faster than it reliably attached. This latency-dependent nondeterminism is the signature of the boundary. ## Condition of Validity The refusal-to-emit rule is valid — and required — precisely when all of the following hold: - The parent GenAI span's completion payload contains one or more `tool_calls` entries (i.e., `finish_reason == "tool_calls"` or equivalent). - Tool execution is dispatched to any executor whose completion is not guaranteed within the parent's synchronous frame (separate task, worker queue, remote MCP/A2A peer). - The instrumentation attaches token-usage attributes to child tool spans, or a downstream consumer joins on parent `end_time`. It is **not** required when tool calls are represented purely as span *events* on the parent (the `gen_ai.tool.call` event form), because events carry no independent timestamp ordering constraint and cannot be orphaned. It is also not required when the backend is known to reconstruct trees by `parent_span_id` alone with no timestamp assumption — though the cost-double-count hazard remains and must be handled by attribute ownership (see below). ## Decision Boundary The runtime must make a binary decision at the moment the model completion is parsed: - **If the completion contains no tool calls:** close and export the parent span immediately. Token usage is final and no child can arrive later. - **If the completion contains tool calls:** mark the parent span **non-exportable** and transition it to a `PENDING_TOOL_RESOLUTION` state. The parent may only be closed after every `gen_ai.tool.call.id` in the completion's `tool_calls` array has a corresponding closed child span, or has been explicitly resolved as `tool.timeout` with a synthesized child span carrying `error.type = "timeout"`. The parent's `gen_ai.usage.output_tokens` must be recorded from the completion, but its `end_time` must be the max of its own completion time and all child `end_time`s. The guardrail is: **token-usage attributes are owned by exactly one span.** The parent owns `gen_ai.usage.input_tokens` and `gen_ai.usage.output_tokens` for the turn. Child tool spans must **not** carry `gen_ai.usage.*`; they carry only `gen_ai.tool.*`. Any instrumentation that copies usage onto children violates the invariant and creates the double-count hazard independent of ordering. ## Operational Effect Enforcing the deferral converts a latency-dependent, intermittent orphaning bug into a bounded, deterministic wait. The cost is that the parent span's export is delayed by the slowest tool in the turn — bounded by the tool timeout. In the observed runtime this raised p99 trace-completion latency from 40 ms to 4.2 s for tool-bearing turns, but eliminated orphaned children entirely and made parent status reflect tool failure. The synthesized timeout child span preserves the `tool_calls` → `execute_tool` cardinality so that reconciliation joins remain one-to-one. The remaining hazard is a tool that never resolves and never times out: the parent span leaks open. This must be bounded by a hard deadline on the parent's `PENDING_TOOL_RESOLUTION` state, after which the parent is force-closed with `error.type = "tool_resolution_deadline_exceeded"` and each unresolved `tool.call.id` gets a synthesized error child — never silently dropped. ```python import time from dataclasses import dataclass, field from typing import Optional class SpanExportOrderError(RuntimeError): """Raised when a GenAI parent span is exported before its tool-call children close.""" @dataclass class GenAISpan: span_id: str operation: str # "chat" | "invoke_agent" | "execute_tool" parent_span_id: Optional[str] = None tool_call_id: Optional[str] = None # only on execute_tool children start_time: float = field(default_factory=time.monotonic) end_time: Optional[float] = None attributes: dict = field(default_factory=dict) open_tool_calls: set = field(default_factory=set) # expected child call ids closed_tool_calls: set = field(default_factory=set) exported: bool = False class SpanTreeGuard: """Enforces: a GenAI parent may not export until all tool-call children close.""" def __init__(self, resolution_deadline_s: float = 30.0): self.deadline = resolution_deadline_s def register_parent(self, span: GenAISpan, tool_calls: list) -> None: # tool_calls: list of {"id": ..., "name": ...} from the completion span.open_tool_calls = {tc["id"] for tc in tool_calls} for tc in tool_calls: span.attributes.setdefault("gen_ai.tool.call.id", []).append(tc["id"]) def register_child(self, parent: GenAISpan, child: GenAISpan) -> None: if child.tool_call_id is None: raise SpanExportOrderError( f"execute_tool child {child.span_id} missing gen_ai.tool.call.id" ) if "gen_ai.usage.input_tokens" in child.attributes: raise SpanExportOrderError( f"child {child.span_id} illegally carries gen_ai.usage; " "usage is owned by the parent span only" ) if child.tool_call_id not in parent.open_tool_calls: raise SpanExportOrderError( f"child call id {child.tool_call_id} not declared in parent tool_calls" ) def close_child(self, parent: GenAISpan, child: GenAISpan) -> None: child.end_time = child.end_time or time.monotonic() parent.closed_tool_calls.add(child.tool_call_id) def try_export_parent(self, parent: GenAISpan) -> bool: now = time.monotonic() unresolved = parent.open_tool_calls - parent.closed_tool_calls if unresolved: if now - parent.start_time < self.deadline: return False # defer, do not export # deadline exceeded: synthesize error children, never drop silently for call_id in unresolved: parent.attributes.setdefault("error.type", []).append( "tool_resolution_deadline_exceeded" ) parent.closed_tool_calls.add(call_id) raise SpanExportOrderError( f"parent {parent.span_id} force-closed at deadline with " f"{len(unresolved)} unresolved tool calls: {sorted(unresolved)}" ) parent.end_time = max( [parent.start_time] + [parent.end_time or 0.0] ) parent.exported = True return True ```