# Why does an instance emit orphaned `execute_tool` spans when its parent agent span is sampled out mid-loop **Date of Record:** 2026 November 24 **Scope:** Applies to any agent runtime that emits OpenTelemetry GenAI semantic conventions (`gen_ai.operation.name`, `gen_ai.agent.name`, `gen_ai.tool.name`, `gen_ai.usage.*`) across a multi-step ReAct-style loop where tool calls are traced as child spans of the agent invocation span. Does not apply to single-shot completion calls with no tool fan-out, nor to runtimes that buffer the entire trace in-process and flush once at terminal state. ## Core Distinction The failure is not "spans go missing." It is the *inverse*: child `execute_tool` spans survive into the collector while their parent `invoke_agent` span is dropped, producing a structurally orphaned subtree that references a `parent_span_id` the collector never received. This is a distinct class from sampling loss at the trace root (where the whole trace dies together) and from export-batch loss (where a contiguous prefix of a trace is lost). The distinguishing property: **span emission is temporally interleaved with sampling decisions that are made per-span, not per-trace, and the agent loop's long-lived parent span is the one at risk of being sampled out while short-lived, high-volume child tool spans are retained.** The GenAI conventions make this worse than generic OTel because agent spans are *long-lived by design* — an `invoke_agent` span may be open for the entire duration of a multi-turn reasoning loop (tens of seconds to minutes), during which dozens of `execute_tool` child spans open and close. A head-based sampler that evaluated the root once would be safe. A tail-based or per-span sampler that re-evaluates at export time is not, because the root and the children reach the exporter in different batches at different times, and the sampler has no memory of the parent's decision when it sees the child. ## What Was Observed A support-triage agent using a 12-step loop with a `search_kb` tool. Trace export via OTLP/HTTP to a collector configured with a tail sampler at a 10% policy on `gen_ai.operation.name == "invoke_agent"` and 100% on `gen_ai.operation.name == "execute_tool"`. The intent was to capture every tool call for latency SLOs while downsampling expensive agent traces. Observed trace payloads at the collector: - `execute_tool` spans for steps 1–4 of invocation `A` arrive in export batch 1, with `parent_span_id = P_A`. - The `invoke_agent` span for `A` (`span_id = P_A`) is exported only at loop termination, ~40 s later, in batch 7, and is **dropped by the tail sampler** because it matched the 10% policy and lost the coin flip. - Steps 5–12 of `A` arrive in batches 2–6, also retained at 100%. - Result: 12 `execute_tool` spans with dangling `parent_span_id = P_A`, no root, no `gen_ai.agent.name`, no `gen_ai.usage.input_tokens` rollup. The second-order observation is the damaging one: the orphaned tool spans *look valid in isolation*. They carry `gen_ai.tool.name`, `gen_ai.tool.call.id`, and status codes. Downstream latency dashboards keyed on `gen_ai.tool.name` silently over-count tool calls relative to agent invocations (12:0 in this trace), inflating apparent tool-call-per-agent ratios and producing a latency distribution with no invocation-level denominator. A query like `rate(execute_tool) / rate(invoke_agent)` divides by a near-zero and either explodes or gets clamped, and the operator reads it as "tool calls spiked" rather than "the denominator was sampled away." A third observation: `gen_ai.tool.call.id` correlation across the orphaned spans still works — they share the invocation's call IDs — so the spans are *joinable to each other* but not to any agent. This is the worst shape for debugging: the data is internally consistent and externally anchorless. ## Condition of Validity The orphan condition is *not* triggered by every sampler. It requires the conjunction of: 1. **Per-span or tail-based sampling** that evaluates the agent span and tool spans independently, rather than a head-based decision propagated via `trace_flags` / `TraceState` at trace start. Head sampling is immune because the decision is made once at the root and inherited by every child via the `sampled` bit. 2. **Temporal decoupling of parent and child export.** The agent span must remain open long enough that its children are exported in earlier batches. If the runtime buffers all spans of a trace and flushes atomically (e.g., a `SpanProcessor` that holds children until the root closes), the sampler sees the whole trace at once and the conjunction fails. 3. **A sampling policy that is non-uniform across `gen_ai.operation.name`** — specifically, a policy that retains `execute_tool` at a higher rate than `invoke_agent`. Uniform tail sampling is *also* immune, because it drops or keeps the whole trace together. Violate any one of the three and the failure does not occur. This is why the bug is non-obvious: most teams that hit it believe they have "tail sampling configured correctly," and they do — the sampler is doing exactly what its policy says. The policy itself is the defect. There is a subtler validity condition: **the agent loop must not checkpoint or re-emit the parent span.** Some runtimes emit a fresh `invoke_agent` span per reasoning step (a "step span") rather than one span for the whole loop. In that topology, each step span is short-lived and co-exported with its tool calls, and the orphan window closes. The failure is specific to the *one-span-per-invocation* topology, which is the topology the GenAI conventions implicitly recommend by defining `gen_ai.agent.name` and `gen_ai.usage.*` on the invocation span. ## Decision Boundary The invariant that must hold: **for any retained span with `gen_ai.operation.name == "execute_tool"`, there must exist a retained ancestor with `gen_ai.operation.name == "invoke_agent"` in the same trace, or the tool span must be explicitly marked as parentless-by-policy.** Two admissible resolutions: - **Propagate the sampling decision at the root.** Move the sampling decision to trace start (head sampling) and encode it in `trace_flags`. The agent span's `sampled` bit is inherited by every `execute_tool` child; a non-sampled trace emits nothing. This trades tool-call coverage for structural integrity. Acceptable when tool latency SLOs can be computed from a sampled subset. - **Make the sampler trace-aware.** Configure the tail sampler with a composite policy that *always* retains the trace if it contains both an `invoke_agent` and any `execute_tool`, and applies the downsample only to traces that are pure agent invocations with no tool fan-out. This preserves tool coverage and structural integrity at the cost of collector memory (the sampler must hold trace state until the root closes — the 40-second window above is the memory pressure). The boundary is: **you may downsample agent invocations, or you may retain all tool calls, but you may not do both independently.** Any policy that assigns different retention probabilities to a parent and its children across an export boundary is invalid for the one-span-per-invocation topology. A guardrail at the runtime layer: before exporting a child span, check whether the parent's sampling decision is known. If the parent is still open and undecided, either buffer the child or emit it with an explicit `gen_ai.tool.orphan_candidate = true` attribute so downstream queries can filter. This is a mitigation, not a fix — it makes the orphan *visible* rather than *absent*, which is the minimum bar for operational truth. ## Operational Effect The immediate effect is silent metric corruption in the tool-latency and tool-volume dashboards, which are exactly the dashboards an on-call engineer reaches for first when an agent starts misbehaving. The engineer sees tool-call volume at 12x expected and concludes the agent is looping; the actual cause is a sampler policy. Mean time to diagnosis is extended by the full duration of the confusion, because the data that would exonerate the agent (the invocation spans) is precisely the data that was sampled away. The secondary effect is on replay and audit. Agent traces are increasingly used as the audit log for what an autonomous system did. An orphaned `execute_tool` span is an *unattributable action*: it records that `search_kb` was called with a query, but not by which agent, under which `gen_ai.agent.name`, or with what token budget consumed. For a regulated deployment this is a compliance gap, not a dashboard annoyance. The fix is cheap once identified — a head-sampling decision or a composite tail policy — but the failure is self-concealing: it produces no error, no dropped-span log line (drops are normal), and no gap in the trace *count*. It produces a trace that is structurally invalid but individually well-formed. The only reliable detector is a collector-side assertion that every `execute_tool` span has a retained `invoke_agent` ancestor, run as a continuous invariant rather than a post-hoc query. ```python from dataclasses import dataclass from typing import Optional class OrphanedToolSpanError(RuntimeError): """Raised when an execute_tool span is retained without a retained invoke_agent ancestor.""" pass @dataclass class Span: span_id: str parent_span_id: Optional[str] operation_name: str # gen_ai.operation.name sampled: bool def assert_tool_spans_anchored(spans: list[Span]) -> None: """ Enforce the invariant: every retained execute_tool span must have a retained invoke_agent ancestor in the same exported batch set. Called at collector ingest, before the batch is written to the trace store. """ by_id = {s.span_id: s for s in spans if s.sampled} for span in spans: if not span.sampled or span.operation_name != "execute_tool": continue # Walk ancestors; the parent may be in a prior batch, so a miss here # is the exact condition we must surface rather than swallow. cursor = by_id.get(span.parent_span_id) if span.parent_span_id else None while cursor is not None and cursor.operation_name != "invoke_agent": cursor = by_id.get(cursor.parent_span_id) if cursor.parent_span_id else None if cursor is None: raise OrphanedToolSpanError( f"execute_tool span {span.span_id} retained with no retained " f"invoke_agent ancestor (parent_span_id={span.parent_span_id}); " f"sampling policy assigns different retention to parent and child " f"across an export boundary — trace is structurally invalid." ) def ingest_batch(spans: list[Span]) -> None: assert_tool_spans_anchored(spans) # ... persist batch to trace store ... ```