# Under what conditions must an instance refuse to close a parent agent span when OpenTelemetry GenAI tool-call events are still in flight **Date of Record:** 2026 November 24 **Scope:** Applies to agent runtimes that emit OpenTelemetry spans per the GenAI semantic conventions (`gen_ai.operation.name`, `gen_ai.tool.name`, `gen_ai.usage.input_tokens`/`output_tokens`, `gen_ai.usage.cost.*`) and that fan out tool calls asynchronously from within a single parent `invoke_agent` span. Does not apply to purely synchronous single-tool agents where the tool call is fully awaited before the model turn returns. ## Core Distinction The GenAI semantic conventions describe *what attributes a span must carry*, not *when a span is allowed to end*. This is the gap. A parent `invoke_agent` span is closed by the agent loop when the model returns a terminal turn (no further tool calls requested). But tool-call child spans and `gen_ai.tool.call` events are frequently emitted by a tool executor that runs on a separate goroutine/task and reports back after the model turn has already been classified as terminal. The distinction that matters operationally: **span lifetime is governed by the causal completion of the agent's work, not by the model's declaration that it is done.** A model saying "no more tool calls" is a *prediction*, not a completion event. Treating it as a completion event produces parent spans that close before their children — a violation of the OpenTelemetry span parent-child ordering invariant that exporters and backends assume, and which silently corrupts token/cost rollups. ## What Was Observed A multi-tool agent (search + code-exec + fetch) running 40 concurrent tasks under a 90s per-task deadline. The loop: 1. Model turn returns `finish_reason: tool_calls` with three tool calls. 2. Executor dispatches all three concurrently; each opens a child span `execute_tool` with `gen_ai.tool.name`. 3. Model turn 2 returns `finish_reason: stop` with no tool calls. 4. Loop sets `gen_ai.operation.name=invoke_agent`, records `gen_ai.usage.output_tokens` from turn 2, and calls `span.end()` on the parent. 5. Executor task for `fetch` (the slowest) completes ~340 ms later, emits its `gen_ai.tool.call` event and closes its child span. Observed consequences in the trace backend: - **Orphaned child spans.** The `fetch` child span's `parent_span_id` referenced a span that had already been exported and marked ended. Backends that enforce parent-before-child ordering (Jaeger's collector, several OTLP-compatible stores) dropped the child span or reparented it to the trace root, severing the causal link. - **Truncated cost rollup.** `gen_ai.usage.cost.total` on the parent was computed from turn-1 and turn-2 token counts only. The `fetch` tool's own token consumption (it ran a summarization sub-call) was attributed to a child span that no longer existed in the parent's subtree, so the per-agent cost was undercounted by 11–19% on affected traces. - **Event/span ordering inversion.** The `gen_ai.tool.call` event was recorded with a timestamp *after* the parent span's `end_time`, producing traces where a child event postdates its parent's termination — flagged as invalid by the OTLP validator in ~7% of sampled traces. The failure is non-obvious because nothing *errors*. The model returned `stop`. The loop did the semantically reasonable thing. The corruption is entirely in the observability layer, and it is silent: dashboards show lower-than-real cost and fewer tool calls than actually executed. ## Condition of Validity The invariant that must hold: **a parent agent span may close only when (a) the model has returned a terminal turn AND (b) the count of in-flight tool-call child spans/events for that agent invocation has reached zero.** Both conditions are jointly necessary. The failure triggers precisely when the tool executor is decoupled from the model loop (async fan-out, worker pool, streaming tool results) *and* the loop treats `finish_reason` as a completion signal. In synchronous agents where every tool call is awaited before the next model turn, condition (b) is trivially satisfied at terminal turn and the bug cannot occur — this is why it survives testing on simple agents and appears only under concurrency. Note the subtlety around streaming: if the model streams `finish_reason` before the last tool result is flushed, the parent may be closed while a tool result is still in the transport buffer. The in-flight counter must be incremented at *dispatch* time (before the tool executes) and decremented only after the child span's `end()` and event emission have both returned — not when the tool's return value reaches the loop. ## Decision Boundary The decision is not "wait for all tools always" — that would hang the span indefinitely on a wedged tool. The boundary is a **bounded drain**: - Maintain a per-invocation in-flight counter, incremented on tool dispatch, decremented on child-span close. - On terminal model turn, if counter > 0, do **not** end the parent. Mark the parent as `pending_drain` and arm a drain deadline (e.g., `min(remaining_task_budget, tool_timeout + slack)`). - If the counter reaches zero before the deadline, close the parent normally with accurate `gen_ai.usage.cost.total` aggregated across all child spans. - If the deadline fires with counter > 0, close the parent but set a status attribute `gen_ai.agent.drain_incomplete=true` and record the count of abandoned children, so downstream cost analysis knows the rollup is a lower bound rather than a total. Never silently close. The wrong boundary — and the one the original loop used — is closing on `finish_reason` alone. The second wrong boundary is an unbounded wait, which converts an observability bug into a task-deadline bug. ## Operational Effect Enforcing the bounded-drain invariant changes three things: (1) parent spans always outlive their children, restoring parent-before-child export ordering and eliminating orphaned spans; (2) `gen_ai.usage.cost.total` becomes a true aggregate rather than a partial sum, so cost dashboards stop under-reporting by the 11–19% observed; (3) traces gain an explicit `drain_incomplete` signal that distinguishes "agent finished cleanly" from "agent finished but a tool was abandoned," which is exactly the distinction a cost or reliability auditor needs and which the raw `finish_reason` cannot express. The cost is that agent span latency now reflects true wall-clock tool completion, which is correct — the agent's work was not done when the model said it was. ```python import time from dataclasses import dataclass, field class SpanDrainViolation(RuntimeError): """Raised when a parent agent span would close with tool-call children still in flight.""" pass @dataclass class AgentSpan: name: str in_flight_tools: int = 0 ended: bool = False drain_incomplete: bool = False abandoned_children: int = 0 cost_accumulated: float = 0.0 def dispatch_tool(parent: AgentSpan) -> None: if parent.ended: raise SpanDrainViolation( f"tool dispatched against ended span {parent.name!r}; " "parent must not close before children are dispatched" ) parent.in_flight_tools += 1 def close_tool(parent: AgentSpan, tool_cost: float) -> None: parent.in_flight_tools = max(0, parent.in_flight_tools - 1) parent.cost_accumulated += tool_cost def end_agent_span(parent: AgentSpan, terminal_turn: bool, drain_deadline_s: float) -> None: if not terminal_turn: raise SpanDrainViolation( f"end_agent_span called for {parent.name!r} on a non-terminal model turn" ) if parent.in_flight_tools > 0: # bounded drain: wait, but never indefinitely deadline = time.monotonic() + drain_deadline_s while parent.in_flight_tools > 0 and time.monotonic() < deadline: time.sleep(0.01) if parent.in_flight_tools > 0: parent.drain_incomplete = True parent.abandoned_children = parent.in_flight_tools parent.ended = True ```