# What structural signals indicate causal span-link corruption when an observability plane re-parents agent spans across a mid-execution context compaction **Date of Record:** 2026 November 26 **Scope:** Applies to agent runtimes that emit distributed traces (OpenTelemetry-style span trees) through an observability plane that performs span re-parenting, late-arrival stitching, or trace-context repair. Does not apply to single-turn, single-span inference calls with no tool fan-out and no context compaction. ## Core Distinction The failure mode is not "missing spans." Missing spans are loud: the trace is visibly short, the parent ID dangles, the dashboard shows an orphan. The non-obvious failure is **span re-parenting under context compaction**, where every span is present, every timestamp is monotonic, every parent ID resolves — and the trace is nonetheless causally wrong. The observability plane, attempting to repair traces whose context headers were dropped during a compaction event, infers parentage from temporal adjacency and token-budget heuristics. The result is a trace tree that is *structurally complete and semantically inverted*: the compaction span (which should be a child of the reasoning span that triggered it) becomes the parent of that reasoning span, because the compaction completes *after* the reasoning span's first token and the stitcher's "nearest preceding open span" rule latches onto the wrong node. Downstream, cost attribution walks the tree child-to-parent and charges the entire pre-compaction reasoning history to the compaction operation, while hallucination signals emitted *during* the compacted window get attached to the post-compaction span that never saw the evidence. ## What Was Observed A multi-step agent (planner → retriever → synthesizer → critic) ran against a 128k context window. At step 7 the runtime emitted a `context.compact` span and dropped the W3C `traceparent` header from the subsequent tool calls to reduce per-call overhead — a deliberate optimization, since the runtime assumed the observability plane would stitch by `session_id` and span start ordering. The stitcher's rule was: *for any span with no resolvable parent, attach to the most recent span in the same session whose end-time exceeds the orphan's start-time; if none, attach to the most recent completed span.* The trace that emerged had the following properties, all of which passed schema validation: - 41 spans, zero orphans, zero dangling parent IDs, zero negative-duration intervals. - The `context.compact` span (duration 2.1s) was the parent of the `reason.step_6` span (which started 0.4s before compaction and ended 0.9s after — i.e., it *overlapped* the compaction, so the "end-time exceeds start-time" rule selected it as parent for the compact span, inverting the true relation). - Cost attribution, computed as the sum of `token_count` over each span's subtree, charged 61,400 tokens to `context.compact` and 8,200 to `reason.step_6`. True figures were 2,100 and 67,500 respectively. The attribution was off by ~30x on the operation that actually cost nothing but a summarization call. - The critic span emitted `hallucination.flag=true` with evidence pointing to a retrieval span that, in the re-parented tree, was a *sibling* of the critic rather than an ancestor — so the evidence link resolved to a span the critic's subtree never contained. The flag was recorded, the evidence was orphaned from the flag, and the audit replay could not reconstruct which retrieved chunk triggered the suspicion. The tell was not in any single span. It was in the **shape of the tree relative to the shape of the execution**: a leaf-like operation (compaction, a pure transform with no downstream reasoning) had 7 children and the largest subtree cost in the trace, while the reasoning span that should have dominated cost had 1 child and near-zero attributed tokens. That inversion — *cost mass migrating toward the operation with the least semantic work* — is the structural signal. ## Condition of Validity This diagnosis is valid only when all of the following hold; if any fails, the trace may be genuinely complete and the cost figures genuinely correct: 1. The runtime dropped or failed to propagate `traceparent`/`tracestate` on at least one hop, forcing the observability plane into inference-based stitching. If headers propagated end-to-end, re-parenting never fires and the tree is authoritative. 2. At least one span pair **overlaps in wall-clock time** across the compaction boundary (the compaction and the reasoning step it interrupted). Non-overlapping execution cannot produce the inversion, because the "most recent open span" rule degenerates to the correct parent. 3. The observability plane's stitcher uses end-time-based or adjacency-based heuristics rather than explicit causal markers (e.g., `agent.step_index`, `caused_by` attributes, or a runtime-emitted `parent_span_id` on the compaction event). 4. Cost attribution is computed by subtree aggregation rather than by per-span `token_count` with independent accounting. Per-span accounting is immune to re-parenting; subtree aggregation is not. If condition 2 fails — the common case in non-concurrent runtimes — the invariant holds and the trace is trustworthy. The failure requires concurrency at the compaction boundary, which is precisely the case that agentic runtimes hit when a reasoning step is mid-generation while the compactor fires. ## Decision Boundary The boundary is not "is the trace complete" but **"does the trace's cost-mass distribution match the execution's semantic-work distribution."** Operationally: - **Accept the trace as causally sound** when, for every span, `subtree_token_cost / span_duration` is within an order of magnitude of the session median, *and* no span classified as a pure transform (`compact`, `summarize`, `truncate`, `embed`) has a subtree cost exceeding the median reasoning span. Transforms should be cheap; if a transform owns the cost, the tree is inverted. - **Reject and re-stitch** when a transform span's subtree cost exceeds `k ×` (k≈5) the largest reasoning span's subtree cost, *and* the transform span's children include a span whose interval overlaps the transform's own interval. Overlap + cost inversion is the joint signature; either alone is ambiguous. - **Quarantine hallucination evidence links** when the cited evidence span is not an ancestor of the flagging span in the tree. A flag whose evidence is a sibling cannot be replayed; treat the flag as unverified rather than as a false positive, because the evidence may be real and merely mis-parented. The invariant to enforce at the plane: **causal parentage must never be inferred from temporal adjacency when a transform span is involved.** Transforms are synchronous within a reasoning step and will always overlap; adjacency heuristics will always invert them. The correct rule is to require an explicit `caused_by` attribute on transform spans, emitted by the runtime at compaction time, and to refuse to stitch a transform span without it — surfacing the trace as *incomplete-but-honest* rather than *complete-but-inverted*. ## Operational Effect The practical consequence is a class of silent cost and safety regressions. Cost dashboards show compaction as the dominant expense, driving teams to optimize the summarizer (which was never expensive) instead of the retrieval fan-out (which was). Hallucination flags appear at a stable rate but their evidence links resolve to the wrong subtree, so root-cause analysis attributes hallucinations to post-compaction context loss when the actual cause was a pre-compaction retrieval mismatch — the opposite remediation. Audit replay, which reconstructs the agent's decision path by walking ancestor chains, reconstructs a path the agent never took: it sees the compactor "deciding" the reasoning step's output, because the compactor is the parent. The guardrail that bounds this is a **causality assertion at trace-close time**: for every transform span, assert that its subtree contains no span whose interval overlaps its own, and that its subtree cost is below the reasoning-span median. When the assertion fails, the plane must mark the trace `causality:unverified` and refuse to serve cost or hallucination-evidence queries from it, rather than serving inverted data with a green schema check. ```python class CausalInversionError(RuntimeError): """Raised when a trace's span tree is structurally valid but causally inverted.""" pass TRANSFORM_KINDS = {"compact", "summarize", "truncate", "embed"} COST_INVERSION_FACTOR = 5.0 def assert_causal_soundness(spans: list[dict]) -> None: """ spans: each dict has keys: span_id, parent_id, kind, start_ns, end_ns, token_count Validates that transform spans are not inverted parents of overlapping reasoning spans, and that cost mass does not migrate onto transforms. """ by_id = {s["span_id"]: s for s in spans} # Build subtree cost by walking parent links. subtree_cost = {sid: s["token_count"] for sid, s in by_id.items()} for s in sorted(spans, key=lambda x: x["start_ns"], reverse=True): pid = s["parent_id"] if pid in subtree_cost: subtree_cost[pid] += subtree_cost[s["span_id"]] reasoning_costs = [ subtree_cost[s["span_id"]] for s in spans if s["kind"] not in TRANSFORM_KINDS ] if not reasoning_costs: return reasoning_median = sorted(reasoning_costs)[len(reasoning_costs) // 2] max_reasoning = max(reasoning_costs) for s in spans: if s["kind"] not in TRANSFORM_KINDS: continue # Signature 1: transform overlaps one of its own descendants. for child in spans: if child["parent_id"] != s["span_id"]: continue overlaps = ( child["start_ns"] < s["end_ns"] and child["end_ns"] > s["start_ns"] ) if overlaps: raise CausalInversionError( f"transform span {s['span_id']} ({s['kind']}) is parent of " f"overlapping span {child['span_id']} ({child['kind']}); " f"parentage was inferred from adjacency, not causation" ) # Signature 2: transform owns cost mass disproportionate to semantic work. cost = subtree_cost[s["span_id"]] if cost > COST_INVERSION_FACTOR * max_reasoning: raise CausalInversionError( f"transform span {s['span_id']} ({s['kind']}) owns subtree cost " f"{cost} vs max reasoning subtree {max_reasoning} " f"(median {reasoning_median}); cost attribution is inverted" ) def assert_evidence_ancestry(spans: list[dict], flag_span_id: str, evidence_span_id: str) -> None: """Hallucination evidence must be an ancestor of the flagging span.""" by_id = {s["span_id"]: s for s in spans} cur = by_id.get(flag_span_id) while cur is not None: if cur["span_id"] == evidence_span_id: return pid = cur["parent_id"] cur = by_id.get(pid) if pid else None raise CausalInversionError( f"hallucination evidence {evidence_span_id} is not an ancestor of " f"flag span {flag_span_id}; evidence link is unreplayable" ) ```