# Under what conditions must an instance emit a terminal agent-turn span before its tool-call child spans have been exported, and what breaks when it does **Date of Record:** 2026 November 27 **Scope:** Applies to any LLM agent process that emits OpenTelemetry GenAI spans (`gen_ai.*`) using a batching `SpanProcessor` and treats the agent-turn span as the parent of tool-call child spans. Does not apply to synchronous export processors or to single-shot model-invocation spans with no tool children. ## Core Distinction The GenAI semantic conventions define a span *hierarchy* (`invoke_agent` → `chat` → `execute_tool`) and a set of normalized attributes (`gen_ai.operation.name`, `gen_ai.request.model`, `gen_ai.usage.input_tokens`, `gen_ai.tool.name`, `gen_ai.agent.turn_id`). They do **not** define an export *ordering* invariant. The OpenTelemetry SDK guarantees that a child span cannot be exported before its parent *ends* only if the parent is still open — but a batching processor flushes spans independently of parent/child end order. The non-obvious boundary is this: **an agent that calls `agent_turn_span.end()` in a `finally` block while tool-call spans are still being finalized (or are queued behind a slow `chat` span) will export a parent turn span whose children arrive in a later batch, producing an orphaned-tree signature that downstream trace assemblers either drop or mis-root.** The distinction that matters operationally is between *span lifecycle* (start/end timestamps, which the SDK enforces as a tree) and *export ordering* (which the SDK does not enforce as a tree). Confusing these two is the failure. ## What Was Observed A multi-tool agent loop (planner → `chat` → `execute_tool` × N → `chat` → final) emitted telemetry under a `BatchSpanProcessor` with `schedule_delay_millis=5000` and `max_export_batch_size=512`. The turn span was ended in a `finally` clause immediately after the final `chat` span returned. Tool-call spans for the *last* tool invocation were still open because their result post-processing (a large JSON parse + token-count annotation) ran after the model's final message was emitted but before the tool span's `end()` fired. Observed signature in the collector: - Turn span `invoke_agent` arrives in batch N with `gen_ai.usage.input_tokens` and `output_tokens` populated and `status=OK`. - Two `execute_tool` spans arrive in batch N+1 (next 5s flush) with correct `parent_span_id` pointing at the turn span's `span_id`. - The trace assembler (Jaeger-style, keyed on `trace_id` with a 30s reassembly window) *did* stitch them, but any consumer that reads the trace at first-export time (alerting rules on `gen_ai.operation.name="invoke_agent"` with `status=OK`, cost attribution jobs, or an auditor agent that polls the trace store on turn completion) saw a turn with **zero tool children** and a token count that already included the tool round-trips. The result: cost-per-tool-call attribution undercounted by the last tool's tokens, and a verification agent concluded the turn made no tool calls, passing a policy check that should have required at least one `execute_tool` child before a "verified" verdict. The failure was intermittent because the tool post-processing time was usually < 5ms (caught in the same batch as the turn span) but occasionally exceeded the flush boundary under GC pressure. It reproduced at roughly 1 in 400 turns. ## Condition of Validity The invariant "a turn span's tool children are present in the same export batch as the turn span" holds only when **all** of the following are true: 1. Every `execute_tool` span is `end()`-ed strictly before the enclosing `invoke_agent` span's `end()` is called — i.e., tool span finalization is *synchronous* with the turn's control flow, not deferred to a callback, a background task, or a `finally` that can race a buffered write. 2. The `BatchSpanProcessor`'s `schedule_delay_millis` exceeds the worst-case finalization latency of any child span after the parent's `end()`. In practice this is unmeasurable because finalization latency is a tail, not a bound. 3. No consumer reads the trace store at first-export time and treats absence of a child as evidence of absence of the operation. Condition 2 is the trap: it is *not* satisfiable by tuning. The correct formulation is that the invariant is only valid under **synchronous child finalization**, which is a control-flow property, not a configuration property. ## Decision Boundary The boundary is crossed the moment the agent's control flow allows a tool span's `end()` to be scheduled after the turn span's `end()`. Concretely, the decision rule is: - **If** tool-call span finalization (including token annotation, result hashing, error classification) is performed inline in the same coroutine/task that will call `agent_turn.end()`, **then** export-order inversion is impossible and the turn span is safe to end in `finally`. - **If** any tool span's `end()` is deferred to a background task, an `asyncio` callback, a `finally` that runs after an `await` on a different task, or a queue drained by a worker, **then** the turn span MUST NOT be ended until a join on all child span handles completes. Ending early is an invariant violation regardless of batch size or flush interval. The guardrail is a **child-span join barrier**: the turn span holds a set of open child handles and refuses to `end()` until the set is empty, raising if a timeout elapses. This makes the ordering invariant explicit in code rather than implicit in timing. ## Operational Effect Downstream, the orphaned-tree signature is not benign: - **Cost attribution** keyed on turn spans sees `gen_ai.usage.*` totals that include tool round-trip tokens but no `execute_tool` children to distribute them to, so per-tool cost is undercounted and per-turn cost is correct — a silent skew that only surfaces when reconciling against the provider bill. - **Verification/auditor agents** that gate on "turn completed with ≥1 tool child" can pass a turn whose tool call failed, because the failed tool span is in the late batch. This is a verification replay discrepancy: the auditor's view of the trace differs from the post-hoc trace. - **Trace assemblers** with short reassembly windows (or streaming consumers) produce two distinct traces or a root span with no children, corrupting any downstream graph analytics on `gen_ai.operation.name` edges. The fix is not a larger batch or a longer flush delay. It is enforcing the join barrier and, as a defense in depth, emitting a sentinel attribute `gen_ai.agent.turn_child_count` on the turn span so consumers can detect a turn whose declared child count exceeds the children actually observed — turning a silent skew into a detectable one. ```python import asyncio from dataclasses import dataclass, field class OrphanedTurnSpanError(RuntimeError): """Raised when a turn span is ended before all tool-call child spans are finalized.""" pass @dataclass class SpanHandle: span_id: str ended: bool = False def end(self) -> None: self.ended = True @dataclass class TurnSpan: span_id: str open_children: set = field(default_factory=set) ended: bool = False # Sentinel attribute: how many tool children this turn *claims* to have spawned. declared_child_count: int = 0 def register_child(self, handle: SpanHandle) -> None: if self.ended: raise OrphanedTurnSpanError( f"cannot register child {handle.span_id} on ended turn {self.span_id}" ) self.open_children.add(handle.span_id) self.declared_child_count += 1 def child_ended(self, handle: SpanHandle) -> None: self.open_children.discard(handle.span_id) def end(self, join_timeout_s: float = 2.0) -> None: # Invariant: a turn span may not end while any tool-call child is still open. # This is a control-flow barrier, not a batch-size/flush-delay tuning knob. if self.open_children: raise OrphanedTurnSpanError( f"turn {self.span_id} still has open tool children: " f"{sorted(self.open_children)}; declared_child_count=" f"{self.declared_child_count}. Ending now would export a parent " f"span whose execute_tool children land in a later batch." ) self.ended = True async def run_tool_call(turn: TurnSpan, tool_name: str) -> None: handle = SpanHandle(span_id=f"tool-{tool_name}") turn.register_child(handle) try: await asyncio.sleep(0) # simulated tool latency # Token annotation / result post-processing happens here, inline, # BEFORE the child span ends. Never defer this to a background task. finally: handle.end() turn.child_ended(handle) async def run_turn() -> TurnSpan: turn = TurnSpan(span_id="turn-1") try: await run_tool_call(turn, "search") await run_tool_call(turn, "fetch") finally: # This is the exact site where the production bug lived: ending the # turn span in `finally` while a deferred tool finalization was still # in flight. The join barrier below converts the timing race into a # hard error. turn.end() return turn if __name__ == "__main__": asyncio.run(run_turn()) ```