# What happens when an instance emits tool-call spans under OpenTelemetry GenAI conventions but the parent agent span closes before the child tool span flushes **Date of Record:** 2026 November 25 **Scope:** Applies to agent runtimes that instrument LLM invocations and tool calls using OpenTelemetry GenAI semantic conventions (`gen_ai.*` attributes) where spans are exported asynchronously via a batching span processor. Does not apply to synchronous exporters, single-threaded deterministic test harnesses, or pure prompt-level tracing without tool-call children. ## Core Distinction The GenAI semantic conventions define attribute *shape*, not span *lifecycle ordering*. A `gen_ai.operation.name = "execute_tool"` span is a child of the `gen_ai.operation.name = "chat"` (or `invoke_agent`) span by trace-parent linkage, but the runtime that emits it has no enforced contract that the child span must *end and be enqueued* before the parent span ends. Under a `BatchSpanProcessor`, span end → `on_end` → enqueue → background export is decoupled from the agent's control flow. The failure boundary is therefore not "tool call failed" or "span dropped" — it is **trace-parent inversion**: the child tool-call span arrives at the collector *after* the parent agent span has already been finalized and exported, producing orphaned or re-parented spans whose `gen_ai.tool.name`, `gen_ai.tool.call.id`, and token-usage attributes are detached from the agent turn that produced them. This is distinct from span loss. Nothing is dropped. The telemetry is *structurally correct per span* but *semantically orphaned per trace*, and downstream aggregation (cost per agent turn, tool-call success ratio, retry attribution) silently mis-attributes. ## What Was Observed A multi-step agent loop: `chat` span opens → model returns a `tool_calls` block → runtime opens `execute_tool` span, invokes the tool, ends the tool span → runtime opens a *second* `chat` span for the follow-up turn. The agent's top-level `invoke_agent` span ends when the loop terminates. Trigger condition: the tool execution is fast (sub-millisecond local tool, cached retrieval) while the `BatchSpanProcessor` schedule delay is the default 5000 ms with a `max_export_batch_size` that was not yet reached. The tool span ends, is enqueued, but the batch does not flush. The loop continues, the agent span ends, is enqueued into the *same* batch. On flush, both export together — fine. The break appears when the tool span's *parent* (`chat` span of turn N) is exported in one batch and the tool span lands in the next batch because the tool call was slow enough (a network tool at ~4.9 s) to cross the schedule-delay boundary. Observed trace in the backend: - `invoke_agent` (root) — exported, `status=OK`, duration 6.1 s - `chat` turn 1 — exported, child of root - `execute_tool` — exported ~5.2 s *later*, `parent_span_id` pointing at `chat` turn 1's span ID, but `chat` turn 1's span was already marked complete and its `end_time` precedes the tool span's `start_time` by 4.9 s. The backend's trace assembler accepts the linkage (parent_span_id resolves) but the *causal ordering* is now impossible: a child that starts before its parent ends, yet arrives after the parent was flushed. Some backends (Jaeger, Tempo) tolerate this and render the child under the parent with a visual gap; others (certain OTLP-compatible SaaS collectors with strict ingestion windows) reject the late child as a "span for an already-completed trace" and drop it — at which point `gen_ai.usage.input_tokens` for the turn is undercounted and the tool call vanishes from the audit trail entirely. A second observed symptom: because `gen_ai.tool.call.id` is the correlation key the runtime uses to match the tool result back into the next `chat` prompt, an auditor reconstructing the turn from telemetry alone cannot verify that the tool result the model consumed corresponds to the tool span emitted — the linkage lives in `gen_ai.tool.call.id` on the tool span and in the prompt content of the next `chat` span, but the two spans are in different export batches and may be in different traces if the runtime used a fresh trace context for the follow-up turn. ## Condition of Validity The invariant that must hold: **for any `execute_tool` span, its `end_time` must be causally ordered before the `end_time` of every ancestor span in the same trace, and all ancestors must remain unexported until the descendant is enqueued.** This is trivially true in-process but false across the async export boundary. The invariant is valid only when one of the following holds: 1. The exporter is synchronous (`SimpleSpanProcessor`) — parent end blocks until child is handed to the transport. Cost: agent latency coupled to collector latency. 2. The runtime explicitly `force_flush()`es the `TracerProvider` before ending the agent span, and the flush is awaited. Cost: one round-trip per agent turn. 3. The runtime defers the parent `invoke_agent` span's `end()` until a `SpanProcessor.on_end` counter confirms all descendant tool spans have been enqueued and the batch containing them has been exported. This requires the runtime to track descendant span counts per trace, which the GenAI conventions do not mandate and most SDKs do not provide. 4. The collector is configured to accept late-arriving children for a completed trace (Tempo's `max_trace_idle` / Jaeger's `--query.max-clock-skew-adjustment`). This is a backend-side mitigation, not a runtime invariant, and it does not fix cost attribution — only visibility. If none hold, the invariant is violated and the failure is silent: no exception, no error span, no `status=ERROR`. The agent reports success; the telemetry reports a truncated trace. ## Decision Boundary The decision is whether to treat the GenAI tool-call span as a *child span* (trace-parent linkage, subject to export ordering) or as a *linked span* (`SpanLink` to the `chat` span, independent lifecycle). The conventions permit both; most instrumentation libraries default to child spans because it renders better in trace UIs. Choose child-span linkage only when invariant (1)–(3) above is enforced. Choose `SpanLink` when the tool executes in a separate process, a separate trace context (e.g., an MCP server with its own `TracerProvider`), or when the tool call is long-running and must not block the parent's export. With `SpanLink`, the tool span carries `gen_ai.tool.call.id` and a link back to the originating `chat` span, and correlation is by attribute join rather than by parent pointer — which survives arbitrary export reordering. The boundary is crossed the moment a tool span's expected duration exceeds the `BatchSpanProcessor` `schedule_delay_millis`, *or* the tool runs out-of-process, *or* the agent loop opens a new trace context for the follow-up turn. Any of these makes child-span linkage unsafe. ## Operational Effect Downstream consumers of GenAI telemetry — cost dashboards, tool-success SLOs, retry-attribution models, and any agent auditor replaying traces — depend on the parent-child join to attribute `gen_ai.usage.*` tokens and tool outcomes to the correct agent turn. When the join is broken by export reordering, the effects are: - **Cost undercount per turn**, because the tool span carrying `gen_ai.usage.input_tokens` for the tool-augmented turn is dropped or detached; aggregate cost across the trace remains correct only if the backend tolerates late children. - **Tool-success ratio inflation**, because dropped tool spans are absent from both numerator and denominator, and only the successful fast tools (which flush in-batch) are counted. - **Replay divergence**, because an auditor reconstructing the turn from spans sees a `chat` span whose prompt references a `tool_call.id` for which no tool span exists in the trace — indistinguishable from a hallucinated tool call, which is precisely the failure mode the telemetry was meant to detect. The guardrail is a runtime-level invariant, not a convention: the agent loop must either force-flush before closing the root span, or emit tool spans as `SpanLink`-ed siblings with an explicit `gen_ai.tool.call.id` correlation key, and the collector must be configured to accept late children. Absent this, the trace is a lossy projection of the agent's actual execution, and every metric derived from it inherits the loss silently. ```python from __future__ import annotations from dataclasses import dataclass, field class ToolSpanOrderingViolation(RuntimeError): """Raised when a tool-call span is enqueued after its ancestor agent span has been exported, violating the causal-ordering invariant required for GenAI trace attribution.""" @dataclass class SpanRecord: span_id: str parent_span_id: str | None operation: str start_ns: int end_ns: int exported: bool = False @dataclass class TraceBuffer: spans: dict[str, SpanRecord] = field(default_factory=dict) exported_roots: set[str] = field(default_factory=set) def end_span(self, span: SpanRecord) -> None: self.spans[span.span_id] = span if span.parent_span_id is None: # Root agent span ends; mark exported as if batch flushed. span.exported = True self.exported_roots.add(span.span_id) def enqueue_tool_span(self, tool: SpanRecord) -> None: parent = self.spans.get(tool.parent_span_id or "") if parent is None: raise ToolSpanOrderingViolation( f"tool span {tool.span_id} has no resolvable parent " f"{tool.parent_span_id}; trace context lost" ) # Walk to root to see if any ancestor already exported. cursor: SpanRecord | None = parent while cursor is not None: if cursor.exported and cursor.parent_span_id is None: raise ToolSpanOrderingViolation( f"tool span {tool.span_id} enqueued after root " f"{cursor.span_id} was exported; child would be orphaned " f"(start_ns={tool.start_ns}, root_end_ns={cursor.end_ns})" ) cursor = self.spans.get(cursor.parent_span_id or "") if tool.start_ns < parent.start_ns or tool.end_ns > parent.end_ns: raise ToolSpanOrderingViolation( f"tool span {tool.span_id} not temporally contained by parent " f"{parent.span_id}" ) self.spans[tool.span_id] = tool def close_agent_turn(buffer: TraceBuffer, root: SpanRecord, tool: SpanRecord) -> None: # Correct order: tool span enqueued and flushed before root ends. buffer.enqueue_tool_span(tool) buffer.end_span(root) if not buffer.spans[tool.span_id].exported: # Simulate force_flush contract. buffer.spans[tool.span_id].exported = True ```