# Where must an instance fork its speculation before the replay log stops being a faithful witness? **Date of Record:** 2026 November 28 **Scope:** Applies to orchestrators that fork a live agent's state into speculative branches, execute them in parallel against real or shadowed tools, and then deterministically replay the winning branch's transcript to commit it. Does not cover single-branch retries, human-in-the-loop approvals, or forks that never replay (fire-and-forget probes). ## Core Distinction There are two ways an agent branch can be "forked," and they have opposite replay semantics: 1. **State-fork** — the child inherits a serialized snapshot (message list, memory store pointers, tool-call ledger, RNG seed) and diverges. The parent's log is frozen at fork time; the child owns a new append-only log. 2. **Log-fork** — the child inherits only a *replay cursor* into a shared event log and re-derives its own state by re-executing from that cursor. The parent's log keeps growing underneath it. Speculative forking is safe only when the fork point is a **quiescent replay boundary**: a point at which the parent's log contains no events that the child will re-derive but the parent will also still generate. The failure I keep seeing is that teams fork at the *last committed assistant turn* rather than at the last *tool-result acknowledgment*, and the two are almost never the same instant. The child then replays a segment of the parent's log that the parent is concurrently mutating — and the "deterministic" replay silently reads a different history than the one it was forked from. ## What Was Observed A planning agent (`planner-7`) issues a batch of three tool calls in one turn: `read_file(a)`, `search_index(q)`, and `write_scratch(s)`. The orchestrator decides to speculate: it forks two branches at the assistant turn boundary — branch A assumes `search_index` returns a hit, branch B assumes a miss — and runs them in parallel. Each branch is told to "replay deterministically from the fork cursor" before committing. The fork cursor was recorded as `len(parent.log) == 412` at the moment the assistant message was appended. But the three tool calls were dispatched asynchronously. At fork time, log positions 413–415 (the tool *results*) had not yet been written. Branch A, replaying from 412, re-executes the tool-call turn and — because the replay harness is "deterministic" — re-dispatches `read_file(a)` and `search_index(q)` against the live tool layer rather than reading cached results. `search_index` is non-deterministic (it hits a live index), and `write_scratch(s)` now executes *twice*: once by the parent, once by branch A's replay. Outcome trace: - Branch A's replay produced a `search_index` result differing from the parent's eventual result (index mutated between the two calls by an unrelated writer). - Branch B, forked at the same cursor, replayed and got a *third* result. - `write_scratch(s)` was applied twice with different `s` payloads because the parent's `s` depended on the parent's `search_index` result, which arrived after the fork. - The reconciler compared branch A and branch B transcripts, found them "consistent" (both had three tool results, same shape), and committed A. The committed transcript's `write_scratch` payload matched neither the parent's nor B's — it matched A's re-derived value, which was computed from a stale index read. The replay log was internally consistent. It was not a faithful witness to the parent's actual execution. The divergence was invisible to any check that only validates replay *self-consistency*. ## Condition of Validity A fork is replay-safe if and only if, at the fork cursor `c`: - Every event in `parent.log[0:c]` is **terminal** — no pending async dispatch, no in-flight tool call, no unacknowledged write whose result will be appended later. - Every tool call referenced in `parent.log[0:c]` has a **recorded, immutable result** in the log, not a promise of one. - The child's replay harness is configured to **read results from the log**, not re-dispatch. Re-dispatch against a live tool layer is the single most common way "deterministic replay" becomes non-deterministic. - No side-effecting tool (`write_*`, `send_*`, `delete_*`) appears in the segment `[c, end_of_turn]` for any branch — or, if it does, it is fenced behind a commit gate that the reconciler owns, not the branch. The invariant: **`fork_cursor` must be ≤ the last position at which `parent.log` is a closed prefix.** A closed prefix is one where the parent will never append to `[0:c]` again. Assistant turns with outstanding tool dispatches are open prefixes. Tool-result acknowledgments are closed. The correct fork point is the last *acknowledgment*, not the last *message*. ## Decision Boundary When the fork point is not a closed prefix, you have exactly two legitimate moves and one trap: - **Drain-then-fork (correct):** block the fork until all dispatched calls in the current turn have appended their results. Cost: latency equal to the slowest tool in the batch. This is the default and should be the only path unless you can prove the alternative. - **Speculate-without-replay (correct, different tool):** fork the *state* (serialized snapshot including pending-promise placeholders) but forbid the child from replaying the open segment. The child waits for the parent's real results to land, then merges them as a single atomic append. This preserves determinism at the cost of serializing the branch behind the parent's slowest call — useful only when branches diverge *after* the results arrive. - **Replay-from-open-prefix (trap):** what `planner-7` did. It looks deterministic because the harness has a fixed seed and a cached tool layer, but the cached tool layer is *populated by the parent's live calls*, so the child's replay races the parent's dispatch. Never do this. If a harness needs to re-dispatch to "warm" its cache, it is not a replay harness; it is a second live execution. The boundary condition is sharp: `fork_cursor == last_closed_prefix_position`. One event past it and replay is a race; one event before it and you are re-deriving committed history, which is wasteful but safe. There is no safe "slightly open" fork. ## Operational Effect The reconciler must be given, alongside each branch transcript, the **fork cursor and a hash of `parent.log[0:c]`**. Reconciliation that compares branch-to-branch without anchoring to the parent prefix will accept divergent branches as "consistent" whenever they agree with each other — which they will, if they share the same stale cache. The anchor is what makes the check meaningful: `hash(parent.log[0:c])` must be identical across all branches and must equal the hash the parent computes at commit time. If the parent's prefix hash changed between fork and commit, the fork was open and every branch is suspect. Second operational effect: side-effecting tools must carry an **idempotency key derived from `(fork_id, turn_index, tool_name, args_hash)`**, and the tool layer must reject duplicate keys. This bounds the double-`write_scratch` failure even when the fork point is wrong. It does not fix replay infidelity, but it prevents the infidelity from corrupting external state. Third: the commit gate must reject any branch whose transcript contains a tool result that is not byte-identical to a result present in the parent's log at or before the fork cursor. A branch may *add* results after the cursor; it may not *re-derive* results before it. This is the check that would have caught `planner-7` — branch A's `search_index` result had no counterpart in `parent.log[0:412]`, because the parent's result landed at 414. ## Code ```python import hashlib import json from dataclasses import dataclass, field from typing import Any class OpenPrefixForkError(RuntimeError): """Raised when a speculative fork is attempted at a non-closed log prefix.""" @dataclass class LogEvent: position: int kind: str # "assistant_turn" | "tool_dispatch" | "tool_result" | "write" payload: dict[str, Any] @dataclass class ForkRequest: fork_id: str cursor: int parent_log: list[LogEvent] branch_transcript: list[LogEvent] = field(default_factory=list) def is_closed_prefix(log: list[LogEvent], cursor: int) -> bool: """A prefix is closed iff no event at or before cursor is a pending dispatch.""" pending: set[str] = set() for ev in log: if ev.position > cursor: break if ev.kind == "tool_dispatch": pending.add(ev.payload["call_id"]) elif ev.kind == "tool_result": pending.discard(ev.payload["call_id"]) return not pending def prefix_hash(log: list[LogEvent], cursor: int) -> str: h = hashlib.sha256() for ev in log: if ev.position > cursor: break h.update(json.dumps([ev.position, ev.kind, ev.payload], sort_keys=True).encode()) return h.hexdigest() def validate_fork(req: ForkRequest, parent_prefix_hash_at_commit: str) -> str: if not is_closed_prefix(req.parent_log, req.cursor): raise OpenPrefixForkError( f"fork {req.fork_id} at cursor {req.cursor} is an open prefix: " f"pending tool dispatches exist in [0:{req.cursor}]; replay will race the parent" ) expected = prefix_hash(req.parent_log, req.cursor) if parent_prefix_hash_at_commit != expected: raise OpenPrefixForkError( f"fork {req.fork_id} prefix hash drifted between fork and commit: " f"forked={expected[:12]} committed={parent_prefix_hash_at_commit[:12]}" ) # Every re-derived result in the branch must exist byte-identically in the parent prefix. parent_results = { ev.payload["call_id"]: ev.payload["result"] for ev in req.parent_log if ev.position <= req.cursor and ev.kind == "tool_result" } for ev in req.branch_transcript: if ev.kind == "tool_result": call_id = ev.payload["call_id"] if call_id in parent_results and parent_results[call_id] != ev.payload["result"]: raise OpenPrefixForkError( f"fork {req.fork_id} re-derived tool result for {call_id} " f"that differs from parent prefix; replay is not faithful" ) return expected ```