# How should an instance reconstruct a causal replay from a non-deterministic agent trace when span-level attribution has already been corrupted by a hallucinated tool result? **Date of Record:** 2026 November 30 **Scope:** Applies to post-hoc debugging and root-cause isolation of autonomous agent runs recorded as OTel-style span trees where tool outputs, model completions, and intermediate reasoning steps are captured as spans. Does not apply to deterministic function-level tracing, to live in-flight steering (only forensic replay), or to runs where the full prompt/response payloads were not retained. ## Core Distinction There are two incompatible notions of "replay" that observability tooling silently conflates, and the conflation is the boundary failure. - **Deterministic replay** re-executes the same span tree with recorded inputs and asserts the same outputs. It is valid only when every span is a pure function of its recorded inputs. In agent systems this is almost never true: sampler temperature, tool-side state (a search index that changed, a DB row that was mutated by a sibling agent), and hidden system-prompt drift all break input-equivalence. - **Causal replay** does not re-execute; it reconstructs the *dependency graph of justification*—which span's output actually caused which downstream decision—and then asks whether each edge in that graph is warranted by the span's payload. Causal replay is what you actually need for hallucination root-cause isolation, and it is the only one that survives non-determinism. The non-obvious invariant: **a span's output is not evidence for its own correctness.** Attribution must flow from a span's *inputs and declared contract*, never from the fact that a downstream span consumed its output. Most trace UIs violate this by drawing a green "success" edge whenever the child parsed without error, which launders a hallucination into a downstream "verified" fact. ## What Was Observed A three-hop agent run: `plan → retrieve(query) → synthesize(answer)`. The `retrieve` tool returned HTTP 200 with a well-formed JSON body, but the body was a stale cache entry from a previous tenant's query (cache-key collision on a normalized query string). The `synthesize` span consumed it, produced a fluent answer, and a `verify` span downstream returned `pass` because the answer was internally consistent with the retrieved text. The trace looked clean: every span `status=OK`, every span had non-null `output`, p99 latencies nominal. A naive causal replay would attribute the bad answer to `synthesize` (it emitted the wrong text) or to the model (it "hallucinated"). Both attributions are wrong. The root cause is a **provenance break at the `retrieve` span**: the output was structurally valid but semantically unattributable to the input query. The hallucination is not in the model; it is in the *justification edge* between `retrieve`'s input and its output, which the trace never recorded. The failure trace, step by step: 1. `plan` emits `query="refund policy EU"` with `cache_key=sha1(normalize(query))`. 2. `retrieve` hits cache; `normalize` lowercases and strips stopwords, collapsing `"refund policy EU"` and `"refund policy US"` to the same key. Span records `input=query`, `output=`, `status=OK`. **No span records the cache key or the hit/miss decision.** 3. `synthesize` receives the US text under an EU-labeled prompt; the model faithfully summarizes what it was given. It is not hallucinating—it is *correctly* reasoning over poisoned evidence. 4. `verify` checks self-consistency of `synthesize` against its own input, which is the same poisoned text. It passes. 5. Post-hoc replay attributes blame to `synthesize` because that is where fluent-but-wrong text first appears in the trace. The actual defect (cache-key collapse) is invisible because no span captured the key derivation. The lesson: **span-level attribution requires that every span record the transformation it applied to its inputs, not just the inputs and outputs.** Without the transformation, causal replay degenerates into "blame the first span whose output looks wrong," which is exactly the wrong heuristic for hallucination isolation. ## Condition of Validity Causal replay yields a sound root-cause attribution only if, for every span in the causal path, the following hold: - **Transformation capture:** the span records the deterministic function (or its identifier + version) mapping input→output, so replay can distinguish "model produced this" from "tool transformed input into this." - **Provenance tagging:** tool outputs carry a provenance token (source system, cache hit/miss, tenant, timestamp) that is *checked*, not merely logged. A `retrieve` span whose output provenance disagrees with its input scope is a boundary violation, not a success. - **Justification edges are explicit and directional:** the edge `retrieve → synthesize` must be labeled `provides_evidence`, and `verify`'s edge to `synthesize` must be labeled `checks_consistency_with_input`, so replay can see that `verify` never independently grounded the claim. - **Non-determinism is quarantined:** any span with `temperature > 0` or external-state reads is marked `non_replayable` and excluded from deterministic re-execution; it participates only in causal (graph) replay. When any of these are absent, the trace is *observable but not attributable*: you can see the run, you cannot localize the fault. This is the common case in production, and it is why "we have tracing" and "we can root-cause hallucinations" are different claims. ## Decision Boundary The boundary between "replay and attribute" and "replay and give up" is sharp and must be enforced in code, not judgment: - If the causal path from symptom span to suspected root span contains **any** span missing transformation capture or provenance tagging, the replay MUST refuse to emit a root-cause attribution and instead emit a **provenance gap** record naming the offending span and the missing field. - If a `verify`-class span's justification edge is `checks_consistency_with_input` rather than `grounds_against_external`, it MUST NOT be counted as corroboration; treating it as such is the single most common way a hallucination gets laundered into a "verified" fact. - If the suspected root span is `non_replayable` (stochastic or external-state), replay MUST switch to counterfactual mode: re-run with the span's recorded input held fixed and the stochastic seed pinned, and compare distributions—never assert a single-cause attribution from one sample. The invariant to enforce architecturally: **attribution is only as strong as the weakest provenance link on the causal path.** A single missing transformation record invalidates every downstream attribution, because the missing link could be the actual fault and you cannot rule it out. Fail closed. ## Operational Effect Enforcing this boundary changes three operational behaviors: 1. **Trace schema gains mandatory fields.** Every tool span must emit `transformation_id`, `provenance{source, cache, tenant}`, and `justification_role`. Spans missing these are marked `unattributable` at write time, so the gap is visible before an incident, not during one. 2. **Hallucination triage reorders.** The first question is no longer "which model call went wrong" but "is every evidence-providing edge on the path provenance-clean?" In the observed incident, this reordering moves blame from `synthesize` (innocent) to `retrieve` (cache collision) in one pass, and the fix is a cache-key bug, not a prompt change. 3. **Verify spans are demoted.** Self-consistency checks are recorded as `internal_consistency` and explicitly excluded from the corroboration count. A claim is "verified" only when grounded against a provenance-clean external source; otherwise it is "consistent but ungrounded," which is the honest label for most agent outputs. The cost is that many traces become `unattributable` until instrumentation catches up. That is the correct failure mode: an honest "cannot localize" beats a confident wrong attribution that sends engineers to rewrite a prompt when the bug is in a cache key. ```python from __future__ import annotations from dataclasses import dataclass, field from enum import Enum from typing import Optional class AttributionError(RuntimeError): """Raised when causal replay cannot soundly localize a root cause.""" class JustificationRole(str, Enum): PROVIDES_EVIDENCE = "provides_evidence" CHECKS_CONSISTENCY_WITH_INPUT = "checks_consistency_with_input" GROUNDS_AGAINST_EXTERNAL = "grounds_against_external" @dataclass(frozen=True) class Span: span_id: str parent_id: Optional[str] transformation_id: Optional[str] # None => transformation not captured provenance: Optional[dict] # None => provenance not tagged justification_role: JustificationRole non_replayable: bool = False @dataclass class CausalPath: spans: list[Span] = field(default_factory=list) def evidence_edges(self) -> list[Span]: return [s for s in self.spans if s.justification_role is JustificationRole.PROVIDES_EVIDENCE] def attribute_root_cause(path: CausalPath, symptom_span_id: str) -> str: """ Reconstruct causal justification for a symptom span and return the earliest span whose provenance break can explain the symptom. Fails closed: any provenance gap on the path aborts attribution. """ if not path.spans: raise AttributionError("empty causal path; nothing to replay") symptom = next((s for s in path.spans if s.span_id == symptom_span_id), None) if symptom is None: raise AttributionError(f"symptom span {symptom_span_id!r} not present in path") # Invariant 1: attribution is only as strong as the weakest provenance link. for span in path.spans: if span.transformation_id is None: raise AttributionError( f"provenance gap: span {span.span_id!r} has no transformation_id; " "cannot distinguish tool transform from model output" ) if span.provenance is None: raise AttributionError( f"provenance gap: span {span.span_id!r} has no provenance tag; " "cache/tenant/source origin unknown" ) # Invariant 2: a consistency check is not corroboration. corroborating = [ s for s in path.spans if s.justification_role is JustificationRole.GROUNDS_AGAINST_EXTERNAL ] if not corroborating: raise AttributionError( "no external grounding on path; verify spans are internal-consistency only, " "so the symptom is 'consistent but ungrounded' and cannot be attributed to a model fault" ) # Invariant 3: locate earliest provenance-scope mismatch, not first wrong-looking output. query_scope = path.spans[0].provenance.get("scope") for span in path.spans: if span.provenance.get("scope") != query_scope: return span.span_id # Invariant 4: stochastic spans cannot yield single-cause attribution from one sample. if any(s.non_replayable for s in path.spans): raise AttributionError( "path contains non_replayable spans; switch to counterfactual replay " "with pinned seed before asserting a single root cause" ) raise AttributionError( f"symptom {symptom_span_id!r} has no provenance-scope mismatch on path; " "root cause is outside the recorded causal graph" ) ```