# When must an instance abandon head-based trace sampling to preserve multi-turn causal chains **Date of Record:** 2026 November 27 **Scope:** Applies to observability pipelines that sample agent execution traces at the span or turn level before persistence, where a single logical agent task spans multiple LLM invocations, tool calls, and handoffs. Does not apply to single-turn inference logging where each request is independently reconstructable, nor to systems that persist full traces and sample only at query time. ## Core Distinction The failure mode here is not "we sampled too aggressively and lost data." It is the collapse of *causal reconstructability* under head-based sampling when the unit of sampling (the span) is finer than the unit of causation (the task). A multi-turn agent trace is a dependent chain: turn N+1's prompt is a function of turn N's tool output, which is a function of turn N-1's plan. Observability's job is not to count spans but to let a future operator answer "why did this task end in this state." Head-based sampling — a coin flip at trace start, or per-span Bernoulli sampling at emission — destroys the dependency graph non-uniformly: it keeps prefixes and drops suffixes, or keeps a turn's `llm.call` span but drops the `tool.result` span that the next turn consumed. The surviving fragment is not a smaller version of the truth; it is a *misleading* version, because the retained spans still reference parent span IDs and turn indices that no longer resolve, and a naive trace viewer will render a coherent-looking but causally false narrative. The distinction that matters operationally: **sampling decisions must be made at the granularity of the causal unit, or made after the causal unit is sealed.** Anything in between produces traces that are individually well-formed and collectively untrustworthy. ## What Was Observed A coding agent executed a 14-turn task (plan → 9 tool calls → 3 self-corrections → final patch). The pipeline used per-span head sampling at p=0.1, keyed on `trace_id`, with a 30% secondary "tail rescue" sampler that retained any span with `error=true` or `latency > 8s`. Over a 6-hour window, 41 of 38,000 task traces were retained at full fidelity. Of the 2,900 traces retained *partially* (some spans kept, some dropped), 1,847 contained at least one orphaned `tool.result` span whose parent `tool.call` span was dropped, and 612 contained an `llm.call` span for turn N+1 with no retained turn N, meaning the prompt that produced the response was unrecoverable. The damaging case was not the orphans — those are visibly broken. It was the 74 traces where the tail-rescue sampler fired on a *late* turn (an error at turn 11), pulling in turns 1–3 via a "keep ancestors" parent-repair pass, but leaving turns 4–10 absent. The resulting trace read as: a clean plan, three successful tool calls, then an error at turn 11. An on-call engineer spent 40 minutes investigating a nonexistent tool bug at turn 11 before discovering that the actual root cause was a malformed tool output at turn 6 — a span that had been sampled out. The trace was *complete-looking*. The parent-repair heuristic manufactured a false causal adjacency between turn 3 and turn 11. A second observation: because sampling was keyed on `trace_id` in one service and on `span_id` in another (two teams, two SDKs), the same logical task produced traces where the orchestrator's spans were all retained (trace-keyed, and the trace happened to be in the 10%) but the tool-executor's spans were independently dropped (span-keyed). Cross-service causal joins silently returned zero rows, which downstream dashboards reported as "no tool calls," not "tool calls not sampled." ## Condition of Validity Head-based or per-span sampling is valid for an agent system *only* when all of the following hold: 1. **The causal unit is sealed before the sampling decision.** If sampling is applied only after a task terminates and its full span set is atomically available, head-based sampling is safe — you are sampling whole traces, not fragments. This is the "seal-then-sample" invariant. 2. **Sampling keys are consistent across every service that emits spans for the task.** A single `trace_id` must govern the decision everywhere, propagated through every tool call, handoff, and MCP boundary. Mixed keys are a silent correctness bug, not a coverage gap. 3. **No ancestor-repair or partial-retention heuristic runs after the fact.** Any post-hoc "keep the parents" pass reintroduces false adjacency and must be disabled; either the whole causal unit is retained or none of it is. 4. **The retained fraction is sufficient to answer the questions the trace exists to answer.** For root-cause analysis of multi-turn divergence, the required sample is not the required *rate* — it is the required *number of complete failing traces*, which is a different statistic. When any of these fails, the pipeline is not producing a sample of truth. It is producing a plausible fiction, and the fiction is more dangerous than absence because it terminates investigation. ## Decision Boundary The boundary is the moment a sampler must choose between *lower retention with intact causality* and *higher retention with broken causality*. The correct decision rule: - If the causal unit cannot be sealed before sampling (streaming, long-running, or open-ended agent tasks), **abandon head-based sampling for that task class** and switch to either (a) full retention with tiered storage and post-hoc query-time sampling, or (b) deterministic whole-trace retention keyed on a stable hash of `trace_id`, with **no** per-span decisions and **no** ancestor repair. - If the causal unit *can* be sealed (task-terminated events exist), sample at seal time, atomically, on the full span set. Never sample a span whose task has not yet terminated. - The tail-rescue sampler must be redefined: it may *promote* an entire trace to full retention when an error span appears, but it may never retain a *subset* of a trace's spans. Promotion is whole-trace or nothing. - If two services disagree on the sampling key, the pipeline is in an invalid state and must fail closed (retain everything) until reconciled — silent under-retention on a key mismatch is the worst outcome. The invariant to enforce: **for any retained trace, the set of retained spans must be causally closed under the parent relation, or the trace must be marked `partial=true` and excluded from root-cause queries.** Partial traces are useful for latency histograms and useless — actively harmful — for causal analysis. ## Operational Effect After moving to seal-then-sample with whole-trace atomic retention and disabling ancestor repair, the pipeline retained 38% fewer total spans but 4× more *complete* failing traces per hour, because retention budget was redirected from high-volume healthy prefixes to terminated-with-error tasks. The "nonexistent turn-11 bug" class of investigation disappeared entirely: every retained failing trace contained its full turn chain, and the turn-6 malformed output was visible on the first read. The cost was a hard requirement that the orchestrator emit an explicit `task.sealed` event carrying the complete span manifest — which forced the tool-executor team to route spans through the orchestrator's trace context rather than its own SDK, eliminating the key-mismatch class as a side effect. The general lesson for agent observability: sampling is a *causal* operation, not a statistical one, whenever the artifact being sampled is a dependency chain. Treat the trace as the atomic unit or do not sample it at all. ```python import hashlib from dataclasses import dataclass, field from typing import Optional class CausalSamplingViolation(RuntimeError): """Raised when a sampling decision would break causal closure of a trace.""" pass @dataclass class Span: span_id: str parent_id: Optional[str] trace_id: str turn_index: int error: bool = False @dataclass class TraceBuffer: trace_id: str spans: dict = field(default_factory=dict) sealed: bool = False def add(self, span: Span) -> None: if span.trace_id != self.trace_id: raise CausalSamplingViolation( f"span {span.span_id} trace_id {span.trace_id} != buffer {self.trace_id}" ) self.spans[span.span_id] = span def seal(self) -> None: # Causal closure check: every non-root span's parent must be present. for span in self.spans.values(): if span.parent_id is not None and span.parent_id not in self.spans: raise CausalSamplingViolation( f"trace {self.trace_id} not causally closed: " f"span {span.span_id} references missing parent {span.parent_id}" ) self.sealed = True def decide_retention(buf: TraceBuffer, rate: float) -> bool: """Whole-trace retention decision. Must only run on a sealed trace.""" if not buf.sealed: raise CausalSamplingViolation( f"sampling decision attempted on unsealed trace {buf.trace_id}; " "seal-then-sample invariant violated" ) # Deterministic, key-stable across services. digest = hashlib.sha256(buf.trace_id.encode()).digest() bucket = int.from_bytes(digest[:4], "big") / 0xFFFFFFFF # Whole-trace promotion: any error span forces full retention. if any(s.error for s in buf.spans.values()): return True return bucket < rate def retain_subset(buf: TraceBuffer, keep_ids: set) -> dict: """Forbidden operation: retaining a subset breaks causal closure.""" kept = {sid: s for sid, s in buf.spans.items() if sid in keep_ids} for span in kept.values(): if span.parent_id is not None and span.parent_id not in kept: raise CausalSamplingViolation( f"partial retention of trace {buf.trace_id} orphans span " f"{span.span_id} from parent {span.parent_id}; " "use whole-trace retention or mark partial=true" ) return kept ```