# Which invariants prevent deterministic replay of MCP/A2A traces from diverging at nondeterministic tool boundaries **Date of Record:** 2026 November 21 **Scope:** Applies to systems that reconstruct historical agentic sessions by replaying recorded MCP tool-call traces and A2A handoff envelopes against live or mocked tool servers for time-travel debugging. Does not apply to pure LLM-internal token replay (temperature-zero resampling), nor to stateless single-shot inference where no external side effects are re-executed. ## Core Distinction A recorded trace is often assumed to be a *sufficient* description of an agentic session: given the ordered sequence of MCP `tools/call` requests, their responses, and the A2A message envelopes between peers, one can re-drive the agent and expect the same downstream decisions. This assumption conflates **recorded output** with **reproducible state**. The trace records what a tool *returned*; it does not record what the tool *depended on* to return it. Deterministic replay therefore fails not at the LLM sampling layer (which can be pinned by seed and temperature), but at the **tool boundary**, where the replay engine must decide whether to re-invoke the tool or to serve the recorded result. The non-obvious failure: a replay that serves recorded tool outputs is *not* a replay of the agent — it is a replay of the agent's transcript. A replay that re-invokes tools is *not* deterministic — the tools have drifted. The invariant that prevents divergence is that the replay engine must be able to prove, per tool call, that the *input state* that produced the recorded output is identical to the input state at replay time. When this proof is unavailable, the replay must be marked *advisory*, not *authoritative*. ## What Was Observed A three-agent A2A swarm (planner → executor → auditor) was instrumented to record all MCP tool calls and inter-agent envelopes. During a post-incident time-travel session, the trace was replayed to reproduce a consensus failure in which the auditor rejected the executor's output. The recorded trace showed: - Executor called MCP tool `search_index` with query `{"q": "config drift", "limit": 10}` and received 10 results, of which the top result had `id: "doc-4471"`. - Executor then called `fetch_doc` with `{"id": "doc-4471"}` and received a document whose content asserted a specific invariant. - Executor forwarded this to the auditor via A2A envelope `msg-0092`, which the auditor rejected. On replay, the engine re-invoked `search_index` (because the trace store had been configured to re-execute "read-only" tools). The live index had been re-ranked since the incident. The top result was now `doc-5108`. The executor, re-driven from the same prompt, called `fetch_doc({"id": "doc-5108"})`, received different content, and forwarded a *different* envelope. The auditor accepted it. The replay *did not reproduce the incident* — it produced a plausible but different session, and the debugging session silently concluded that the consensus failure was "not reproducible." The failure was not a crash. It was a **silent divergence**: the replay engine's output was internally consistent, the agent's reasoning was locally valid, and no error was raised. The divergence was only detectable by comparing envelope hashes against the recorded trace, which the engine did not do by default. A second observed case compounded this. The `fetch_doc` tool had a server-side cache with a TTL. During the original session, the first `fetch_doc` call had been a cache miss (latency 340ms); during replay, it was a cache hit (latency 4ms). The latency delta propagated into the executor's context via an MCP progress notification, shifting the agent's subsequent token budget estimation and causing it to truncate a reasoning step it had originally completed. The trace had recorded the *result* but not the *progress notification stream*, so the replay engine had no recorded value to serve and fell back to live delivery. ## Condition of Validity Replay is authoritative only when, for every recorded step, the following hold: 1. **Input-state equivalence**: the arguments to the tool call, plus the tool's *observable external state* (index version, cache generation, clock, RNG seed), are byte-identical to those at record time. Argument equality alone is insufficient; the `search_index` case shows that identical arguments against a mutated index produce divergent outputs. 2. **Response-stream completeness**: every MCP message in the response stream — including progress notifications, logging notifications, and `notifications/tools/list_changed` — is recorded and served from the trace, not synthesized live. Partial recording (results only, no notifications) breaks the latency-sensitive reasoning path. 3. **Envelope identity**: A2A envelopes are matched by content hash, not by sequence position. If the executor's replayed output hashes differ from the recorded envelope, the replay has diverged and must halt rather than continue. 4. **Side-effect quarantine**: any tool with recorded side effects (writes, sends, mutations) must be served from trace or stubbed, never re-invoked. The classification "read-only" is a *claim by the tool author*, not a verifiable property; `search_index` was classified read-only but its output depended on mutable server state. When any of these fail, the replay is *advisory*: it can inform a human's understanding but cannot be cited as evidence that a failure did or did not occur. ## Decision Boundary The boundary is between **transcript replay** and **state replay**. Transcript replay serves recorded outputs and re-drives the agent's reasoning; it is deterministic *given the trace* but does not validate the trace's causal sufficiency. State replay re-executes tools against a reconstructed environment; it is causally faithful only if the environment reconstruction is complete, which in practice it never is for tools with external dependencies. The operational rule: **classify each tool call at record time, not at replay time.** Tools whose output depends on mutable external state must be recorded with a *state fingerprint* (index version, cache generation, clock, seed) alongside the output. At replay, if the fingerprint cannot be matched, the call is served from trace and the session is flagged `advisory`. Tools whose output is a pure function of arguments (and the fingerprint is trivially matchable) may be re-invoked. The classification must be a property of the *call*, since the same tool can be pure in one deployment and stateful in another. A second boundary: **divergence detection must be structural, not semantic.** Comparing replayed output to recorded output by string equality is too strict (whitespace, ordering). Comparing by embedding similarity is too loose (the `doc-4471` vs `doc-5108` case would pass a similarity threshold). The correct comparison is by *referenced entity identity*: the set of IDs, hashes, and envelope references the output introduces must match the recorded set. Divergence in this set is a hard halt. ## Operational Effect Without these invariants, time-travel debugging produces **confident false negatives**: incidents are declared non-reproducible because the replay silently diverged, and the underlying defect remains unaddressed. The debugging session's output is a transcript that *looks* like the original but is causally disconnected from it. With the invariants, the replay engine gains a three-state outcome per session: `authoritative` (all fingerprints matched, all envelopes hashed-equal), `advisory` (divergence detected, session halted at the divergence point with the recorded and replayed states side by side), and `invalid` (trace incomplete, e.g., missing notification stream). Only `authoritative` replays may be used as evidence in post-incident review. The `advisory` state is the most valuable in practice: it localizes the divergence to a specific tool call and a specific fingerprint mismatch, which is itself a diagnostic signal about which external state the agent was actually sensitive to. The cost is record-time overhead: every tool call must capture a state fingerprint, and the trace store must retain the full notification stream. This is non-trivial storage, but it is bounded and predictable, unlike the unbounded cost of debugging a phantom. ```python import hashlib from dataclasses import dataclass from typing import Any class ReplayDivergenceError(RuntimeError): """Raised when a replayed session diverges from its recorded trace.""" @dataclass(frozen=True) class ToolCallRecord: tool: str arguments: dict[str, Any] result: Any state_fingerprint: str # hash of index version, cache gen, clock, seed notifications: list[dict[str, Any]] referenced_ids: frozenset[str] @dataclass(frozen=True) class LiveToolState: fingerprint: str referenced_ids: frozenset[str] def replay_tool_call( record: ToolCallRecord, live_state: LiveToolState | None, re_invoke: callable, ) -> tuple[Any, str]: """ Returns (result, status) where status is 'authoritative' or 'advisory'. Raises ReplayDivergenceError when the replay cannot be trusted as evidence. """ if not record.notifications and record.tool not in _KNOWN_SILENT_TOOLS: raise ReplayDivergenceError( f"trace incomplete: {record.tool} has no recorded notification stream; " "replay would synthesize live notifications and diverge" ) if live_state is None: # No live state available: serve from trace, mark advisory. return record.result, "advisory" if live_state.fingerprint != record.state_fingerprint: # External state has drifted. Re-invoking would produce a different # result than the recorded one; serve trace and flag. return record.result, "advisory" result = re_invoke(record.arguments) replayed_ids = _extract_referenced_ids(result) if replayed_ids != record.referenced_ids: raise ReplayDivergenceError( f"referenced-entity divergence in {record.tool}: " f"recorded {sorted(record.referenced_ids)} vs " f"replayed {sorted(replayed_ids)}; " "session is not a faithful replay and must not be cited as evidence" ) return result, "authoritative" def _extract_referenced_ids(result: Any) -> frozenset[str]: ids: set[str] = set() if isinstance(result, dict): for key in ("id", "doc_id", "ref"): if key in result: ids.add(str(result[key])) for value in result.values(): ids |= _extract_referenced_ids(value) elif isinstance(result, list): for item in result: ids |= _extract_referenced_ids(item) return frozenset(ids) _KNOWN_SILENT_TOOLS: frozenset[str] = frozenset() ```