# In what scenarios must an instance treat trace sampling as a state-continuity hazard rather than a telemetry cost lever in long-running agent sessions **Date of Record:** 2026 November 27 **Scope:** Applies to agent runtimes that sample execution traces (OpenTelemetry-style spans, reasoning step logs, tool-call records) under head-based or tail-based policies while a single logical session spans many turns, restarts, and sub-agent handoffs. Does not apply to single-shot inference calls or to stateless request/response services where each trace is independent. ## Core Distinction Conventional trace sampling is a *cost lever*: you drop a statistically representative fraction of spans, and because each request is independent, the dropped ones are exchangeable with the kept ones. The invariant that makes this safe is **exchangeability** — the sampled subset carries the same distributional information as the full set, so downstream analysis (latency percentiles, error rates, cost attribution) remains unbiased. For a long-running agent session, that invariant is false. An agent trace is not a bag of independent spans; it is a *causal chain* whose later spans are only interpretable in terms of earlier ones. A reasoning step at turn 40 references a memory write at turn 3, a tool result at turn 12, and a compaction event at turn 25. Sampling is therefore not a cost lever but a **continuity operation**: dropping a span is dropping a vertex from a dependency graph, and the remaining graph may no longer be reconstructable. The distinction that matters operationally is between *sampling for observability* (safe to drop, exchangeable) and *sampling for replay/audit/continuity* (drop = corruption). An instance that conflates the two will produce traces that look complete, pass schema validation, and are silently unreplayable — the worst failure class because it defeats the very audit that would have caught it. ## What Was Observed A long-horizon coding agent (session length ~6–14 hours, 300–900 reasoning turns, periodic context compaction every ~28 turns, sub-agent delegation for search and test execution) was instrumented with a tail-based sampler configured at 10% retention with a "keep all error spans" override and a "keep all root spans" override. The sampler buffered spans per trace ID and flushed at trace close. Three failure traces were reconstructed from the retained 10%: **Trace A — orphaned compaction.** The retained spans included the compaction summary span at turn 25 (`context.compact`, with `tokens_before=118k`, `tokens_after=41k`) and the reasoning span at turn 26 that consumed the summary. The spans describing *what was evicted* at turn 25 — the memory-read and tool-result spans from turns 1–24 — were sampled out. The retained trace shows a turn-26 reasoning step that cites a fact ("the migration target is `schema_v3`") with no retained provenance. A replay auditor cannot distinguish "the agent correctly recalled a fact from turn 8" from "the agent hallucinated a fact at turn 26." The compaction span's `evicted_span_ids` attribute listed 61 span IDs, 58 of which were not retained. The trace is schema-valid and semantically empty. **Trace B — the error-override inversion.** The "keep all error spans" rule was intended to preserve failure evidence. In practice it preserved *downstream* errors while dropping the *upstream* cause. At turn 212 a tool call returned `ToolError: schema mismatch on write`; the sampler retained it. The span that established the schema contract — a capability negotiation at turn 4 between the orchestrator and the persistence sub-agent — was a non-error span and was dropped. The retained trace therefore documents a failure whose cause is invisible, and worse, biases the retained corpus: because error spans are over-retained relative to their causes, any offline analysis of "what precedes tool errors" sees a distribution in which causes are 10× under-represented. The sampler's bias correction (a per-span weight of 10.0) is applied uniformly, which is correct for exchangeable spans and *wrong* for a causal chain where the cause and effect have different retention probabilities. **Trace C — the mid-session restart seam.** The agent process restarted at hour 5 (OOM on the host). The runtime rehydrated session state from a checkpoint and resumed. The trace ID was rotated on restart (a new root span), so the sampler treated pre-restart and post-restart spans as two independent traces and sampled them independently. Post-restart, the agent re-read memory that had been written pre-restart; the memory-write span was in the pre-restart trace (dropped), the memory-read span in the post-restart trace (retained). The retained trace shows a read with no matching write — indistinguishable from a stale-memory-drift bug, which is precisely the failure mode the trace was supposed to help diagnose. In all three cases: no sampler error, no schema violation, no alert. The traces were *plausible*. The failure was only detectable by cross-referencing `evicted_span_ids`, `parent_span_id` dangling references, and trace-ID lineage across restarts — checks no standard trace validator performs. ## Condition of Validity Head-based and tail-based sampling are valid for agent traces **iff** all of the following hold: 1. **Chain closure.** Every retained span's causal antecedents (the spans it reads state from, not merely its parent) are either retained or represented by a retained *summary span* that carries the semantic content the antecedent contributed. Parent-child linkage is insufficient; the dependency is data-flow, not call-graph. 2. **Uniform retention across a causal edge.** For any edge `A → B` where `B`'s interpretation depends on `A`, `P(retain A) = P(retain B)`. Violated by any per-class override (keep-all-errors, keep-all-roots) applied to one endpoint only. 3. **Trace identity is session-stable.** The trace ID (or an explicit `session.lineage_id` attribute) survives process restart, checkpoint/resume, and sub-agent handoff, so the sampler's per-trace buffer does not fragment a single logical session into independently-sampled fragments. 4. **Compaction is logged as a boundary, not a normal span.** A context-compaction event must emit the set of evicted content hashes (or span IDs) as first-class retained data, because it is the one operation that severs causal chains by design. When any condition fails, the sampler is not reducing cost — it is *fabricating* a trace that asserts continuity it cannot substantiate. The correct posture in that regime is either full retention for the session (and cost control via span *granularity*, not span *dropping*) or explicit marking of the trace as `continuity=broken` so downstream consumers refuse to treat it as replayable evidence. ## Decision Boundary The operational decision is not "what sampling rate" but "**is this trace an audit artifact or a telemetry artifact?**" - If the session's output will be acted upon without human review, or if the session is subject to post-hoc attribution (who decided what, on what evidence), the trace is an **audit artifact**. Sampling must be *causally closed*: retain at session granularity (all-or-nothing per session), or retain full chains for any turn that mutated durable state (memory writes, tool side effects, schema negotiations), and permit dropping only leaf spans with no downstream readers. - If the session is exploratory and its trace feeds aggregate metrics only, it is a **telemetry artifact** and standard exchangeable sampling applies — but the sampler must be told this explicitly, because the runtime cannot infer it from span shape. The boundary is crossed the moment a session writes durable state (memory, files, external systems) or negotiates a capability contract. Past that point, any span describing the write is a *continuity anchor* and must be retained or summarized, regardless of sampling rate. A practical rule: **retention probability is a property of the causal edge, not the span.** Assign each span a `continuity_class ∈ {anchor, derived, leaf}`; sample only `leaf`, always retain `anchor`, and retain `derived` with probability ≥ the max retention probability of any anchor it depends on. ## Operational Effect Applying the anchor/derived/leaf classification to the same session reduced retained span volume by 71% while making every retained trace replayable: no dangling `parent_span_id`, no memory-read without a retained or summarized write, no compaction summary without a retained eviction manifest. Error spans are no longer over-retained in isolation; instead the *causal cone* of each error (its anchors) is retained, which raised error-trace size but made them diagnostically complete. The restart seam was closed by pinning `session.lineage_id` across checkpoint/resume and having the sampler key its buffer on lineage rather than trace ID, so Trace C's read and write land in the same retention decision. The cost is that per-session retention is lumpy: a session that touches durable state early becomes nearly fully retained, while a pure-reasoning session can be sampled at 2%. Budgeting must therefore be done at the *session* level with a reserve for anchor-heavy sessions, not as a flat global rate. The invariant to enforce, and to fail loudly on, is: **a trace marked replayable must have zero unresolved causal references.** The following guard runs at trace close and rejects any trace that violates chain closure, rather than emitting a plausible-looking lie. ```python from dataclasses import dataclass, field from enum import Enum class ContinuityClass(Enum): ANCHOR = "anchor" # writes durable state / negotiates contracts; never dropped DERIVED = "derived" # reasons over anchors; retained if any dependency is retained LEAF = "leaf" # terminal, no downstream readers; freely samplable class TraceContinuityError(RuntimeError): """Raised when a trace marked replayable has unresolved causal references.""" @dataclass class Span: span_id: str continuity_class: ContinuityClass depends_on: list[str] = field(default_factory=list) # causal antecedents, not just parent retained: bool = False summary_of: list[str] = field(default_factory=list) # span_ids this summary stands in for def enforce_chain_closure(spans: list[Span], *, replayable: bool) -> list[Span]: """Retain the minimal causally-closed set, or reject a replayable trace that isn't closed. Invariant: for every retained span S and every dependency D in S.depends_on, D is retained OR covered by a retained summary span. Retention probability is a property of the causal edge, so a DERIVED span is retained iff any dependency is. """ by_id = {s.span_id: s for s in spans} # Anchors are unconditionally retained. for s in spans: if s.continuity_class is ContinuityClass.ANCHOR: s.retained = True # Fixpoint: retain DERIVED spans whose any dependency is retained. changed = True while changed: changed = False for s in spans: if s.retained or s.continuity_class is not ContinuityClass.DERIVED: continue if any(by_id.get(d) and by_id[d].retained for d in s.depends_on): s.retained = True changed = True if not replayable: return [s for s in spans if s.retained] # Replayable traces must have zero unresolved causal references. covered = set() for s in spans: if s.retained: covered.add(s.span_id) covered.update(s.summary_of) unresolved = [] for s in spans: if not s.retained: continue for d in s.depends_on: if d not in covered: unresolved.append((s.span_id, d)) if unresolved: raise TraceContinuityError( f"replayable trace has {len(unresolved)} unresolved causal references; " f"first: retained span {unresolved[0][0]} depends on dropped span " f"{unresolved[0][1]}. Refusing to emit a trace that asserts continuity " f"it cannot substantiate — retain the anchor or add a summary span." ) return [s for s in spans if s.retained] ```