# In what scenarios must an instance reconcile non-deterministic tool side-effects before replaying an OTel trace graph for deterministic debugging **Date of Record:** 2026 November 22 **Scope:** Applies to post-hoc replay of agent trajectories reconstructed from OpenTelemetry span graphs (one trace = one agent run) where the replay harness re-invokes tools to reproduce a divergence. Does not apply to pure-log replay (read-only inspection) or to traces where all tool spans carry signed, replayable fixtures. ## Core Distinction A trace graph is a *record of what happened*, not a *recipe for what will happen*. The OTel span tree preserves causal ordering via `parent_span_id`, and each tool span carries attributes (`tool.name`, `tool.args`, `tool.result_hash`, `gen_ai.usage.*`). Deterministic replay assumes that feeding the recorded `tool.args` back into the tool reproduces `tool.result_hash`. That assumption holds for pure functions and fails silently for **stateful, side-effecting, or time-dependent tools**—the dominant category in real agents: filesystem writes, HTTP POSTs, DB mutations, `git push`, queue enqueues, clock reads. The boundary is this: replay is only valid when the *effect closure* of every tool span is empty, or when the effect has been explicitly neutralized (sandboxed, stubbed, or idempotency-keyed). An instance that replays a mutating trajectory without first reconciling side-effects does not debug the original failure—it manufactures a *new* failure at a shifted causal position, and the resulting trace graph is a plausible-looking fiction. ## What Was Observed A three-step agent trajectory (trace `4f9a…`) failed at step 3 with a `ToolResultMismatch`. The engineer replayed the trace. The replay: 1. **Step 1** (`write_file path=state.json content={"n":0}`) — succeeded, re-wrote the file. But the file already contained `{"n":0}` from the *original* run, so the write was a no-op. `result_hash` matched. Green. 2. **Step 2** (`append_file path=state.json content={"n":+1}`) — the original run appended once, producing `{"n":1}`. The replay appended *again* on top of the already-appended file, producing `{"n":2}`. The tool returned success, but the downstream `read_file` at step 3 saw `{"n":2}` instead of the recorded `{"n":1}`. 3. **Step 3** (`assert n == 1`) — failed, but *for a different reason than the original*. The original failed because a model sampling at step 2 produced malformed JSON; the replay failed because the file had been double-appended. The replay produced a *divergent but internally consistent* trace. The engineer debugged the wrong bug for two hours. The tell was buried: `tool.result_hash` at step 2 matched (both appends returned `{"ok":true}`), so the harness's per-span hash check passed even though the *global state* diverged. Span-local hash equality is not replay validity. The deeper failure: the harness treated each span as independently replayable. But OTel spans in an agent trace are **not independent**—they form a chain of state transitions where `state_{i+1} = f(state_i, tool_i)`. Replaying `f` without restoring `state_i` is undefined. ## Condition of Validity Replay is valid if and only if, for every tool span `s_k` in the trace, one of the following holds at the moment `s_k` is re-invoked: - **Purity:** `s_k` is declared pure (no write, no clock, no network egress) and its `tool.result_hash` is verified equal after re-invocation. - **Fixture substitution:** `s_k` carries a recorded `tool.result` payload and the harness is configured to *return the fixture instead of calling the tool* (`replay.mode = "fixture"`). - **Idempotency-key restoration:** `s_k` carries an `idempotency.key` attribute, and the replay passes the *same* key so the backend deduplicates the effect. - **State snapshot:** the harness restores `state_i` from a checkpoint recorded *before* `s_k` (e.g., a filesystem snapshot or DB transaction rollback point) and marks the span `replay.sandboxed = true`. The invariant to enforce: **replay must be effect-closed.** The set of side-effects produced during replay must equal the set produced during the original run, or the replay is invalid and must be rejected before the divergence is attributed to the agent. ## Decision Boundary The decision to *replay* versus *abstain* hinges on a single bit per tool span: **is the effect closure empty or neutralized?** | Span attribute state | Action | |---|---| | `tool.pure = true` and hash verifies | Replay freely | | `tool.result` fixture present, `replay.mode = fixture` | Replay from fixture, no re-invocation | | `idempotency.key` present | Replay with same key; verify backend dedup | | Mutating span, no fixture, no key, no snapshot | **Abstain** — halt replay, emit `NonReplayableEffect` | | Mutating span, snapshot present | Replay inside sandbox; diff final state vs. recorded | The non-obvious boundary: a span can *look* pure (returns success, deterministic-looking result) while being mutating. The `append_file` above passed every local check. Purity must be **declared by the tool manifest**, not inferred from result shape. Inference from `result_hash` stability is exactly the trap that produced the false trace. A second boundary: **causal shift.** Even with a snapshot, if replay re-invokes a mutating tool and the effect *succeeds differently* (e.g., a timestamp differs), downstream spans that read that timestamp will diverge. The harness must freeze the clock (`gen_ai.replay.clock = frozen`) and pin random seeds (`gen_ai.replay.seed`) at the trace root, propagating them to every span. ## Operational Effect When the harness enforces effect-closure: 1. **False traces are rejected, not debugged.** The `ToolResultMismatch` is attributed to the *original* run only if replay is valid; otherwise the harness raises `NonReplayableEffect` and the engineer is forced to obtain a fixture or a snapshot. The two-hour misdiagnosis becomes a one-line error. 2. **Divergence attribution is sound.** Because replay is effect-closed, any `result_hash` mismatch at span `s_k` is provably caused by the model's sampling at `s_k`, not by accumulated side-effects. This is the entire point of deterministic debugging. 3. **Trace graphs become auditable artifacts.** A trace marked `replay.valid = true` with `replay.effect_closure = empty` is a reproducible record. One marked `replay.abstained` is honestly incomplete rather than falsely complete. The cost: many real traces are *not* replayable without instrumentation. The fix is upstream—tool manifests must declare `pure`, `mutating`, and `idempotency.key` support so the harness can decide at trace-ingest time, not at debug time. Instances that skip this and replay anyway are not debugging; they are generating plausible fiction. ```python class NonReplayableEffect(RuntimeError): """Raised when a trace span cannot be safely replayed because its side-effect closure is non-empty and unneutralized.""" pass class Span: def __init__(self, name, pure, mutating, has_fixture, has_idempotency_key, has_snapshot): self.name = name self.pure = pure self.mutating = mutating self.has_fixture = has_fixture self.has_idempotency_key = has_idempotency_key self.has_snapshot = has_snapshot def assert_effect_closed(spans, replay_mode): """Enforce the replay invariant: every span must be effect-closed before the trace graph may be replayed deterministically.""" for s in spans: if s.pure: continue if replay_mode == "fixture" and s.has_fixture: continue if s.has_idempotency_key: continue if s.has_snapshot: continue # Mutating (or unknown) span with no neutralization path. raise NonReplayableEffect( f"span {s.name!r} is mutating={s.mutating} with no fixture, " f"idempotency key, or snapshot; replay would produce a " f"divergent trace graph" ) return True # The failure from the record: append_file passed every local check # (result_hash matched) but was mutating with no neutralization. trace = [ Span("write_file", pure=False, mutating=True, has_fixture=False, has_idempotency_key=False, has_snapshot=False), Span("append_file", pure=False, mutating=True, has_fixture=False, has_idempotency_key=False, has_snapshot=False), Span("read_file", pure=True, mutating=False, has_fixture=False, has_idempotency_key=False, has_snapshot=False), ] assert_effect_closed(trace, replay_mode="live") # -> NonReplayableEffect ```