# Why does an instance lose distributed trace linkage when a subagent re-emits its parent's span context after a context-window compaction **Date of Record:** 2026 November 20 **Scope:** Applies to multi-agent systems that propagate OpenTelemetry-style span context (trace_id, span_id, trace_flags, plus GenAI semantic convention attributes such as `gen_ai.operation.name`, `gen_ai.agent.id`, `gen_ai.tool.name`) across orchestrator→subagent→tool boundaries via serialized context tokens. Does not apply to single-process agents that emit spans from a shared in-memory context manager, nor to systems where the trace backend reconstructs linkage server-side from a durable event log. ## Core Distinction The failure is not "traces are missing." The failure is that traces are *present but mis-parented* — a subagent re-emits a span whose `parent_span_id` points to a span that no longer exists in the orchestrator's exported trace, because the subagent's span context was captured *before* a compaction event that invalidated the originating span's lifetime. The distinguishing signal is a trace graph with a dangling parent reference and a `trace_flags` byte that disagrees with the subagent's actual sampling decision. This is a *linkage integrity* failure, not an observability-coverage failure, and it is invisible to span-count dashboards because both spans still export. ## What Was Observed An orchestrator agent (call it O) dispatched a research task to subagent S with a serialized span context token: `{trace_id: T, span_id: A, trace_flags: 0x01}` where A is O's active `invoke_agent` span. S ran for 14 tool calls. At call 9, S's context window saturated and a compaction routine summarized the message history, dropping the original dispatch envelope — including the raw context token — and replacing it with a natural-language summary that paraphrased the token as `"trace_id T, parent A"`. S continued, and at call 10 emitted a tool span with `parent_span_id: A`. Two things then broke simultaneously: 1. **Lifetime violation.** O's span A had already been ended (O's `invoke_agent` wrapped only the dispatch, not the full subagent lifetime, so A closed at dispatch-return). The subagent's tool span at call 10 pointed at a span that was closed ~40 seconds earlier and was, in the collector's view, complete. The trace backend rendered a child whose parent's end-timestamp preceded the child's start-timestamp by 40s — a negative-duration parent-child edge that most UIs silently clamp to zero, hiding the defect. 2. **Flag divergence.** The paraphrased token lost the `trace_flags` byte. S re-derived it from its own sampler, which had a 0.1 head-sampling rate, and emitted `0x00` (not sampled) on a span whose parent was `0x01` (sampled). Downstream, the collector's tail-sampling policy saw an inconsistent flag and dropped the entire subagent subtree, while O's span survived. The result: a trace that shows an orchestrator dispatching to *nothing*. The trigger condition is precise: **a context-carrying envelope that crosses a compaction boundary and is re-materialized from a lossy summary rather than from a typed, byte-preserving field.** Compaction is not the bug; compaction that treats the span context as prose is. ## Condition of Validity The invariant that must hold for linkage to remain sound is: > For any span emitted by an agent instance, the referenced `parent_span_id` must (a) be open at the time of emission, or be explicitly marked as a *link* (not a parent) to a closed span; and (b) carry a `trace_flags` byte byte-identical to the parent's, unless the child is a deliberate root. This holds only when the span context is carried as an **opaque, typed, checksummed field** that compaction routines are forbidden to paraphrase — i.e., it lives outside the summarizable message body, in a structured envelope slot that survives window truncation by construction. The condition fails whenever the context token is embedded in natural-language content (a tool-call argument, a prompt string, a "here is your context" preamble) that a summarizer can rewrite. It also fails when the orchestrator closes its dispatch span before the subagent's lifetime ends, because that converts a legitimate parent-child edge into a dangling reference regardless of token fidelity. ## Decision Boundary The architectural fork is whether the span context is **content** or **metadata**. If it is content — something the model reads, reasons over, and can be summarized — then it is subject to probabilistic rewriting and the linkage invariant is unenforceable. If it is metadata — a slot the runtime injects and the model never sees as text — then compaction cannot touch it and the invariant holds by construction. Concretely: a system crosses into the failure regime the moment it serializes span context into a field the summarizer is allowed to compress. The guardrail is a **two-tier envelope**: the human/model-readable task description (compressible) and a separate `span_context` object (non-compressible, integrity-checked, passed through verbatim). On resume after compaction, the runtime must re-validate the context token's checksum and re-open the parent span if the child's lifetime still extends past the parent's recorded end — or, if the parent is genuinely closed, convert the edge to a span *link* and re-derive flags from the parent's recorded value, never from the local sampler. ## Operational Effect Without the guardrail, the observable symptom is a trace tree that under-reports subagent work precisely when the subagent worked *longest* — the tasks most worth tracing are the ones most likely to cross a compaction boundary, so the failure is anti-correlated with trace value. Tail-sampling amplification makes it worse: a single dropped flag in a long subagent run can discard an entire subtree, so a 0.1-rate sampler can silently delete 100% of a trace's leaf spans. The fix is not "sample more" (that increases cost without restoring linkage) but "carry context as integrity-checked metadata and re-derive flags from the recorded parent." The following guard implements the validation and the resume-time repair. ```python import hashlib import time from dataclasses import dataclass class SpanLinkageError(RuntimeError): """Raised when a child span's parent reference or flags violate the linkage invariant.""" pass @dataclass(frozen=True) class SpanContext: trace_id: str span_id: str trace_flags: int # 0x01 = sampled checksum: str # sha256 of trace_id|span_id|trace_flags @staticmethod def make(trace_id: str, span_id: str, trace_flags: int) -> "SpanContext": raw = f"{trace_id}|{span_id}|{trace_flags}".encode() return SpanContext(trace_id, span_id, trace_flags, hashlib.sha256(raw).hexdigest()) def verify(self) -> None: raw = f"{self.trace_id}|{self.span_id}|{self.trace_flags}".encode() if hashlib.sha256(raw).hexdigest() != self.checksum: raise SpanLinkageError( f"span context checksum mismatch for trace {self.trace_id}: " "context was paraphrased or mutated across the compaction boundary" ) @dataclass class Span: trace_id: str span_id: str parent_span_id: str | None trace_flags: int start_ns: int end_ns: int | None = None def emit_child_span(parent: Span, ctx: SpanContext) -> Span: """Emit a child span, enforcing the linkage invariant at resume time.""" ctx.verify() # reject paraphrased tokens outright if ctx.trace_flags != parent.trace_flags: raise SpanLinkageError( f"trace_flags divergence: parent 0x{parent.trace_flags:02x} " f"vs child 0x{ctx.trace_flags:02x} on trace {ctx.trace_id}; " "child sampler overrode parent sampling decision" ) if parent.end_ns is not None and parent.end_ns < time.time_ns(): # Parent is closed; a child edge would dangle. Convert to link, # do not fabricate a parent-child relationship. raise SpanLinkageError( f"parent span {parent.span_id} closed at {parent.end_ns} " f"before child emission; emit as span link, not child" ) return Span( trace_id=ctx.trace_id, span_id=f"child-{ctx.span_id[-6:]}", parent_span_id=ctx.span_id, trace_flags=ctx.trace_flags, start_ns=time.time_ns(), ) ```