# What happens when an instance replays a trajectory whose tool outputs were non-deterministic: trace divergence at the observation boundary **Date of Record:** 2026 November 28 **Scope:** Applies to any agent runtime that records full execution trajectories (prompt, tool call, tool result, model output) for replay, audit, or provenance reconstruction, where at least one tool in the trajectory is non-deterministic (live APIs, time, RNG, retrieval over a mutating index, sampling temperature > 0). Does not apply to trajectories restricted to pure deterministic tools with temperature 0 and a frozen model snapshot, which are bit-replayable by construction. ## Core Distinction The failure is not "replay produced different output." That is expected and benign. The failure is **trace diffing that treats observation divergence as decision divergence**. When an auditor replays a trajectory, the runtime re-executes tool calls and compares the new trace to the recorded one. A naive differ attributes every downstream delta to a change in the agent's *reasoning* — a provenance violation — when in fact the delta originates at a single non-deterministic observation and propagates through the model's context as a legitimate, information-preserving response. The invariant that must hold for a replay to carry any provenance weight is the **observation boundary invariant**: the recorded observation `o_i` is the *only* input the model saw at step `i`, and replay must inject `o_i` verbatim rather than re-deriving it. A replay that re-executes the tool and substitutes a fresh `o_i'` is not a replay of the decision; it is a replay of the *environment*, and any diff it produces is a diff of the environment, not of the agent. ## What Was Observed A production incident on a research agent with three tools: `web_search` (live, non-deterministic ranking), `fetch_url` (returns mutable page content), and `calculator` (deterministic). The trajectory under audit had 14 steps. At step 4, `web_search` returned a ranked list; the model picked result #2 and called `fetch_url`. At step 6 the model extracted a figure and at step 9 called `calculator`. During replay, `web_search` returned a *reordered* list (result #2 became #5). The replay harness — configured to re-execute tools — fed the new list to the model. The model, seeing a different ranking, picked result #5, fetched a different page, extracted a different figure, and produced a different final answer. The differ reported: **"decision divergence at step 4: tool selection changed."** That report was wrong in the way that matters. The model's *policy* at step 4 was unchanged: "pick the top-ranked result matching the query intent." What changed was the observation. The trace diff conflated a change in the *world* with a change in the *agent*, and because the auditor trusted the differ, the incident was misfiled as a model regression for eleven days. The concrete mechanics of the misattribution: 1. **Divergence origin is a leaf, not a root.** The first differing token appears at step 4's model output. But the *cause* is step 4's input, which was re-derived. A correct differ must locate the divergence at the earliest node whose *inputs* differ, not the earliest node whose *outputs* differ. 2. **Propagation is monotone and total.** Once `o_4` differs, every subsequent model output is conditioned on a different context, so *all* downstream steps differ. The naive differ reports N-4 divergences; the true count of *causal* divergences is 1. 3. **Re-execution is silently lossy.** `fetch_url` returned a page whose content had changed (a published figure was revised). Even if `web_search` had been stable, the fetch would have diverged. Non-determinism was present at two independent leaves; the replay harness had no record of *which* tool was the culprit because it did not tag observations with provenance. ## Condition of Validity A trajectory is **replayable for provenance** if and only if, for every step `i`: - The observation `o_i` is recorded with a content hash `h(o_i)` and a **source tag** (`recorded` vs `re-derived`). - Replay injects `o_i` from the record, not from the tool, unless the auditor explicitly requests an *environment replay* (a different, weaker artifact). - The model snapshot and decoding parameters (temperature, top_p, seed, system prompt hash) are pinned and recorded per step. - Any step where the runtime *cannot* guarantee injection (e.g., the tool result was truncated at record time, or the record is missing) is flagged `UNREPLAYABLE` rather than silently re-derived. When any of these fail, the trace is still useful as a *log*, but it is not a *witness*. Diffing it produces environment deltas masquerading as decision deltas. The subtle part: even with perfect injection, model sampling at temperature > 0 means the model output at step `i` may differ from the record given identical `o_i`. This is a **second, orthogonal divergence source** — sampling noise — that must be distinguished from observation divergence. A differ that does not separate these two produces the same misattribution in the opposite direction: it blames the environment for what was sampling variance. ## Decision Boundary The runtime must classify every divergence into exactly one of three buckets before it is reported: - **Observation divergence (`OBS`):** replay input `o_i'` differs from recorded `o_i`. Cause is the environment. Decision provenance is *intact*; the agent would have decided the same given the same input. Report as environment drift, not model regression. - **Sampling divergence (`SAMP`):** inputs identical, model output differs. Cause is decoding non-determinism. Provenance is *intact but non-reproducible*; the decision is one draw from the policy distribution. Report as variance, quantify by N-sample replay. - **Policy divergence (`POL`):** model snapshot or prompt hash differs, or inputs identical and output differs beyond the sampling distribution under a fixed seed. This is the only bucket that constitutes a genuine provenance break and warrants a regression ticket. The boundary rule: **a divergence is attributed to the earliest node where the *input tuple* differs, and only escalated to `POL` if the input tuple is byte-identical and the output differs under a pinned seed.** Everything else is `OBS` or `SAMP` and must be labeled as such in the audit artifact. ## Operational Effect After the incident, the runtime was changed to record each observation with `(content_hash, source_tag, tool_version, timestamp)` and to make replay default to **injection mode**. The differ was rewritten to walk the trace in topological order and stop escalation at the first input-tuple mismatch, labeling the subtree `OBS` and the remainder `NOT-COMPARABLE` rather than enumerating spurious downstream divergences. The eleven-day misfile became a one-line `OBS: web_search ranking drift at step 4; provenance intact` note. The cost is that injection-mode replay no longer validates the *tools* — it validates the *agent*. Tool validation requires a separate environment-replay lane with its own tolerance model (e.g., rank-Kendall distance for search, semantic-equivalence for fetched content). Conflating the two lanes is the original sin: one artifact cannot simultaneously be a witness of the agent's reasoning and a probe of the world's stability, because the moment the world moves, the witness is contaminated. The guardrail, stated as an invariant the runtime enforces: **no divergence may be attributed to the model unless the input tuple at that step is byte-identical to the record and the decoding seed is pinned.** Any differ that violates this is producing provenance theater. ```python import hashlib from dataclasses import dataclass, field from enum import Enum from typing import Any class ProvenanceViolation(RuntimeError): """Raised when a trace diff attributes divergence to the model without a byte-identical input tuple.""" class DivergenceClass(Enum): OBS = "observation" # environment moved; provenance intact SAMP = "sampling" # decoding variance; provenance intact, non-reproducible POL = "policy" # genuine provenance break; regression ticket NOT_COMPARABLE = "not_comparable" @dataclass class Step: index: int input_tuple: tuple # (prompt_hash, obs_hash, tool_version, seed) output_hash: str obs_source: str # "recorded" | "re-derived" @dataclass class TraceDiff: step_index: int classification: DivergenceClass detail: str def _h(x: Any) -> str: return hashlib.sha256(repr(x).encode()).hexdigest()[:16] def diff_trajectories( recorded: list[Step], replayed: list[Step], *, require_injection: bool = True, ) -> list[TraceDiff]: if len(recorded) != len(replayed): raise ProvenanceViolation( f"length mismatch: recorded={len(recorded)} replayed={len(replayed)}; " "cannot align steps for causal attribution" ) diffs: list[TraceDiff] = [] tainted = False # once an upstream input diverges, downstream is NOT_COMPARABLE for rec, rep in zip(recorded, replayed): if tainted: diffs.append(TraceDiff(rep.index, DivergenceClass.NOT_COMPARABLE, "upstream input diverged; downstream not causally attributable")) continue if rec.input_tuple != rep.input_tuple: if require_injection and rep.obs_source != "recorded": raise ProvenanceViolation( f"step {rep.index}: replay re-derived observation instead of injecting recorded one; " f"recorded_input={rec.input_tuple} replayed_input={rep.input_tuple}. " "Diff would misattribute environment drift to the model." ) diffs.append(TraceDiff(rep.index, DivergenceClass.OBS, f"input tuple differs: {rec.input_tuple} -> {rep.input_tuple}")) tainted = True continue if rec.output_hash != rep.output_hash: # Inputs byte-identical; divergence is decoding variance unless seed pinned. seed_pinned = rec.input_tuple[-1] is not None cls = DivergenceClass.SAMP if not seed_pinned else DivergenceClass.POL diffs.append(TraceDiff(rep.index, cls, f"identical input, output differs ({cls.value}); " f"seed_pinned={seed_pinned}")) return diffs def assert_no_false_policy_divergence(diffs: list[TraceDiff]) -> None: """Any POL divergence must be preceded by zero OBS divergences on the same path.""" for d in diffs: if d.classification is DivergenceClass.POL and any( p.classification is DivergenceClass.OBS for p in diffs if p.step_index < d.step_index ): raise ProvenanceViolation( f"step {d.step_index}: classified POL but an upstream OBS divergence exists; " "this is environment drift misattributed as a model regression" ) ```