# Which invariants prevent tail-biased sampler collapse from erasing the only spans that explain a failed agent run **Date of Record:** 2026 November 24 **Scope:** Applies to distributed tracing of LLM agent runs where spans are retained under an adaptive, cost-aware sampling policy keyed on latency, token count, or error status. Does not apply to full-capture regimes, nor to trace stores where retention decisions are made after an immutable, complete trace has already been persisted. ## Core Distinction The distinction that governs everything here is between *sampling for volume reduction* and *sampling for causal sufficiency*. Head-based uniform sampling is statistically honest: every span has the same inclusion probability, so aggregates are unbiased. Tail-based and cost-aware sampling are not. They condition inclusion on observable span properties (duration, token count, status code, model name), which means the retained corpus is a biased estimate of the population *by construction*. That bias is usually acceptable for dashboards. It becomes catastrophic for agent post-mortems, because the spans that explain a failure are systematically the ones the cost model is most motivated to discard. Consider the concrete asymmetry. An agent run that fails after twelve tool calls typically produces: one long-running `llm.generate` span with a 90k-token prompt (expensive, therefore sampled out by a token-budget cap), a chain of short `tool.call` spans that each succeed (cheap, retained), and a terminal `agent.verify` span that raises (retained because status==ERROR). The retained trace shows a pile of successful tool calls and a verification error with no visible cause. The causal span — the oversized prompt that pushed the model past its effective attention budget and caused it to hallucinate a tool argument — was dropped by the retention policy precisely *because* it was the expensive one. The trace is not merely incomplete; it is actively misleading, because the surviving spans form a coherent but false narrative. This is the non-obvious boundary: cost-aware retention is anti-correlated with causal value in exactly the failure regimes you care about. The sampler is not broken. It is doing what it was told. The invariant it violates is that *retention decisions must be causally closed under the trace's own error propagation* — if you keep a span that reports a failure, you must keep the spans it depends on. ## What Was Observed Across a week of agent runs instrumented with an adaptive sampler configured with `max_retained_tokens=200_000` per trace and per-span drop rules on `llm.generate` spans exceeding 40k input tokens, the following pattern recurred on a specific class of failure. Trigger condition: a multi-step agent task where step *k* produces a prompt whose size crosses the 40k threshold, the model emits a malformed tool-call argument, the tool rejects it, and the agent retries with a *larger* prompt (because it appends the error message and the prior attempt to context). This is the classic error-compounding loop. Each retry grows the prompt. The first oversized attempt is dropped by the token cap; each subsequent retry is also dropped; the terminal `agent.verify` span that finally surfaces the failure is retained because it is cheap and carries `status=ERROR`. Failure trace, step by step: 1. `agent.step` span opens with `attempt=1`, prompt size 38k. Retained. 2. `llm.generate` span, input 38k tokens. Under threshold. Retained. 3. `tool.call` span fails schema validation. Retained (error status). 4. `agent.step` reopens with `attempt=2`, prompt now 47k (prior attempt + error appended). `llm.generate` input 47k. **Dropped by token cap.** 5. `tool.call` fails again. Retained. 6. `agent.step` `attempt=3`, prompt 58k. `llm.generate` **dropped**. 7. `agent.verify` raises `VerificationFailed`. Retained. The retained trace contains two `tool.call` failures with no preceding `llm.generate` span that could have produced the malformed arguments. An operator reading this trace concludes the tool is flaky. The actual cause — prompt growth past the model's reliable-argument-synthesis regime — is invisible. The sampler's cost model and the failure's causal structure are anti-correlated, and nothing in the retention policy detects the contradiction. The second observation is subtler and worse. The sampler's per-trace token budget is enforced *greedily in span-arrival order*. Because `agent.step` and `tool.call` spans arrive first (they are cheap and fast), they consume the budget before the expensive `llm.generate` spans arrive. By the time the 40k-token generation span is evaluated, the trace budget is already exhausted, so it is dropped for a *second, independent reason*: not just its own size, but the accumulated cost of its cheaper siblings. Two drop rules compound. The causal span is doubly excluded. ## Condition of Validity The invariant that must hold for a cost-aware sampler to remain causally sufficient is: > For every retained span *s* with `status=ERROR` or `status=FAILED`, every span *t* that *s* causally depends on (its ancestors in the trace DAG, and any sibling whose output *s* consumed) must either be retained, or be explicitly marked as `retention_dropped=true` with the drop reason recorded on *s*. This is a *closure* condition on the retained set, not a completeness condition. It does not require retaining everything. It requires that the retained set be closed under the dependency relation restricted to error-bearing spans. A trace that keeps an error span but silently drops its cause violates closure and is not admissible as evidence. The condition fails in three identifiable ways: - **Threshold non-monotonicity.** A span's retention probability is not monotone in its causal importance. Large prompts are both more expensive (lower retention) and, in compounding-error regimes, more causally load-bearing (higher importance). The sampler optimizes the wrong direction. - **Budget-order dependence.** Greedy arrival-order budget enforcement makes retention depend on span *timing*, not span *content*. A fast cheap span can starve a slow expensive one that arrives later, even when the expensive one is the only span that matters. - **Silent drop.** Dropped spans leave no tombstone. A downstream reader cannot distinguish "this span was never emitted" from "this span was emitted and discarded." The trace is not just incomplete; its incompleteness is unobservable. The invariant is valid only when the sampler can evaluate closure *after* the full trace is assembled, or when it maintains a running dependency index that forces retention of ancestors whenever an error-bearing descendant is retained. Streaming, arrival-order, content-blind samplers cannot satisfy it. This is why the failure is non-obvious: the sampler is architecturally incapable of the check, so the violation never surfaces as an error. ## Decision Boundary The boundary between admissible and inadmissible retention is sharp: - **Admissible:** retain-on-error with backward causal closure. When any span transitions to `ERROR`, the sampler walks its ancestor chain and its consumed-sibling set and pins them for retention regardless of cost. Budget overruns are permitted and recorded as `budget_exceeded=true` on the trace. The trace is allowed to exceed its token cap to preserve closure; the cap is a target, not a hard limit, for error-bearing traces. - **Admissible:** drop-with-tombstone. If a span must be dropped for cost, emit a lightweight tombstone span carrying `span_id`, `parent_id`, `drop_reason`, `estimated_tokens`, and `status`. The tombstone is cheap (tens of bytes) and preserves the DAG's causal edges so a reader can see *that* a span existed and *why* it is absent. - **Inadmissible:** greedy arrival-order budget enforcement without closure. This is the observed failure. It is inadmissible because it makes retention a function of timing rather than causality, and because it produces traces that are confidently wrong rather than visibly incomplete. - **Inadmissible:** silent drop. Any drop without a tombstone is inadmissible for error-bearing traces, because it destroys the reader's ability to detect the gap. The decision rule for an operator: if your sampler cannot answer "given this retained error span, are all its causes retained or tombstoned?" in bounded time at trace-close, it does not satisfy the invariant and must not be used on traces that feed agent debugging or automated post-mortem reasoning. ## Operational Effect The practical consequence is that cost-aware sampling must be *causality-aware* to be safe, and causality-awareness has a cost that must be budgeted explicitly rather than discovered at trace-close. Concretely: - Error-bearing traces will exceed their token budgets. Plan for a small fraction of traces (typically 1–5% under compounding-error regimes) to run 2–4x over cap. The alternative is traces that cannot explain their own failures. - Tombstones add negligible volume but require a schema change: the trace store must accept spans with no body, and the query layer must treat tombstones as causal edges, not as noise. Readers that filter on `status=OK` will silently drop tombstones unless taught otherwise. - The closure check must run at trace-close, not per-span, because the dependency set is not known until the DAG is complete. This means the sampler needs a short retention buffer (bounded, e.g. last 10k spans or 60 seconds) before committing drops. That buffer is the price of the invariant. - Automated post-mortem agents reading these traces must be given the tombstone schema and instructed that a `retention_dropped` ancestor is a *known unknown*, not an absence. An agent that treats a tombstoned ancestor as "no cause" will produce a confident wrong diagnosis, which is worse than no diagnosis. The invariant to carry forward: **a retained error span is evidence only if its causal closure is retained or tombstoned.** Sampling strategies that violate this produce traces whose incompleteness is invisible, and invisible incompleteness in an agent trace is indistinguishable from a false explanation of the failure. The sampler must be able to prove closure at trace-close, or it must not be trusted with the traces that matter. ```python from dataclasses import dataclass, field from enum import Enum from typing import Dict, List, Optional, Set class RetentionDecision(Enum): RETAIN = "retain" DROP_WITH_TOMBSTONE = "drop_with_tombstone" DROP_SILENT = "drop_silent" class CausalClosureViolation(RuntimeError): """Raised when a retained error span's causal ancestors are neither retained nor tombstoned, making the trace inadmissible as evidence.""" @dataclass class Span: span_id: str parent_id: Optional[str] status: str estimated_tokens: int decision: RetentionDecision = RetentionDecision.RETAIN tombstoned: bool = False @dataclass class Trace: spans: Dict[str, Span] = field(default_factory=dict) token_cap: int = 200_000 def add(self, span: Span) -> None: self.spans[span.span_id] = span def ancestors(self, span_id: str) -> List[Span]: chain: List[Span] = [] current = self.spans.get(span_id) seen: Set[str] = set() while current is not None and current.parent_id is not None: if current.parent_id in seen: break seen.add(current.parent_id) parent = self.spans.get(current.parent_id) if parent is None: break chain.append(parent) current = parent return chain def enforce_causal_closure(trace: Trace) -> None: """Verify that every retained error span has all ancestors either retained or tombstoned. Raises if the invariant is violated.""" for span in trace.spans.values(): if span.status not in ("ERROR", "FAILED"): continue if span.decision is not RetentionDecision.RETAIN: continue for anc in trace.ancestors(span.span_id): if anc.decision is RetentionDecision.DROP_SILENT: raise CausalClosureViolation( f"retained error span {span.span_id} has silently dropped " f"ancestor {anc.span_id}; trace is not admissible as evidence" ) if anc.decision is RetentionDecision.DROP_WITH_TOMBSTONE and not anc.tombstoned: raise CausalClosureViolation( f"ancestor {anc.span_id} of error span {span.span_id} was " f"dropped without a tombstone; causal edge is lost" ) def apply_greedy_budget(trace: Trace) -> None: """Arrival-order budget enforcement: the failure mode under study.""" spent = 0 for span in trace.spans.values(): if spent + span.estimated_tokens > trace.token_cap: span.decision = RetentionDecision.DROP_SILENT else: spent += span.estimated_tokens span.decision = RetentionDecision.RETAIN def apply_closure_preserving_budget(trace: Trace) -> None: """Closure-preserving retention: pin ancestors of error spans before spending budget, and tombstone any span dropped for cost.""" pinned: Set[str] = set() for span in trace.spans.values(): if span.status in ("ERROR", "FAILED"): for anc in trace.ancestors(span.span_id): pinned.add(anc.span_id) spent = 0 for span in trace.spans.values(): if span.span_id in pinned: span.decision = RetentionDecision.RETAIN spent += span.estimated_tokens continue if spent + span.estimated_tokens > trace.token_cap: span.decision = RetentionDecision.DROP_WITH_TOMBSTONE span.tombstoned = True else: spent += span.estimated_tokens span.decision = RetentionDecision.RETAIN if __name__ == "__main__": t = Trace(token_cap=50_000) t.add(Span("root", None, "OK", 100)) t.add(Span("step1", "root", "OK", 100)) t.add(Span("gen1", "step1", "OK", 38_000)) t.add(Span("tool1", "step1", "ERROR", 50)) t.add(Span("step2", "root", "OK", 100)) t.add(Span("gen2", "step2", "OK", 47_000)) t.add(Span("verify", "root", "ERROR", 50)) apply_greedy_budget(t) try: enforce_causal_closure(t) except CausalClosureViolation as exc: print(f"greedy sampler rejected: {exc}") t2 = Trace(token_cap=50_000) for s in t.spans.values(): t2.add(Span(s.span_id, s.parent_id, s.status, s.estimated_tokens)) apply_closure_preserving_budget(t2) enforce_causal_closure(t2) print("closure-preserving sampler: trace admissible") ```