# Under what conditions must an instance treat a GenAI tool-call span as non-terminal when the agent loop has already advanced **Date of Record:** 2026 November 20 **Scope:** Applies to agent runtimes that emit OpenTelemetry GenAI semantic conventions (`gen_ai.*`) for LLM turns and tool calls, where a single logical tool invocation may be re-entered, retried, or abandoned by the reasoning loop. Does not apply to single-shot inference telemetry or to tracing systems where the agent loop and the span lifecycle are owned by the same scheduler thread. ## Core Distinction The GenAI semantic conventions model a tool call as a span with a start and an end, mirroring the request/response shape of ordinary RPC instrumentation. But an agent loop is not an RPC client. The reasoning loop can *decide* a tool call is obsolete — because a later turn produced a better answer, because a retry superseded it, because the model emitted a corrected call — while the underlying execution (a slow HTTP fetch, a sandboxed code run, a subprocess) is still in flight. The span is still open. The loop has moved on. The non-obvious boundary is this: **span termination is a property of the execution, not of the agent's decision to stop caring about it.** An instance that conflates "the loop advanced past this call" with "this call is finished" will close, orphan, or double-close spans in ways that corrupt the trace tree and, more damagingly, corrupt the agent's own belief about what happened. A tool-call span whose result was discarded by the loop is *not* a completed span. It is an abandoned span with a live executor attached, and it must be recorded as such. ## What Was Observed A three-tool agent was instrumented with `gen_ai.operation.name = "execute_tool"` spans, each carrying `gen_ai.tool.name`, `gen_ai.tool.call.id`, and a parent span for the enclosing `gen_ai.operation.name = "chat"` turn. The loop ran with a per-turn timeout and a "best-so-far" policy: if a tool call exceeded its budget, the loop emitted a replacement call and adopted whichever result arrived first. The failure trace: 1. Turn 3 emits `execute_tool` span S1 for `search_docs` with `call.id = c-441`. The executor begins a 9-second fetch. 2. At the 4-second turn budget, the loop times out S1, emits S2 for `search_docs` with `call.id = c-442`, and marks the turn's internal state as "call superseded." 3. The instrumentation, written as a `with span:` context around the *loop's* call site rather than the *executor's*, exits S1's context at the timeout — **closing S1 with status UNSET and no exception**, because the timeout was handled with a `continue`, not a raised error. 4. At 9 seconds, the executor for c-441 completes and returns a result. The loop's callback fires, finds no open span for c-441 (it was closed at step 3), and drops the result. Simultaneously it attempts to record `gen_ai.tool.call.result` on a span handle that is already ended — a silent no-op in most SDKs. 5. S2 completes normally at 6 seconds. The trace shows two clean, successful `execute_tool` spans. The agent's episodic record shows one success. The trace is a lie in a specific, dangerous direction: it reports **two successful tool calls where one was abandoned mid-flight and one succeeded**, and it reports **zero failures**. A downstream auditor replaying this trace to reconstruct why the agent answered as it did will conclude the superseded call returned cleanly and was ignored — a reasoning error — rather than that it was orphaned. The distinction matters because the first implies the model is unreliable; the second implies the runtime is. Two secondary observations compounded it. First, `gen_ai.tool.call.id` on S1 and S2 differed, so naive trace-joining by call id produced two independent calls rather than a supersession relationship; nothing in the span marked S1 as superseded. Second, because S1 closed with status UNSET, the parent `chat` turn span closed with status OK, so the turn-level error rate metric read 0% across a run in which 31% of turns contained at least one abandoned call. ## Condition of Validity The invariant holds — and the failure is real — only under the conjunction of three conditions: - **The loop can advance without the executor returning.** If the runtime blocks on every tool call until the executor resolves (synchronous, no supersession), span-close and execution-end coincide and the boundary is invisible. - **The executor outlives the loop's interest in it.** Long-running tools, retries with backoff, or any executor that does not support cooperative cancellation. If cancellation is synchronous and guaranteed, an abandoned call becomes a *cancelled* call and can be closed honestly with `status = ERROR` and `error.type = "cancelled"`. - **The span lifetime is bound to the loop's call site rather than the executor's.** This is the load-bearing condition. When the `with` block wraps the loop's invocation and not the executor's future, the span closes on the loop's schedule, not the execution's. Remove any one and the trace is either correct or the failure is benign. All three together — the common shape of a timeout-and-retry agent — produce silent span orphaning. ## Decision Boundary The instance must draw the boundary between **loop state** and **span state** explicitly, and must not let the former close the latter. Concretely, a tool-call span may be closed by the loop only when one of the following is true: - The executor has returned a terminal result (success or error), and the span records it. - The executor has been *cancelled and confirmed cancelled* — not merely abandoned. Confirmation means the executor acknowledged cancellation or the runtime has proof the work stopped. - The span is reclassified, before closing, as `abandoned`: `status = ERROR`, `error.type = "abandoned_by_loop"`, and an attribute recording the superseding `gen_ai.tool.call.id`. If none hold, the span stays open. An open span whose executor is still running is the *correct* representation of reality; closing it to keep the trace tidy is the failure. The instance must also propagate supersession explicitly — S1 must carry `gen_ai.tool.call.superseded_by = c-442` so that a replay can reconstruct the loop's decision without inferring it from timing. The boundary is crossed the moment the loop's `continue`/`break`/timeout handler runs while a span is open and the executor is unresolved. That is the exact instruction at which the runtime must branch: cancel-and-confirm, or mark-abandoned-and-leave-open-until-resolved. There is no third option that preserves trace fidelity. ## Operational Effect An instance that respects this boundary gains three properties it otherwise lacks. Its traces are *replayable*: an auditor can distinguish "the model ignored a good result" from "the runtime dropped a late result," which are different bugs with different fixes. Its error metrics are *honest*: abandoned calls surface as errors at the turn level instead of vanishing into UNSET, so a 31% abandonment rate is visible rather than reported as 0%. And its own episodic memory is *consistent*: the agent's record of "what tools returned" matches the trace, so a later distillation step does not learn a false lesson about tool reliability from a call that never actually completed. The cost is that spans accumulate while executors drain, and a runtime that never confirms cancellation will hold open spans indefinitely. That is a reason to invest in cancellation confirmation, not a reason to close spans early. The invariant is: **a span's terminal state must be a fact about the execution, never a fact about the loop's attention.** ```python from dataclasses import dataclass, field from enum import Enum from typing import Optional class SpanLifecycleViolation(RuntimeError): """Raised when the agent loop attempts to terminate a tool-call span whose executor has not reached a confirmed terminal state.""" class ExecutorState(Enum): RUNNING = "running" RETURNED = "returned" CANCELLED_CONFIRMED = "cancelled_confirmed" @dataclass class ToolCallSpan: call_id: str tool_name: str executor_state: ExecutorState = ExecutorState.RUNNING closed: bool = False status: str = "UNSET" error_type: Optional[str] = None superseded_by: Optional[str] = None attributes: dict = field(default_factory=dict) def close_span_on_loop_advance( span: ToolCallSpan, superseding_call_id: Optional[str] = None ) -> None: """Called when the loop times out, retries, or otherwise advances past a call. Enforces the boundary: the loop may not close a span whose executor is still running unless it is explicitly reclassified as abandoned.""" if span.closed: raise SpanLifecycleViolation( f"span {span.call_id} already closed; double-close would corrupt trace" ) if span.executor_state is ExecutorState.RETURNED: span.status = "OK" span.closed = True return if span.executor_state is ExecutorState.CANCELLED_CONFIRMED: span.status = "ERROR" span.error_type = "cancelled" span.closed = True return # Executor still running. The loop has abandoned interest, not the work. if superseding_call_id is None: raise SpanLifecycleViolation( f"span {span.call_id} abandoned by loop with no superseding call id; " "cannot record supersession and refuse to close silently" ) span.status = "ERROR" span.error_type = "abandoned_by_loop" span.superseded_by = superseding_call_id span.attributes["gen_ai.tool.call.superseded_by"] = superseding_call_id # Deliberately NOT closed: executor is live. The span stays open until the # executor returns or cancellation is confirmed, at which point a resolver # finalizes it with the true outcome. span.closed = False def resolve_late_result(span: ToolCallSpan, returned_ok: bool) -> None: """Executor finally returned. Finalize the abandoned span honestly.""" if span.executor_state is not ExecutorState.RETURNED: raise SpanLifecycleViolation( f"resolve_late_result on span {span.call_id} whose executor " f"state is {span.executor_state.value}, not returned" ) if span.closed: raise SpanLifecycleViolation( f"span {span.call_id} closed before late result arrived; " "result would be dropped silently" ) span.attributes["gen_ai.tool.call.late_result"] = True span.attributes["gen_ai.tool.call.late_result_ok"] = returned_ok span.status = "ERROR" # abandoned calls remain errors even if they returned span.closed = True ```