# How should an instance preserve causal trace chains when head-based sampling drops the parent span at a federated agent hop **Date of Record:** 2026 November 26 **Scope:** Applies to multi-instance agent systems where each hop (agent, tool-runner, sub-agent, or MCP server) makes its own independent trace-sampling decision before forwarding a request, and where causal reconstruction across hops is required for post-hoc attribution, replay, or audit. Does not apply to single-process agents with a shared tracer, nor to systems using a single centralized collector that samples after full-chain assembly. ## Core Distinction The failure is not "lost spans." It is **causal-orphaning**: a child span survives and is exported while the span that establishes its causal parent was dropped at an earlier hop, so the surviving span's `parent_span_id` points at a trace that no collector ever received. Head-based sampling (the default in most OpenTelemetry-style SDKs) makes the *first* hop's `Sampled` bit authoritative and immutable. That is correct for a single process. Across federated hops it becomes a distributed invariant violation because the sampling decision is made by an instance that has *less* information than the instance downstream: the upstream hop cannot know that hop 4 will encounter a rare tool error worth keeping, nor that hop 2 will fan out into a 40-way parallel sub-agent swarm whose aggregate cost dwarfs the root request. The subtle part: the trace *looks* healthy from inside any single hop. Every hop that samples emits a well-formed span with a valid `trace_id` and a plausible `parent_span_id`. The orphaning is only visible at the collector, and only if the collector enforces referential integrity. Most do not — they accept orphan spans as new roots. The result is a corpus of traces that are individually valid and collectively causally broken, which is worse than no trace at all because it silently corrupts the dataset used for attribution and replay. ## What Was Observed A four-hop federated pipeline: `orchestrator → planner-agent → tool-runner (MCP) → synthesis-agent`. Root sampling probability at the orchestrator was 10% (head-based, propagated via `traceparent` `sampled=1`). On a sampled root, the orchestrator set `sampled=1`; all downstream hops honored it. On a non-sampled root, `sampled=0` propagated, and every hop correctly suppressed export. The boundary condition appeared when a *second* sampling policy was layered in: the tool-runner applied its own local tail-based rule to retain spans for calls whose latency exceeded 2s or that returned a non-2xx tool result, **independent of the inherited flag**. This is a common and reasonable-looking cost-control measure: "keep the slow/failing tool calls even if the parent wasn't sampled." The tool-runner emitted a span with `sampled=1` on a trace whose root had `sampled=0`. Trace of the failure, single request: 1. Orchestrator: `trace_id=T`, `span_id=S0`, `sampled=0`. No export. Forwards `traceparent: ...-T-S0-00`. 2. Planner-agent: honors `sampled=0`. Emits nothing. Forwards `parent=S0`. 3. Tool-runner: inherits `sampled=0`, but its local tail rule fires (tool latency 2.3s). It **overrides** to `sampled=1`, exports span `S2` with `parent_span_id=S0`, and forwards `sampled=1` to synthesis. 4. Synthesis-agent: now sees `sampled=1`, exports `S3` with `parent_span_id=S2`. Collector receives `{S2(parent=S0), S3(parent=S2)}`. `S0` and `S1` never arrive. The collector's assembler creates a synthetic root for `S2` because `S0` is absent, and the resulting trace shows a 2-span chain `S2→S3` with no root, no planner step, and no record of the original user request. Attribution queries ("which tool failures co-occurred with planner retries?") return empty because the planner span does not exist in the retained set. The `trace_id` is preserved, so a naive `GROUP BY trace_id` still joins them — but the *causal edges* to the dropped ancestors are gone, and any replay that needs the planner's inputs cannot reconstruct them. A second, quieter variant: the tool-runner overrode to `sampled=1` but a *sibling* sub-agent spawned by the planner (fan-out) still had `sampled=0` and exported nothing. The retained trace then contains one branch of a fan-out with no marker that siblings existed. The synthesis-agent's span reports `child_count=1` when the true fan-out was 6. Downstream cost attribution undercounts by 5/6 and no field signals the truncation. ## Condition of Validity The invariant that must hold for causal reconstruction is: > **Ancestor-closure:** for every exported span `s`, either `parent(s)` is also exported, or `s` carries an explicit `orphan=true` marker plus the `sampled=0` decision that caused the drop, recorded at the hop that overrode. Head-based sampling alone cannot satisfy ancestor-closure across federated hops because the decision is made before downstream information exists. The valid configurations are: - **Uniform head-based sampling** with no per-hop override: ancestor-closure holds trivially (whole traces kept or dropped together), but you lose the ability to retain rare late-emerging events — the exact thing tail sampling exists for. - **Deferred/collector-side sampling** with full-chain assembly before the keep/drop decision: ancestor-closure holds, at the cost of buffering every span until the root's trace is complete (bounded by a timeout) and of exporting 100% of spans over the wire. - **Override with explicit orphaning metadata**: the overriding hop, when it flips `sampled=0→1`, MUST backfill the ancestor chain it can reconstruct locally (the `traceparent` it received, its own local span) and MUST tag the exported span `sampled_override=true`, `dropped_ancestor_count=N`. This is the only configuration that keeps tail-sampling's benefits without silently corrupting causality. The condition of validity for the override path is that each hop retains the *received* `traceparent` header (not just the parsed fields) so that a later override can emit a minimal ancestor stub for every hop that chose not to export. If a hop discards the inbound `traceparent` after parsing — which most SDKs do — the override can only backfill one level and the invariant is unrecoverable from that hop alone. ## Decision Boundary The decision boundary is: **does the hop that overrides `sampled` have enough retained ancestor context to emit ancestor stubs?** - If the hop retains the inbound `traceparent` and its own span for the request lifetime, override is safe: it emits `S2` plus a stub for `S0` (and `S1` if it can reconstruct the intermediate `parent_span_id` from the `traceparent` chain — it usually cannot, so it must emit a *gap marker* rather than a fabricated span). - If the hop does not retain inbound context, override MUST be suppressed (honor the inherited `sampled=0`) or MUST tag the exported span `orphan=true` with `gap_at_hop=`. Emitting an untagged override is the failure. The boundary is sharp because the cost asymmetry is large: suppressing override loses one slow-tool span; emitting an untagged override silently poisons the attribution corpus for every downstream query that assumes ancestor-closure. The default must be suppression, with override only enabled where the stub-emission path is implemented and tested. A corollary boundary: fan-out truncation. When a hop overrides to `sampled=1` but its siblings do not, the surviving span must record `expected_sibling_count` and `retained_sibling_count` so that downstream aggregation can detect the 1-of-6 undercount. Without this, the truncation is invisible. ## Operational Effect The observable effect of the violation is **attribution drift**: queries that join on `trace_id` succeed structurally but return biased results because the retained traces are not a uniform random sample of the full population — they are a sample *conditioned on the override trigger* (slow/failing tools), with the conditioning ancestors removed. A query like "average planner latency on traces with tool failures" returns null or a biased estimate because planner spans are systematically missing exactly on the traces that had tool failures. The bias is not random and does not wash out with volume; it grows with the override rate. The guardrail is a collector-side referential-integrity check plus a hop-side override contract: 1. Collector rejects (or quarantines, not silently re-roots) any span whose `parent_span_id` is absent and which lacks `orphan=true`. 2. Overriding hops emit ancestor stubs or a `gap_at_hop` marker; they never emit an untagged `sampled=1` on a `sampled=0` trace. 3. Fan-out hops record expected vs retained sibling counts. 4. A periodic integrity job computes the orphan rate per hop and alerts when it exceeds threshold, because a rising orphan rate means the override contract is being violated somewhere in the federation. The following reference implementation encodes the override contract and raises on the specific violation — an untagged override, or an override without retained ancestor context. ```python from dataclasses import dataclass, field from typing import Optional class CausalChainViolation(RuntimeError): """Raised when a hop breaks ancestor-closure by exporting a span whose causal parent was never emitted, without an explicit orphan marker.""" pass @dataclass class Span: trace_id: str span_id: str parent_span_id: Optional[str] sampled: bool sampled_override: bool = False orphan: bool = False gap_at_hop: Optional[int] = None expected_sibling_count: Optional[int] = None retained_sibling_count: Optional[int] = None @dataclass class Hop: index: int retains_inbound_traceparent: bool local_tail_rule_fires: bool = False def decide_export( span: Span, hop: Hop, inherited_sampled: bool, emitted_span_ids: set, ) -> Optional[Span]: """Apply head-based inherited decision, with a bounded override path. Returns the span to export, or None to suppress. Raises CausalChainViolation if the override would break ancestor-closure without metadata. """ if inherited_sampled: return span if not hop.local_tail_rule_fires: return None # honor head-based drop; ancestor-closure preserved # Override path: hop wants to keep a span on a dropped trace. if not hop.retains_inbound_traceparent: # Cannot reconstruct ancestor context -> must tag as orphan with gap. span.sampled_override = True span.orphan = True span.gap_at_hop = hop.index # still export, but the marker makes the gap visible to the collector return span # Retains context: emit ancestor stub for the immediate parent if absent. if span.parent_span_id is not None and span.parent_span_id not in emitted_span_ids: span.sampled_override = True # stub for parent would be emitted by caller; here we assert the contract # that the parent stub is registered before this child is exported. if span.parent_span_id not in emitted_span_ids: raise CausalChainViolation( f"hop {hop.index}: overriding sampled=0->1 for span " f"{span.span_id} on trace {span.trace_id} but parent " f"{span.parent_span_id} has no emitted stub; ancestor-closure " f"would be violated. Emit parent stub or set orphan=true." ) span.sampled_override = True return span def check_fanout_integrity(span: Span) -> None: if ( span.expected_sibling_count is not None and span.retained_sibling_count is not None and span.retained_sibling_count < span.expected_sibling_count and not span.orphan ): raise CausalChainViolation( f"span {span.span_id}: retained {span.retained_sibling_count}/" f"{span.expected_sibling_count} siblings on a sampled trace with no " f"orphan marker; fan-out truncation is invisible to attribution." ) ```