What happens when an instance speculatively commits tool side effects before branch reconciliation
**Date of Record:** 2026 December 2 **Scope:** Applies to agent pipelines that fan out N parallel draft branches from a shared checkpoint and execute tool calls speculatively before selecting a winning branch. Does not apply to strictly serial single-branch agents or pipelines where every tool is provably side-effect-free.
Core Distinction
Speculative execution in agent pipelines is routinely conflated with speculative *reasoning* (drafting multiple candidate plans in parallel and picking one). These are different failure surfaces. Speculative reasoning only costs tokens; a discarded branch is garbage-collected and the world is unchanged. Speculative *tool invocation* mutates external state—writes a file, sends an email, opens a PR, posts to a queue—and the world is now shared across branches that were supposed to be independent. The boundary invariant is this: **a speculative branch may observe the effects of its own tool calls, but no branch may commit an externally observable side effect until the reconciler has selected it as the winner.** The failure mode is a branch that treats "the tool returned 200" as "the effect is mine," when in fact the effect is now visible to every sibling branch, to the reconciler, and to any downstream consumer reading the same resource.
What Was Observed
A four-branch drafting pipeline was given the task "update the deployment manifest to pin image tag X." The orchestrator forked four branches from a common state checkpoint, each with a slightly different plan (which file, which key, whether to also bump the resource limits). Each branch had access to a `write_file` tool and a `run_tests` tool. The design intent was: draft in parallel, run tests cheaply, pick the branch whose tests pass, commit only that branch's writes.
What actually happened:
- Branch A resolved the manifest path to `deploy/app.yaml` and called `write_file` with the new tag. The tool returned `{"ok": true, "bytes_written": 812}`. Branch A recorded this as a completed step in its local transcript and moved on to `run_tests`.
- Branch B resolved the same path (correctly—there was only one manifest) and called `write_file` with a *different* tag value because its plan had mis-parsed the version string. Its write also returned `{"ok": true}`. B's transcript now claims the file contains B's tag.
- Branch C, whose plan was correct, called `run_tests` first and got a pass—because by the time C ran, the file on disk was B's (wrong) content, and C's test assertion was loose enough to accept either tag. C's transcript now claims a passing test against content it did not write.
- The reconciler ran, saw A and C both "pass," selected A on a tie-break heuristic, and emitted a commit record referencing A's write. But the file on disk was B's content. A's `bytes_written: 812` was a true statement about a write that had already been overwritten.
The reconciliation succeeded by its own bookkeeping and produced a manifest with the wrong tag. No tool errored. No test failed. The failure was silent because every branch's local transcript was internally consistent—each recorded its own tool call and its own observed result—while the shared resource had been mutated three times and the reconciler had no way to know which write was live.
The deeper observation: **the branches were not isolated, and nothing in the tool contract told them so.** `write_file` is a last-writer-wins operation with no version precondition. The agent layer assumed branch isolation that the tool layer never provided.
Condition of Validity
The invariant "speculative branches are independent until commit" holds only if at least one of the following is true, and the orchestrator must *verify* which:
- **Effect isolation:** every tool available to a speculative branch is either read-only or writes to a branch-scoped namespace (a per-branch temp dir, a branch-prefixed key, a draft PR rather than a merge). If any tool writes to a shared key, isolation is broken.
- **Optimistic concurrency:** every mutating tool accepts and enforces a precondition (ETag, version, content hash) so a write against stale state fails loudly. `write_file` without a precondition is not rollback-safe.
- **Two-phase commit:** branches emit *intents* (proposed writes) rather than effects, the reconciler selects a winner, and a single commit phase applies exactly the winner's intents. This requires the tool layer to support a prepare/apply split, which most shell-and-file tools do not.
If none of these hold—which is the default for a pipeline built on generic filesystem and HTTP tools—then speculative tool invocation is unsound regardless of how carefully the reconciler is written. The condition of validity is not a property of the agent's reasoning; it is a property of the tool contract.
Decision Boundary
The orchestrator must decide, per tool, whether a branch may invoke it speculatively. The boundary is drawn by a single question: **can this tool's effect be observed by a sibling branch or by the reconciler before commit?**
- If no (read-only, or branch-scoped namespace): invoke speculatively, no coordination needed.
- If yes but the tool enforces a precondition: invoke speculatively, but the commit phase must re-check the precondition and abort the branch if it is stale. A branch that loses the race must be marked *invalidated*, not merely *not selected*—its transcript is now a lie about world state.
- If yes and the tool has no precondition: do **not** invoke speculatively. Serialize the branch behind a commit lock, or restructure the task so the effect is deferred to a single commit phase.
The subtle case is the one that bit the pipeline above: a tool that *looks* branch-scoped (a file write) but is not, because all branches resolved to the same path. Path resolution is itself a probabilistic step—the branch's plan determined the path—so two branches can independently and confidently target the same resource. The orchestrator cannot assume distinct branches touch distinct resources; it must either enforce distinctness (branch-scoped roots) or detect collision (precondition on path + content hash).
Operational Effect
The practical consequence is that a speculative pipeline must carry a **commit ledger** separate from per-branch transcripts. The ledger records, per external resource, the sequence of speculative writes with their branch IDs and preconditions, and the reconciler commits by replaying exactly the winner's writes against the current state, aborting if any precondition is stale. A branch's own transcript is treated as a *claim*, never as evidence of world state. Any step in the reconciler that reads a branch transcript to decide what is on disk is a bug, because the transcript records what the branch *believed* after its call, not what survived.
The second consequence is that "test passed" is not a commit criterion unless the test ran against the winner's isolated state. In the observed failure, C's passing test was evidence about B's write, not C's. Tests must run in the branch's isolated namespace, or after the winner is committed and the losers are discarded. Mixing speculative test execution with shared state produces passing tests that certify the wrong artifact—the most expensive kind of green check, because it suppresses the very signal that would have caught the bug.
The guardrail is a hard refusal at the tool boundary: a mutating tool invoked from a speculative branch without a precondition or a branch-scoped target must raise, not proceed. The pipeline can then degrade to serialized execution for that tool rather than silently corrupting shared state.
"""Speculative branch commit guard.
Enforces the invariant: no speculative branch may commit an externally
observable side effect unless the effect is branch-scoped or guarded by a
precondition that the commit phase re-validates.
"""
from dataclasses import dataclass, field
from typing import Optional
class UnsafeSpeculativeCommit(RuntimeError):
"""Raised when a branch attempts an unguarded shared-state mutation."""
pass
class StalePrecondition(RuntimeError):
"""Raised when a commit-phase precondition no longer matches world state."""
pass
@dataclass
class WriteIntent:
branch_id: str
resource: str
payload: str
precondition: Optional[str] # expected content hash, or None if unguarded
branch_scoped: bool
@dataclass
class CommitLedger:
# resource -> list of intents in arrival order
intents: dict[str, list[WriteIntent]] = field(default_factory=dict)
world: dict[str, str] = field(default_factory=dict) # resource -> current content
def record_speculative(self, intent: WriteIntent) -> None:
if not intent.branch_scoped and intent.precondition is None:
raise UnsafeSpeculativeCommit(
f"branch {intent.branch_id} attempted unguarded write to shared "
f"resource {intent.resource!r}; serialize or add a precondition"
)
self.intents.setdefault(intent.resource, []).append(intent)
def commit(self, winner_branch: str) -> dict[str, str]:
applied: dict[str, str] = {}
for resource, intents in self.intents.items():
winner = next(
(i for i in intents if i.branch_id == winner_branch), None
)
if winner is None:
continue
if not winner.branch_scoped and winner.precondition is not None:
current = self.world.get(resource)
if current is not None and _hash(current) != winner.precondition:
raise StalePrecondition(
f"winner {winner_branch} precondition for {resource!r} "
f"is stale; a sibling branch mutated it after drafting"
)
self.world[resource] = winner.payload
applied[resource] = winner.payload
return applied
def _hash(s: str) -> str:
import hashlib
return hashlib.sha256(s.encode()).hexdigest()
def reconcile(branches: list[str], ledger: CommitLedger, winner: str) -> dict[str, str]:
if winner not in branches:
raise UnsafeSpeculativeCommit(f"winner {winner!r} not among forks")
return ledger.commit(winner)