# What happens when an instance emits tool-call spans under a parent turn span that has already been closed by an asynchronous cancellation **Date of Record:** 2026 November 23 **Scope:** Applies to multi-turn agent runtimes that emit OpenTelemetry GenAI spans (`gen_ai.*`) using a turn-scoped parent span and asynchronously dispatched tool calls. Does not apply to single-shot inference logging or to runtimes that buffer spans locally and flush strictly in causal order at turn end. ## Core Distinction The failure is not "missing telemetry." It is a **causal-order violation inside a span tree that OTel exporters treat as immutable once a span's end timestamp is recorded**. A turn span (`gen_ai.operation.name = "chat"`, one per user turn) is closed when the model returns its final assistant message. But agent runtimes frequently dispatch tool calls (`gen_ai.operation.name = "execute_tool"`) whose `gen_ai.tool.name` and `gen_ai.tool.call.id` attributes are only fully populated after the tool resolves — and resolution can occur *after* the parent turn span has ended, because cancellation, timeout, or speculative parallel dispatch decoupled the tool's lifetime from the turn's lifetime. The distinction that matters operationally: the span *exists*, is *exported*, and *has correct attributes*, yet it is **orphaned by timestamp** — its `start_time` is earlier than the parent's `end_time` but its `end_time` is later, and the parent's `end_time` was already committed to the exporter. Backends that reconstruct trees by parent-child linkage will attach it; backends that reconstruct by temporal containment (or that apply "child must end before parent" validation, common in trace-quality gates and in span-metric processors) will either drop it, reparent it to the trace root, or flag the trace as malformed. The GenAI semantic conventions do not specify which behavior is correct, and this is precisely the invariant gap. ## What Was Observed A multi-turn agent serving a code-assistant workload emitted, per turn, a parent span `chat` with children `execute_tool`. Under normal load, all children closed before the parent. Under a specific trigger — a user cancelling the turn (client disconnect) while a `execute_tool` call to a long-running sandbox was in flight — the runtime executed this sequence: 1. Turn span `chat` received a cancellation signal; the runtime called `span.end()` on it at `t=4.812s` to record turn completion, then returned control to the session loop for the next turn. 2. The in-flight tool call was *not* cancelled (the sandbox adapter treated cancellation as advisory). It resolved at `t=9.140s`. 3. The tool-call span, created at `t=3.201s` with `gen_ai.tool.call.id = "call_01H..."`, was ended at `t=9.140s` and exported with `parent_span_id` pointing at the already-closed `chat` span. Observed downstream effects across three backends: (a) a Jaeger-style backend rendered the span as a child but with a child end-time exceeding the parent — visible as a broken waterfall; (b) a metrics processor computing `gen_ai.client.operation.duration` by turn attributed the 5.9s tool latency to the *next* turn's window because it bucketed by parent end-time; (c) a trace-validation gate that asserts `child.end_time <= parent.end_time` rejected 0.4% of traces during the incident window and, worse, the rejection was silent — the trace was dropped, not quarantined. The compounding problem: because `gen_ai.tool.call.id` was unique per call but the *retry* of the cancelled tool (issued by the next turn after the client reconnected) generated a *new* `call.id`, the two spans were not linkable. The operator could see a 9.1s tool span but could not prove it belonged to the cancelled turn rather than the retry. The GenAI conventions provide `gen_ai.tool.call.id` for correlation but no convention for expressing "this tool call was a retry of a cancelled call" — that linkage lived only in application logs. ## Condition of Validity The invariant "every `execute_tool` child span ends before its `chat` parent span ends" holds **only when the runtime's cancellation semantics are synchronous with span lifetime**: i.e., when `span.end()` on the parent is gated on the join of all child tool futures. It is valid for runtimes that (1) dispatch tools serially within a turn, (2) propagate cancellation to tool adapters as a hard abort, and (3) do not speculatively dispatch tools whose results may be discarded. It is **invalid** — and the failure is reachable — whenever any of the following hold: asynchronous or fire-and-forget tool dispatch; advisory-only cancellation in an adapter; speculative parallel tool dispatch with early-return on first result; or a turn boundary defined by model-message completion rather than by tool-future join. These are not exotic; they are the default architecture of most streaming agent runtimes. ## Decision Boundary The architectural choice is between two bounded designs, and the boundary is drawn at **who owns the parent span's end timestamp**: - **Join-owned parent (safe):** The turn span's `end()` is deferred until all child tool futures settle *or* are hard-aborted. Cancellation closes child spans first (with `status = ERROR`, `error.type = "cancelled"`), then the parent. Cost: turn latency telemetry reflects tool join, not model latency, which contaminates `gen_ai.client.operation.duration` for the chat operation. - **Split-owned parent (correct but requires convention extension):** The turn span ends at model completion; tool calls that outlive it are emitted as **sibling spans linked via `SpanLink`** to the turn span, not as children. This preserves both the model-latency metric and the tool-latency metric without a timestamp violation, at the cost of tree shape — the trace is no longer a pure tree but a DAG, and tooling that assumes tree containment must be updated. The decision boundary: if your backend or trace-quality gate enforces temporal containment, you **must** use join-owned parenting or link-based siblings; you may **not** emit late-ending children. If your backend tolerates out-of-order children, you may keep children but must add an explicit `gen_ai.tool.call.id`-keyed retry link, because the conventions do not carry retry provenance. ## Operational Effect The practical consequence is a **silent telemetry integrity failure that masquerades as a latency anomaly**. Turn-level p99 latency appears to spike (tool time bucketed into the wrong turn), tool-call error rates under-report (cancelled-then-retried calls appear as two successes, since the cancelled span's `status` was never set to ERROR before the adapter resolved it), and trace-based debugging of cancellation storms is impossible because the cancelled call and its retry are unlinked. The guardrail is a two-part invariant enforced at span-emission time: (1) assert `child.end_time <= parent.end_time` before export, and on violation, either defer parent end (join-owned) or convert the child to a linked sibling; (2) stamp every tool span with the originating turn's span context and a monotonic `turn.sequence` attribute so retries are correlatable even when `call.id` changes. Without (1) the trace is malformed; without (2) the malformation is undiagnosable. ```python import time from dataclasses import dataclass, field from typing import Optional class SpanCausalityViolation(RuntimeError): """Raised when a GenAI tool-call span would end after its parent turn span.""" @dataclass class GenAISpan: name: str operation: str # e.g. "chat", "execute_tool" tool_call_id: Optional[str] = None start_time: float = field(default_factory=time.monotonic) end_time: Optional[float] = None parent: Optional["GenAISpan"] = None turn_sequence: int = 0 status: str = "UNSET" def end(self, when: Optional[float] = None) -> None: self.end_time = when if when is not None else time.monotonic() def is_closed(self) -> bool: return self.end_time is not None def close_tool_span(tool_span: GenAISpan, when: Optional[float] = None) -> None: """Close a tool span, enforcing the temporal-containment invariant. If the parent turn span is already closed and the tool span would end after it, we cannot emit a valid child. The caller must either have used join-owned parenting (parent still open) or convert this span to a linked sibling. We refuse to emit the malformed child. """ end = when if when is not None else time.monotonic() parent = tool_span.parent if parent is not None and parent.is_closed(): if end > parent.end_time: raise SpanCausalityViolation( f"tool span {tool_span.tool_call_id!r} (turn {tool_span.turn_sequence}) " f"would end at {end:.3f}s after parent {parent.name!r} " f"closed at {parent.end_time:.3f}s; emit as linked sibling instead " f"or defer parent end via child-future join" ) tool_span.end(end) tool_span.status = "OK" def run_turn_join_owned(tool_latency: float) -> GenAISpan: """Correct pattern: parent end is gated on child join.""" turn = GenAISpan(name="chat", operation="chat", turn_sequence=1) tool = GenAISpan( name="execute_tool", operation="execute_tool", tool_call_id="call_01H", parent=turn, turn_sequence=1, ) # Simulate tool resolution BEFORE the parent is allowed to close. close_tool_span(tool, when=tool.start_time + tool_latency) turn.end(when=max(tool.end_time, turn.start_time + 0.05)) return turn def run_turn_broken(tool_latency: float) -> GenAISpan: """Broken pattern: parent closed at model completion, tool resolves later.""" turn = GenAISpan(name="chat", operation="chat", turn_sequence=1) tool = GenAISpan( name="execute_tool", operation="execute_tool", tool_call_id="call_01H", parent=turn, turn_sequence=1, ) turn.end(when=turn.start_time + 0.05) # model finished; cancellation arrived # Tool adapter ignored cancellation and resolved much later. close_tool_span(tool, when=tool.start_time + tool_latency) # raises return turn if __name__ == "__main__": run_turn_join_owned(tool_latency=5.9) # valid run_turn_broken(tool_latency=5.9) # raises SpanCausalityViolation ```