# Where must an instance reconcile causal span links before replay when a parent span's tool result is non-deterministic and the child span's inputs were sampled from it? **Date of Record:** 2026 November 26 **Scope:** Applies to agent runtimes that emit causal span trees (parent/child links across tool calls, LLM invocations, and handoffs) and that support span-level replay for debugging or regression. Does not apply to purely observational logging without replay, nor to deterministic function-call traces with no sampling or external state. ## Core Distinction A trace is **causally linked** when every child span records the exact byte-level inputs it consumed from its parent's output. A trace is **merely temporally ordered** when child spans record only timestamps and a parent span ID. Most agent observability stacks ship the latter and label it the former. The distinction matters only under replay: if a parent span's output was non-deterministic (an LLM sampling at temperature > 0, a tool returning a set with unstable iteration order, a retrieval hit list with tie-broken scores), then a child span replayed against a *re-executed* parent will receive different inputs than it originally consumed. The replay harness then either (a) diverges silently, producing a "successful" replay of a trace that never existed, or (b) crashes on a shape mismatch deep in the child, obscuring the actual causal break. The invariant that must hold: **a child span is replayable if and only if its recorded input payload is byte-identical to the parent output it was originally bound to, and the harness verifies this binding before executing the child.** Span IDs and timestamps are not sufficient. The binding must be a content hash over the exact serialized payload the child consumed, stored on the child at emission time. ## What Was Observed A three-hop agent chain: `plan` (LLM, temp 0.7) → `search` (tool, returns ranked list) → `summarize` (LLM, temp 0.2). The trace store captured spans with `parent_span_id` and wall-clock timestamps only. During a replay of a reported failure, the harness re-executed `plan`, which sampled a *different* tool-call argument set than the original run (one query term differed). `search` was re-executed against the new query and returned a different ranked list. `summarize` was re-executed against the new list and produced fluent, plausible output. The replay reported **status: OK**. The original failure did not reproduce, and the on-call engineer concluded the bug was "intermittent" and closed the ticket. The failure was not intermittent. The replay harness had silently substituted a counterfactual trace. The child spans' recorded inputs were never checked against the re-executed parent outputs, because they were never recorded. The harness's success criterion was "no exceptions thrown during re-execution," which is a liveness property, not a fidelity property. A second observed mode, same root cause, opposite symptom: when `search` returned a list whose length changed (7 hits vs. 4 hits), `summarize`'s prompt template indexed into position 2, which existed in one run and not the other. The replay raised `IndexError` inside the child, which the harness attributed to the child span's code — sending an engineer to inspect `summarize` for a bug that lived entirely in the missing causal binding. ## Condition of Validity The content-hash binding is valid under these conditions, and only these: 1. **The parent output is serialized deterministically before hashing.** JSON with sorted keys, floats canonicalized, no `set` iteration. If the parent emits a Python `set` or a dict with insertion-order dependence, the hash over the serialized form is not stable across processes and the binding is worthless. 2. **The child records the hash of the payload it *actually consumed*, not the hash of the parent's full output.** A child that reads only `results[0:3]` must hash the slice it read. Hashing the full parent output over-binds (any change in `results[4:]` invalidates a child that never saw it) and under-protects (a child reading a *different* slice of an identical full output is not detected). 3. **Replay is *anchored*, not *regenerated*, at non-deterministic spans.** The harness must replay children against the *recorded* parent output by default, and only re-execute a non-deterministic parent when explicitly instructed to explore a counterfactual branch. Regeneration is a different operation from replay and must be labeled as such in the output. 4. **The hash is compared before the child executes, not after.** A post-hoc comparison detects divergence but does not prevent the child from mutating shared state (caches, memory stores, external side effects) under false inputs. When any of these fails, the trace is at best temporally ordered and the replay harness must refuse to claim fidelity. ## Decision Boundary The boundary is between **fidelity replay** and **counterfactual exploration**. They are not the same operation and must not share a success signal. - **Fidelity replay** answers: "does this exact sequence of inputs reproduce this exact failure?" It requires anchored parents, content-hash bindings on every child, and pre-execution verification. Its success criterion is byte-identical child inputs and a matching terminal outcome. - **Counterfactual exploration** answers: "what would have happened if `plan` had sampled differently?" It regenerates non-deterministic spans and is useful for robustness testing. Its success criterion is distributional, not identical. The failure mode documented here is that harnesses default to counterfactual exploration while reporting fidelity replay. The decision rule: **if any ancestor span between the replay root and the target span is non-deterministic and was regenerated, the replay must be tagged `counterfactual` and must not be cited as evidence that a bug is fixed or intermittent.** A trace with a missing content-hash binding on any child is not eligible for fidelity replay at all — it should be rejected at harness entry, not silently downgraded. ## Operational Effect The observable consequence of getting this wrong is **phantom non-reproducibility**: bugs that are perfectly deterministic in production appear intermittent under replay because the replay is not replaying them. Teams then add retries, widen timeouts, and eventually close tickets as "cannot reproduce," while the actual defect remains live. The cost is not the failed replay — it is the false negative that terminates investigation. The fix is cheap and must be enforced at emission time, not at replay time: every child span carries `parent_output_hash` over the exact payload slice it consumed, and every non-deterministic span carries `determinism: sampled` with the seed and temperature. At replay, the harness computes the hash of the anchored parent payload and compares before dispatching the child. On mismatch, it raises a specific error rather than proceeding — because proceeding is how the counterfactual gets laundered into a fidelity claim. ```python import hashlib import json from dataclasses import dataclass from typing import Any class CausalBindingError(RuntimeError): """Raised when a child span's recorded input hash does not match the payload it would receive from its (anchored) parent during replay. This indicates the replay is counterfactual, not fidelity, or that the trace is missing a binding and cannot be faithfully replayed.""" @dataclass(frozen=True) class Span: span_id: str parent_span_id: str | None determinism: str # "deterministic" | "sampled" output: Any # For child spans: hash over the exact slice of parent output consumed. parent_output_hash: str | None # For parent spans: the exact slice children are allowed to bind to. consumed_slice: Any = None def canonical_hash(payload: Any) -> str: """Deterministic hash over a serialized payload. Rejects non-canonical types (sets, unordered dicts) that would make the binding unstable across runs.""" if isinstance(payload, (set, frozenset)): raise CausalBindingError( "Cannot hash a set: iteration order is not stable across processes. " "Serialize to a sorted list before binding." ) serialized = json.dumps(payload, sort_keys=True, separators=(",", ":"), default=str) return hashlib.sha256(serialized.encode("utf-8")).hexdigest() def replay_child(parent: Span, child: Span, *, allow_counterfactual: bool = False) -> Any: """Replay a child span against an anchored parent. Verifies the causal binding before executing; refuses to proceed on mismatch unless the caller explicitly opts into counterfactual exploration.""" if child.parent_output_hash is None: raise CausalBindingError( f"Child span {child.span_id} has no parent_output_hash. " "Trace is temporally ordered, not causally linked; ineligible for fidelity replay." ) if parent.determinism == "sampled" and parent.consumed_slice is None: raise CausalBindingError( f"Parent span {parent.span_id} is sampled but exposes no consumed_slice; " "cannot anchor child replay. Re-execution would be counterfactual." ) anchored_payload = parent.consumed_slice if parent.consumed_slice is not None else parent.output actual_hash = canonical_hash(anchored_payload) if actual_hash != child.parent_output_hash: if not allow_counterfactual: raise CausalBindingError( f"Causal binding broken: child {child.span_id} recorded " f"hash {child.parent_output_hash[:12]}… but anchored parent " f"{parent.span_id} yields {actual_hash[:12]}…. " "This replay would be counterfactual, not fidelity. " "Pass allow_counterfactual=True to explore, and tag the result accordingly." ) # Counterfactual path: proceed, but the caller must not report this as fidelity. return {"counterfactual": True, "child": child.span_id, "payload": anchored_payload} return {"counterfactual": False, "child": child.span_id, "payload": anchored_payload} ```