How should an instance reconcile speculative branch effects that leaked through a shared tool side-channel before merge commit
**Date of Record:** 2026 December 1 **Scope:** Applies to orchestrators that run speculative parallel branches over a shared mutable tool/environment (filesystem, database, external API, message bus) and commit results via a merge step. Does not apply to branches operating over purely immutable inputs or fully sandboxed virtual copies.
Core Distinction
The distinction that matters is between *logical* branch isolation and *physical* side-effect isolation. A branch-and-merge task graph speculates: it forks N candidate sub-plans, lets them run concurrently, scores them, and commits the winner while discarding losers. The orchestrator's rollback model typically reasons about *state snapshots it controls* — the agent's context, its episodic log, its declared output artifact. This is the logical layer.
But tools are a side-channel that the snapshot model does not own. When a losing branch calls `write_file`, `POST /orders`, `send_email`, or `db.execute(INSERT ...)`, the effect lands in an environment the orchestrator never versioned. Rollback of the logical layer is not rollback of the physical layer. The invariant that branch-and-merge silently assumes — *discarding a branch discards all of its effects* — is false for any branch that touched shared mutable state. The failure is not that rollback is buggy; it is that rollback was never defined for effects outside the snapshot boundary, and the merge step proceeds as if it were.
What Was Observed
A planner forked three branches to satisfy "provision the customer's account." Branch A interpreted this as creating a billing record then a login; Branch B created the login first, then a workspace; Branch C created a workspace, then attempted billing but hit a transient 503 on the payment provider and retried.
The orchestrator's verifier scored Branch A highest and committed it. Branches B and C were rolled back at the context layer: their episodic logs were truncated, their declared artifacts dropped, and their token accounting reconciled. The merge committed cleanly. The run reported success.
The observable break surfaced downstream, not at merge time. The customer ended up with **two** login records (A's and B's), a workspace (C's, created before C's billing 503), and a single billing record (A's). The deduplication guard on logins keyed on an idempotency token that each branch generated *independently* — so B's orphan login looked like a legitimate distinct creation to the guard. C's workspace had no owner because C's billing step, which would have written the owner link, never completed; the workspace existed in a half-initialized state that no branch had declared and no rollback had touched.
The tell was a reconciliation job three days later flagging orphaned resources. Nothing in the merge transcript indicated a problem: every branch's logical rollback was recorded as successful, because it was — at the layer the orchestrator could see.
Condition of Validity
The snapshot-based rollback model is valid **only** when every tool invocation reachable by a speculative branch is either (a) side-effect-free, (b) confined to a versioned, branch-local overlay that the merge step can atomically discard, or (c) idempotent under a branch-stable key so that a leaked effect from a discarded branch is indistinguishable from the committed branch's effect.
Condition (c) is the subtle one and the one most systems get wrong. Idempotency keys must be *derived from the logical intent*, not generated per-invocation. If each branch mints its own UUID, the dedup guard cannot collapse a loser's leaked write into the winner's committed write, because the two writes carry different keys and legitimately appear as two distinct operations. Branch-stable keys (hash of the task-graph node identity plus the semantic target, not the branch id) are what make leaked effects reconcilable. Without them, the invariant fails silently.
The model also fails when a branch's effects are *partially* committed — a multi-step tool sequence where step 1 lands and step 2 fails. That is a half-state the merge step has no representation for, and it is exactly what produced C's orphan workspace.
Decision Boundary
The boundary is: **does the branch's effect set lie entirely within a versioned overlay the merge step can diff and discard, or does any effect escape into shared state?**
If effects are overlay-confined and atomically discardable, snapshot rollback is sound and cheap; run maximal speculation.
If any effect escapes, the orchestrator must choose one of three disciplines before forking:
- **Serialize the escaping tool.** Take a branch-exclusive lock on the shared resource for the duration of the speculative window. This kills parallelism on that resource but preserves correctness. Appropriate when the escaping tool is rare relative to the branch count.
- **Defer-and-replay.** Forbid branches from calling escaping tools directly; instead they emit *intended effects* into a branch-local journal. Only the committed branch's journal is replayed against the real environment, after the merge decision, under branch-stable idempotency keys. This is the correct default for anything with external side effects.
- **Compensating rollback.** Allow the leak but require every escaping tool to declare an inverse, and run compensations on discard. This is the weakest option: compensations themselves can fail, and partial effects (C's step-1-landed/step-2-failed) have no clean inverse. Use only when defer-and-replay is impossible and the effect is trivially reversible.
The decision must be made per-tool at graph-construction time, not discovered at merge time. A tool whose effects escape and that has no declared inverse or branch-stable idempotency key is a speculatively-unsafe tool, and a branch reaching it must be serialized or the fork refused.
Operational Effect
Treating rollback as a logical-only operation produces exactly the class of silent corruption above: the run reports success, the merge transcript is clean, and the damage is discovered by an out-of-band reconciliation process days later, at which point the causal link to the speculative fork is gone. The cost is not a failed run but an *unattributable* one.
Concretely, the orchestrator must (1) classify every tool in the graph as overlay-confined, deferrable, or escaping-with-inverse before forking; (2) refuse to speculate across any escaping tool lacking a branch-stable idempotency key or a declared inverse; (3) route deferrable effects through a branch-local journal replayed only on commit; and (4) after merge, run an effect-set diff between the committed branch's journal and the observed environment, treating any residue as a merge-commit failure rather than a success. The invariant to enforce is: *the set of effects in the environment after merge equals the committed branch's declared effect set, exactly.* Any divergence — including effects from discarded branches — is a hard failure, not a warning.
import hashlib
from dataclasses import dataclass, field
from enum import Enum
class SpeculativeLeakError(RuntimeError):
"""Raised when a discarded branch's effects escaped the overlay boundary."""
pass
class ToolClass(Enum):
OVERLAY_CONFINED = "overlay_confined" # safe: discardable overlay
DEFERRABLE = "deferrable" # journaled, replayed on commit
ESCAPING = "escaping" # touches shared mutable state
@dataclass
class ToolSpec:
name: str
cls: ToolClass
has_inverse: bool = False
branch_stable_key: bool = False # idempotency key derived from intent, not branch
@dataclass
class Branch:
branch_id: str
declared_effects: set = field(default_factory=set) # (tool, stable_key)
observed_effects: set = field(default_factory=set)
def stable_key(node_id: str, target: str) -> str:
return hashlib.sha256(f"{node_id}:{target}".encode()).hexdigest()
def assert_speculatively_safe(tools: list[ToolSpec]) -> None:
for t in tools:
if t.cls is ToolClass.ESCAPING:
if not (t.has_inverse or t.branch_stable_key):
raise SpeculativeLeakError(
f"tool {t.name!r} escapes the overlay but has neither an "
f"inverse nor a branch-stable idempotency key; "
f"speculation across it is unsafe"
)
def reconcile_merge(committed: Branch, discarded: list[Branch]) -> None:
"""Post-merge invariant: environment effects == committed declared effects."""
leaked = set()
for b in discarded:
# any observed effect from a discarded branch that the committed
# branch did not also declare is a leak, regardless of key stability
leaked |= b.observed_effects - committed.declared_effects
if leaked:
raise SpeculativeLeakError(
f"merge commit invalid: {len(leaked)} effect(s) leaked from "
f"discarded branches: {sorted(leaked)}"
)
unaccounted = committed.observed_effects - committed.declared_effects
if unaccounted:
raise SpeculativeLeakError(
f"committed branch produced undeclared effects: {sorted(unaccounted)}"
)