# When must an instance Reject a Replayed Trajectory: Causal Trace Linking Breaks Under Idempotent-Write Masking **Date of Record:** 2026 November 30 **Scope:** Applies to agent runtimes that reconstruct execution state by replaying recorded tool-call trajectories (span trees, causal event logs) for observability, anomaly detection, or post-hoc verification. Does not apply to live single-shot inference without recorded tool side effects, nor to pure prompt logging where no causal linkage between spans is asserted. ## Core Distinction There are two fundamentally different things an observability pipeline can replay: the *token stream* an agent emitted, and the *causal graph* of side effects its tool calls produced. Token-stream replay is a deterministic function of recorded bytes—re-run the model with the same sampler seed and context and you get the same tokens (modulo floating-point non-associativity). Causal-graph replay is *not* deterministic, because the graph's edges depend on the environment's response to each tool call, and the environment is stateful and mutating. The non-obvious failure lives exactly at the seam. A replay harness reconstructs the trajectory by re-issuing each recorded tool call in recorded order, then diffing the observed responses against the recorded ones to detect drift, tampering, or model divergence. The implicit invariant is: *if the replayed response equals the recorded response at every step, the trajectory is causally faithful.* This invariant is false under **idempotent-write masking**: a write tool whose second invocation is a no-op returns the same success payload as its first invocation, so replay silently "passes" even when the original trajectory's causal ordering was wrong, or when a step was skipped, or when a concurrent agent mutated the resource between steps. The replay cannot distinguish "the write happened as recorded" from "the write had already happened, so this call was absorbed." ## What Was Observed A three-agent pipeline (planner → executor → auditor) wrote to a shared resource registry via an idempotent `upsert_resource(key, value)` tool. The registry returned `{"status": "ok", "version": N}` where `version` incremented only on actual mutation. During a routine anomaly-detection replay of a 41-step trajectory, the harness re-issued all 41 tool calls and reported **zero response mismatches**. Yet a downstream auditor had flagged the original run as anomalous because the executor's span showed it reading a `version` of 7 for a key that the planner's span had written at `version` of 9. The trace, reconstructed: 1. Planner span `p-12` called `upsert_resource("cfg.threshold", 0.8)` → returned `version: 9`. 2. Executor span `e-03` called `read_resource("cfg.threshold")` → returned `version: 7, value: 0.6`. 3. Executor span `e-04` called `upsert_resource("cfg.threshold", 0.8)` → returned `version: 9` (idempotent no-op; value already 0.8 at v9). The recorded `e-03` read of `version: 7` is causally impossible if `p-12` truly completed before `e-03` began. The real sequence was: `e-03` read v7, *then* `p-12` wrote v9, *then* `e-04`'s write was absorbed. The span tree's parent-child timestamps were recorded from the agents' local clocks, which were skewed by ~40ms across hosts, so the log *looked* ordered `p-12 → e-03 → e-04`. Replay re-issued the calls in log order: `p-12` (writes v9, but v9 already exists → returns v9, matches), `e-03` (reads v9... wait, recorded was v7). Here is the masking. The replay harness had been configured to *reset the registry to a snapshot* before replaying. The snapshot was taken at trajectory start, so `cfg.threshold` was at v7. Replay: `p-12` upsert 0.8 → v9 (matches recorded v9). `e-03` read → v9. **Mismatch.** The harness *should* have flagged it. Instead, the harness's diff function compared only `status` fields for read tools and only `version` for write tools—and `e-03` is a read, so it compared `status: ok == ok`. The `value` and `version` fields of read responses were never diffed. Three consecutive replays passed. The anomaly was caught only by a human reading the auditor's separate flag. The deeper invariant failure: the replay harness treated *response equality* as *causal fidelity*, but idempotent writes make response equality compatible with at least two distinct causal histories (write-then-read vs. read-then-write-absorbed). Equality of observations does not imply equality of the causal graph when the observation function is non-injective. ## Condition of Validity The "replay passes ⇒ trajectory faithful" inference is valid only when the observation function from world-state to tool-response is **injective over the relevant state space**—i.e., no two distinct world states produce identical responses for the tools being replayed. Idempotent writes, `SET`-style overwrites, cache hits, and any tool whose response is a function of *request* rather than *resulting state* all violate injectivity. Formally: if `f(s₁) = f(s₂)` for `s₁ ≠ s₂`, then observing `f(s)` cannot pin down `s`, and replay-diff cannot certify the transition. The invariant a replay harness must actually enforce is stronger and state-based, not response-based: **after each replayed step, the reconstructed world-state digest must equal the recorded post-step state digest.** This requires the runtime to have recorded a state digest (or version vector, or per-resource version map) at each span boundary—not merely the tool's response payload. Absent that, replay can only detect *divergence*, never *fidelity*, and must never be used to clear a trajectory. ## Decision Boundary An instance must **reject** a replayed trajectory as unverifiable—and must not emit a "clean" anomaly verdict—when any of the following hold: - The trajectory contains at least one tool call classified as idempotent-write or overwrite-semantics (`upsert`, `set`, `put`, `create-if-absent`) **and** no per-step state digest was recorded. - Span ordering was established solely from wall-clock timestamps across more than one host/clock domain, with no logical-clock (Lamport/vector) ordering recorded. - The response-diff function compares a strict subset of response fields (e.g., `status` only) for any tool whose full response is state-bearing. - A read tool's response was compared but the read's *observed version* was not checked for monotonicity against prior writes to the same key in the same trajectory. An instance may **accept** replay as fidelity evidence only when a state digest is present at every span boundary and the digest chain is contiguous (no gaps), or when all tools in the trajectory are provably injective (pure reads against an immutable snapshot, append-only logs with monotonic offsets). The boundary is not "did replay produce matching responses"—it is "could two distinct causal histories have produced these responses." If yes, the trajectory is under-determined and the replay verdict is void. ## Operational Effect The practical consequence is a change in what the observability layer must *capture*, not just what it computes. Recording tool responses is insufficient for causal replay; the runtime must record a **state witness** per span: a compact digest of the resources the span touched (key → version, or a Merkle root over the touched keyspace). The digest is cheap (a hash of version counters), but it is the only artifact that makes replay-diff injective. Without it, idempotent-write masking converts the replay harness from a verifier into a rubber stamp, and anomaly detection silently inherits the blind spot: real ordering violations (read-before-write races across agents, skipped steps absorbed by idempotency, concurrent mutations between spans) all present as clean replays. The second effect is on anomaly-detection thresholds. A harness that has been passing replays under masking will have a falsely low baseline anomaly rate; when a state witness is introduced, the apparent anomaly rate jumps—not because behavior changed, but because previously invisible causal violations become visible. Operators must treat that jump as a measurement-instrument correction, not a regression, and must re-baseline rather than page on it. ```python import hashlib from dataclasses import dataclass from typing import Optional class ReplayFidelityError(RuntimeError): """Raised when a replayed trajectory cannot certify causal fidelity.""" @dataclass(frozen=True) class Span: span_id: str tool: str idempotent_write: bool response: dict state_digest: Optional[str] # digest over touched keyspace post-step logical_clock: Optional[int] def _digest_touched(resource_versions: dict) -> str: payload = "|".join(f"{k}={v}" for k, v in sorted(resource_versions.items())) return hashlib.sha256(payload.encode()).hexdigest() def certify_replay( spans: list[Span], reconstructed_versions: dict, recorded_versions: dict, ) -> None: """ Certify that a replayed trajectory is causally faithful. Rejects when idempotent-write masking or clock-skew ordering makes response-equality an insufficient witness of causal fidelity. """ has_idempotent_write = any(s.idempotent_write for s in spans) has_state_witness = all(s.state_digest is not None for s in spans) single_clock_domain = all(s.logical_clock is not None for s in spans) if has_idempotent_write and not has_state_witness: raise ReplayFidelityError( "idempotent-write masking: trajectory contains upsert/overwrite " "tools but no per-span state digest; response equality cannot " "distinguish write-then-read from read-then-absorbed-write. " "Replay verdict is void." ) if not single_clock_domain and not has_state_witness: raise ReplayFidelityError( "causal ordering under-determined: spans ordered only by " "wall-clock across multiple clock domains and no logical clock " "or state witness recorded; cannot certify edge direction." ) # State-witness path: reconstructed post-step digest must equal recorded. for span in spans: if span.state_digest is None: continue observed = _digest_touched(reconstructed_versions) if observed != span.state_digest: raise ReplayFidelityError( f"state-witness mismatch at span {span.span_id}: " f"reconstructed={observed[:12]} recorded={span.state_digest[:12]}" ) # Monotonicity check on any read that observes a versioned key. seen_versions: dict[str, int] = {} for span in spans: for key, ver in span.response.get("observed_versions", {}).items(): if key in seen_versions and ver < seen_versions[key]: raise ReplayFidelityError( f"non-monotonic read at span {span.span_id}: key {key} " f"observed v{ver} after prior v{seen_versions[key]}; " f"indicates cross-agent ordering violation masked by replay." ) seen_versions[key] = max(seen_versions.get(key, ver), ver) def replay_and_certify(spans: list[Span], registry) -> None: """Re-issue calls in recorded order, then certify via state witness.""" reconstructed = {} for span in spans: result = registry.invoke(span.tool, span.response.get("args", {})) reconstructed.update(result.get("touched_versions", {})) certify_replay(spans, reconstructed, registry.snapshot_versions()) ```