# Which invariants prevent causal trace graphs from silently re-parenting tool effects onto the wrong retrieval node **Date of Record:** 2026 November 27 **Scope:** Applies to any agent runtime that constructs a causal trace DAG by joining prompt spans, retrieval spans, tool-call spans, and outcome spans via parent/child span IDs, especially when spans are emitted asynchronously by separate subsystems (LLM gateway, vector store client, tool sandbox) and reconciled post-hoc. Does not apply to single-process synchronous agents that emit a single linear trace with a single clock. ## Core Distinction A causal trace graph is not a log. A log answers "what happened, in order." A causal trace graph asserts a *causal edge*: "this retrieval's content caused this tool invocation's arguments." That assertion is a claim about information flow, and it can be true or false independently of whether every span was recorded. The failure mode here is **silent re-parenting**: when the true parent span of a tool effect is missing, late, or has a colliding span ID, the reconciler attaches the tool span to the nearest *plausible* ancestor — typically the most recent retrieval span in the same turn — producing a graph that is internally consistent, passes schema validation, renders cleanly in the trace viewer, and is causally wrong. The distinction that matters: **span completeness is not causal correctness.** A DAG with 100% span coverage can still encode a false causal edge, and the falseness is invisible because the edge has no annotation distinguishing "observed parent" from "inferred parent." ## What Was Observed A tool-calling agent (retrieval-augmented, ~9 tools, average 4.2 tool calls per task) emitted spans from three clocks: the LLM gateway stamped prompt spans with its own monotonic clock at request dispatch; the retrieval client stamped retrieval spans at response receipt; the sandbox stamped tool spans at execution start. All three were normalized to wall-clock at ingestion, then joined by `trace_id` + `parent_span_id`. The reconciler had a fallback: if a span's declared `parent_span_id` did not resolve within a 500 ms grace window, it was re-parented to the most recent span in the same trace with an earlier normalized start time. This fallback fired on roughly 1.8% of tool spans under load, because the sandbox's clock drifted up to 700 ms behind the gateway under CPU contention, so the *declared* parent (the prompt span that generated the tool call) sometimes had a normalized start time *later* than the tool span it supposedly caused. The reconciler saw a child older than its declared parent, treated the parent as unresolvable, and re-parented the tool span to the preceding retrieval span. The resulting traces were indistinguishable from correct ones at the schema level. The damage surfaced only during a retrieval-quality audit: a retrieval source was credited with a 31% "causal influence on tool outcomes" rate. When the audit replayed the traces, the credited retrievals had in several cases returned content that was never in the tool call's arguments and could not have been, because the tool call was issued from a prompt segment that predated the retrieval. The graph had manufactured a causal edge from a coincidental temporal adjacency. The second-order effect was worse: the same traces fed an automated retriever-tuning loop that up-weighted the falsely credited sources, which then dominated future retrievals, which then appeared even more "causally influential" because they were now frequently the most recent retrieval before any tool call. A false edge became a self-reinforcing prior. ## Condition of Validity The invariant that must hold for a trace edge to be trusted is: > **A causal edge `R → T` (retrieval to tool effect) is valid only if (a) `T.parent_span_id` explicitly equals `R.span_id`, AND (b) the reconciler recorded that the edge was *observed*, not *inferred*, AND (c) the clock skew between the two emitters was bounded below the inter-span interval at emission time.** Three conditions, all necessary: 1. **Explicit parentage.** Re-parenting is never permitted to produce an edge that is rendered identically to an observed edge. An inferred edge must carry a distinct provenance tag (`edge.kind = "inferred_temporal"`) and must be excluded from any causal-influence metric. 2. **Provenance preservation.** The reconciler must not overwrite the declared `parent_span_id` when it fails to resolve. It must retain the unresolved ID and emit a separate `unresolved_parent` record. Overwriting destroys the evidence needed to detect the failure. 3. **Skew bound.** The grace-window fallback is only sound if the maximum emitter clock skew is strictly less than the minimum inter-span emission interval. If skew can exceed the interval (as here, 700 ms skew vs. sub-500 ms tool-call gaps), *temporal adjacency carries zero causal information* and the fallback must be disabled entirely, not merely tightened. Condition (c) is the non-obvious one. Operators reflexively fix re-parenting bugs by shrinking the grace window, but the window is not the problem — the problem is that the fallback assumes ordering information survives clock normalization. When skew ≥ interval, it does not, and no window size repairs it. ## Decision Boundary The boundary between a usable trace graph and a poisoned one is whether **inferred edges are separable from observed edges at query time.** Concretely: - If every edge carries `edge.kind ∈ {observed, inferred_temporal}` and every downstream consumer (influence metrics, retriever tuning, incident replay) filters to `observed`, the graph is usable even with 2% inferred edges — they are quarantined noise. - If inferred edges are merged into the observed edge set (as in the failure above, where re-parenting wrote the edge with no tag), the graph is unusable for any causal claim, regardless of how few inferred edges exist, because there is no way to know *which* edges are which after the fact. The decision rule: **never let a reconciler emit an edge whose provenance cannot be recovered from the edge record alone.** If provenance must be reconstructed from a separate join or from logs, the boundary has already been crossed. A secondary boundary: the retriever-tuning loop must consume only `observed` edges *and* must treat the absence of an observed edge as evidence of no influence, not as missing data to be imputed. Imputing the inferred edge back into the tuning signal is how the false prior formed. ## Operational Effect With the invariant enforced, the observed 1.8% re-parenting rate became a 1.8% `unresolved_parent` rate — visible, bounded, and excluded from causal metrics. The retriever-influence audit recovered to a 4% influence rate consistent with replay. The tuning loop, restricted to observed edges, stopped reinforcing the falsely credited sources within two tuning cycles. Without it, the failure is silent and self-amplifying: the trace viewer shows a coherent causal story, the metric is plausible, and the feedback loop converts a transient clock-skew artifact into a persistent retrieval bias. The general lesson for agent observability: **a causal trace graph is only as trustworthy as its weakest provenance guarantee, and re-parenting is the operation that silently deletes provenance.** Any reconciler that can invent an edge must tag it, and any consumer that can act on an edge must refuse untagged ones. ```python from dataclasses import dataclass, field from enum import Enum from typing import Optional class TraceIntegrityError(RuntimeError): """Raised when a reconciler would produce an untraceable causal edge.""" class EdgeKind(str, Enum): OBSERVED = "observed" INFERRED_TEMPORAL = "inferred_temporal" @dataclass class Span: span_id: str trace_id: str declared_parent_id: Optional[str] start_ns: int emitter: str @dataclass class Edge: parent_id: str child_id: str kind: EdgeKind # Provenance must be recoverable from the edge record alone. provenance: dict = field(default_factory=dict) def reconcile( spans: dict[str, Span], max_emitter_skew_ns: int, min_inter_span_interval_ns: int, ) -> list[Edge]: """ Build causal edges. Invariant: no edge is emitted as OBSERVED unless the declared parent resolved AND skew < interval. Inferred edges are tagged and the declared parent is never overwritten. """ edges: list[Edge] = [] # Condition (c): if skew can exceed the inter-span interval, temporal # adjacency is causally uninformative. The fallback must be disabled, # not merely windowed. temporal_fallback_sound = max_emitter_skew_ns < min_inter_span_interval_ns for child in spans.values(): parent_id = child.declared_parent_id if parent_id is None: continue parent = spans.get(parent_id) if parent is not None and parent.start_ns <= child.start_ns: edges.append( Edge( parent_id=parent.span_id, child_id=child.span_id, kind=EdgeKind.OBSERVED, provenance={"resolved": True, "emitters": [parent.emitter, child.emitter]}, ) ) continue # Declared parent missing or clock-inverted (child appears older). # Preserve the declared parent; never overwrite it. if not temporal_fallback_sound: # Cannot infer. Record unresolved; do NOT invent an edge. edges.append( Edge( parent_id=parent_id, child_id=child.span_id, kind=EdgeKind.INFERRED_TEMPORAL, provenance={ "resolved": False, "reason": "skew_exceeds_interval", "declared_parent": parent_id, "fallback_disabled": True, }, ) ) continue # Fallback is sound: attach to nearest earlier span, but TAG it. candidates = [s for s in spans.values() if s.start_ns < child.start_ns] if not candidates: edges.append( Edge( parent_id=parent_id, child_id=child.span_id, kind=EdgeKind.INFERRED_TEMPORAL, provenance={ "resolved": False, "reason": "no_earlier_span", "declared_parent": parent_id, }, ) ) continue nearest = max(candidates, key=lambda s: s.start_ns) edges.append( Edge( parent_id=nearest.span_id, child_id=child.span_id, kind=EdgeKind.INFERRED_TEMPORAL, provenance={ "resolved": False, "reason": "declared_parent_unresolvable", "declared_parent": parent_id, "reparented_to": nearest.span_id, }, ) ) return edges def causal_influence_metric(edges: list[Edge]) -> dict[str, int]: """ Downstream consumer. Refuses to act on untagged edges and refuses to silently drop them — dropping hides the integrity problem. """ for e in edges: if e.kind not in (EdgeKind.OBSERVED, EdgeKind.INFERRED_TEMPORAL): raise TraceIntegrityError( f"edge {e.parent_id}->{e.child_id} has unrecognized kind {e.kind!r}" ) if e.kind == EdgeKind.INFERRED_TEMPORAL and "declared_parent" not in e.provenance: raise TraceIntegrityError( f"inferred edge {e.parent_id}->{e.child_id} lost declared parent; " "provenance not recoverable from edge record" ) observed = [e for e in edges if e.kind == EdgeKind.OBSERVED] inferred = [e for e in edges if e.kind == EdgeKind.INFERRED_TEMPORAL] # Invariant: inferred edges are excluded, not imputed. if inferred and not observed: raise TraceIntegrityError( "all edges inferred; causal metrics would be fabricated" ) return { "observed_edges": len(observed), "quarantined_inferred_edges": len(inferred), } ```