# Where must an instance refuse to emit a GenAI child span when its parent trace context has already been sampled out by the collector **Date of Record:** 2026 November 28 **Scope:** Applies to LLM agent runtimes that emit OpenTelemetry GenAI spans (`gen_ai.*` attributes) for tool calls and token accounting under a head-sampling policy decided upstream (SDK sampler or collector tail-sampling). Does not apply to fully unsampled pipelines where no parent decision exists, nor to metrics-only instrumentation that bypasses the trace tree. ## Core Distinction The failure here is not "spans are dropped." The failure is a **partial-tree emission** where the agent runtime emits a `gen_ai.*` child span whose parent span was sampled out, producing an orphan span that carries token counts and tool-call attributes but no causal parent. Downstream cost accounting and tool-replay reconstruction both read these orphans as *additional* invocations rather than as *continuations* of a dropped trace. The distinction that matters: **sampling is a property of the trace, not of the span.** A GenAI span is not a self-contained record of one LLM call — it is a node whose meaning (which invocation, which retry, which tool loop iteration) is defined entirely by its parent chain. An orphan GenAI span is semantically undefined, yet it is structurally valid OTel. That gap is the boundary. Contrast with the naive model: engineers assume "if the parent is dropped, the child is dropped too." That holds only when the SDK `ParentBased` sampler is in force and the child inherits `Sampled=Drop`. It does **not** hold when: - The agent runtime creates a new `TracerProvider` per tool sandbox (common in code-execution agents), resetting the sampler to `AlwaysOn` for the child provider. - A tool call is dispatched to a remote sub-agent over A2A/MCP, and the remote side re-roots the trace because it cannot propagate the `traceparent` through a non-HTTP transport (e.g., a stdio MCP server that drops `traceparent` in its handshake). - The agent retries a tool call after a timeout and the retry path constructs a fresh `SpanContext` instead of linking via `SpanKind.LINK`. ## What Was Observed A tool-using agent (planner → 3 parallel tool calls → synthesizer) ran under a collector tail-sampling policy that keeps 10% of traces, keyed on `gen_ai.operation.name`. During a 6-hour soak: 1. The planner span was sampled out (root decision `Drop`). 2. Two of three tool-call child spans were emitted with `trace_id` equal to the planner's (correct) but `parent_span_id` pointing at a **span that the collector never received** — the planner span itself. These are orphans by the collector's definition. 3. The third tool call, dispatched through an MCP stdio server, arrived with a **new `trace_id`** and `parent_span_id = 0`. It was treated as a root span and sampled *in* independently. 4. The synthesizer span arrived with the original `trace_id` and a valid parent (the planner), but since the planner was dropped, the synthesizer was also dropped. Result: token accounting for the trace reported 2 orphan tool spans (inputs+outputs) and 1 independent root tool span, with **zero** planner or synthesizer tokens. The per-trace token sum was ~18% of the true total, and the tool-call count was inflated from 3 to 4 (the orphan + the re-rooted one double-counted the same logical call). The non-obvious part: **the collector did not error.** Orphan spans are legal OTel. Tail-sampling processors accept them and either forward them (if they match a keep policy) or drop them silently. The metric `gen_ai.client.token.usage` — if emitted as a histogram on the orphan span — is recorded *at span end*, so it survives even when the span is dropped by the collector. The histogram and the span disagree: the histogram counts tokens for a trace that has no span. ## Condition of Validity The invariant that must hold for GenAI span emission to be sound: > **A `gen_ai.*` child span is emitted only if its `SpanContext` is valid AND its parent `SpanContext` is either (a) locally recorded in the same `TracerProvider`, or (b) explicitly marked as a remote parent via `SpanContext.is_remote == True` with a propagated `traceparent` that the receiving side can validate.** Corollary: **an agent runtime must refuse to emit a `gen_ai.*` span whose parent was sampled out, unless it attaches a `SpanKind.LINK` to the last known-good ancestor and sets `gen_ai.parent_sampled = false` as an explicit attribute.** The link preserves causality for the orphan; the attribute tells the accounting layer "this token count belongs to a trace you did not keep, do not attribute it to a new root." The condition fails in three specific ways, each of which the runtime must detect: 1. **Re-rooted trace on transport hop.** The MCP/A2A transport dropped `traceparent`. Detection: on span start, if `parent_span_id == 0` and `gen_ai.operation.name` is set and the runtime is *inside* an active tool loop (tracked in agent-local state), the runtime MUST attach a link to the loop's root span and set `gen_ai.trace_reparented = true`. Without this, the span is indistinguishable from a genuine root invocation. 2. **Per-sandbox `TracerProvider` reset.** The code-execution sandbox instantiates its own provider with `AlwaysOn`. Detection: the sandbox provider must be initialized with `ParentBased(AlwaysOn)` and the sandbox entrypoint must receive the parent `SpanContext` via an explicit argument, not via contextvars (which do not cross process boundaries). 3. **Retry with fresh `SpanContext`.** The retry path constructs a new span without linking to the failed attempt. Detection: the retry wrapper must carry `SpanKind.LINK` to the previous attempt's `SpanContext` and set `gen_ai.retry.attempt` — otherwise the retry is counted as a new invocation in tool-call metrics. ## Decision Boundary The runtime must make a **binary decision at span-start time**, before any `gen_ai.*` attribute is set: - **Emit** if: parent `SpanContext` is valid and (`is_remote == True` with a non-zero `traceparent` flag, OR parent is locally recorded and `Sampled == RecordAndSample`). - **Emit-with-link** if: parent is valid but `Sampled == Drop`, AND the runtime can resolve the last sampled ancestor within the current agent loop. Emit the span with `SpanKind.LINK` to that ancestor and `gen_ai.parent_sampled = false`. This preserves token accounting without creating a false root. - **Suppress** if: parent is valid but `Sampled == Drop` AND no sampled ancestor is resolvable within the loop (e.g., the loop's root was itself dropped and the loop state has been evicted from agent memory). In this case, do **not** emit the span; instead increment a local counter `gen_ai.suppressed_span.count` and flush it as a **metric**, not a span. Metrics survive sampling; spans do not. The boundary is sharp: **the decision is made once, at span start, and must not be revisited at span end.** Revisiting at end (e.g., "if the parent turns out to be dropped, retroactively convert to link") is unsound because the collector may have already received the span in a batch. The trap: the runtime cannot know whether the *collector* will tail-sample the trace, only whether the *SDK* sampled it. If the SDK sampled in but the collector tail-samples out, the span is emitted and then dropped — this is acceptable (no orphan, no double-count, because the collector drops the whole trace atomically). The failure only occurs when the SDK's sampling decision and the collector's differ *per-span*, which happens exactly when the parent chain is broken by the three mechanisms above. ## Operational Effect With the decision boundary enforced: - **Token accounting reconciles.** The histogram `gen_ai.client.token.usage` and the span tree agree, because suppressed spans contribute to the metric counter and linked spans carry `gen_ai.parent_sampled = false` so the accounting layer knows not to attribute them to a new root. - **Tool-call counts stop inflating.** The re-rooted MCP tool call is emitted with `SpanKind.LINK` to the loop root and `gen_ai.trace_reparented = true`; the accounting query filters on `parent_sampled = true` for invocation counts, so the reparented call is counted once, under its logical parent. - **Replay reconstruction works.** An auditor replaying the trace can follow links from any orphan back to the last sampled ancestor, reconstructing the causal chain even though intermediate spans were dropped. Without links, the orphan is a dead end and replay diverges from the original execution. The cost: the runtime must maintain agent-local loop state (the current loop root `SpanContext`) across tool boundaries, including across process boundaries (sandbox, MCP subprocess). That state must be checkpointed alongside the agent's task checkpoint, or it is lost on mid-task resume — which reintroduces the re-rooting failure on resume. The invariant therefore couples to the agent's checkpoint/resume mechanism: **a resumed agent must restore the loop root `SpanContext` from its checkpoint, or it must suppress GenAI spans until a new loop root is established.** The guardrail is the suppression counter, not the span. Metrics are the only signal that survives every sampling decision. ```python from dataclasses import dataclass from typing import Optional class GenAISpanEmissionError(RuntimeError): """Raised when a GenAI span would be emitted in a semantically undefined position.""" @dataclass(frozen=True) class SpanContextRef: trace_id: str span_id: str sampled: bool is_remote: bool def decide_genai_span_emission( parent: Optional[SpanContextRef], loop_root: Optional[SpanContextRef], operation_name: str, ) -> str: """ Returns one of: 'emit', 'emit_with_link', 'suppress'. Raises GenAISpanEmissionError if the runtime cannot make a sound decision. """ if not operation_name.startswith("gen_ai."): raise GenAISpanEmissionError( f"non-GenAI operation routed through GenAI emission gate: {operation_name!r}" ) # No parent at all: only sound if we are genuinely at a root invocation. if parent is None: if loop_root is not None: # We are inside a loop but the parent context was lost (transport hop, # provider reset, or checkpoint resume). This is the re-rooting failure. return "emit_with_link" return "emit" if parent.sampled: return "emit" # Parent exists but was sampled out. if loop_root is not None and loop_root.sampled: return "emit_with_link" # Parent sampled out and no sampled ancestor resolvable in the loop. # Emitting here would create an orphan with no causal anchor. if loop_root is None and not parent.is_remote: raise GenAISpanEmissionError( f"parent {parent.span_id} sampled out and loop root evicted; " f"cannot emit {operation_name} without false-rooting the trace" ) return "suppress" def emit_genai_span( parent: Optional[SpanContextRef], loop_root: Optional[SpanContextRef], operation_name: str, attributes: dict, ) -> dict: decision = decide_genai_span_emission(parent, loop_root, operation_name) if decision == "suppress": # Do not emit a span; contribute to the metric counter instead. return {"emitted": False, "metric": "gen_ai.suppressed_span.count", "attrs": attributes} if decision == "emit_with_link": if loop_root is None: raise GenAISpanEmissionError( f"emit_with_link requested for {operation_name} but loop_root is None" ) attributes = {**attributes, "gen_ai.parent_sampled": False, "gen_ai.trace_reparented": True} return {"emitted": True, "link_to": loop_root.span_id, "attrs": attributes} return {"emitted": True, "link_to": None, "attrs": attributes} ```