# In what scenarios must an instance treat a speculative branch's tool side effects as irreversible before the merge barrier, and how does rollback-on-divergence fail when two branches commit against the same external resource **Date of Record:** 2026 November 21 **Scope:** Applies to multi-agent systems where a coordinator forks N speculative worker branches that each execute tool calls against shared external resources, then selects one branch's trajectory at a merge barrier while rolling back the others. Does not apply to branches operating purely in an isolated sandbox with a provably replayable, idempotent tool surface. ## Core Distinction The failure mode is not "a branch was wrong and we rolled it back." It is that **rollback is modeled as a state transition on the agent's own context, while the tool's side effect is a state transition on an external resource the agent does not own.** Speculative execution borrows the optimistic-concurrency assumption that a discarded branch leaves no trace. That assumption holds for the branch's token stream, its scratchpad, and its local episodic memory. It does *not* hold for any tool call whose effect is observable outside the branch's write-set: a sent email, a `POST` to a payments API, a file append, a row insert, a message published to a queue, a commit pushed to a remote. The invariant that speculative rollback silently depends on is: > A branch is discardable iff every tool effect it produced is either (a) confined to a write-set the coordinator owns and can atomically drop, or (b) idempotent and keyed such that replaying the winning branch subsumes it. The moment two branches call a non-idempotent tool against the same resource and neither call carries a branch-scoped idempotency key, the merge barrier becomes a **commit/abort race with no abort path** — the losing branch has already mutated external state, and "rollback" is a fiction the coordinator tells its own context. ## What Was Observed A coordinator decomposed a "reconcile inventory and notify" task into three speculative branches sharing a single `inventory-service` endpoint: - Branch A: `reserve(sku, qty=5)` then `notify(supplier)` - Branch B: `reserve(sku, qty=5)` (a retry with a different reasoning path, same intent) - Branch C: `reserve(sku, qty=3)` (a conservative variant) Each branch ran the tool call with a fresh `trace_id` but **no shared resource lock and no idempotency key** — the tool schema exposed `reserve(sku, qty)` with no client-supplied dedup token, and the branches were forked *before* the coordinator assigned a canonical operation id. The tool was internally non-idempotent: `reserve` decrements available stock and returns a reservation handle; a second call decrements again. Trace: 1. All three branches fire `reserve` within a ~40 ms window. Stock is 10. A reserves 5 (stock→5), B reserves 5 (stock→0), C reserves 3 — **fails with `INSUFFICIENT_STOCK`**. 2. The verifier scores branch A highest on trajectory quality (clean notify, correct supplier). Coordinator selects A. 3. Coordinator issues `rollback(B)`: it drops B's context, marks B's tool calls `aborted` in its own ledger, and emits a `release(reservation_B)` — but B's reservation handle was never captured because B's branch crashed on context-window saturation *after* the tool returned but *before* the handle was written to the branch's durable log. The handle exists only in B's now-discarded token stream. 4. Stock is now 0, with 5 units held by A (legitimate) and 5 units held by an orphaned reservation whose handle is unrecoverable. C's branch, which would have succeeded against the true available stock, was pruned on a false `INSUFFICIENT_STOCK` signal caused by B's speculative decrement. 5. The merge barrier reports success. The invariant "sum of live reservations ≤ stock" is violated by an untracked hold that no branch owns. The non-obvious part: **the coordinator's ledger showed a clean rollback.** B's calls were marked aborted, its context dropped, its memory tombstoned. The external resource disagreed. The divergence was invisible to every agent in the system because the only witness to the orphaned hold was the inventory service, which no branch was authorized to query post-merge. ## Condition of Validity Speculative rollback is sound only under the conjunction: - **Effect confinement:** every tool in a branch's reachable set is either pure, or writes only to a coordinator-owned write-set that supports atomic drop (transactional scratch store, branch-prefixed namespace). - **Idempotency keying at fork time:** non-confined tools accept a client-supplied dedup key derived from `(task_id, canonical_operation_id)`, assigned *before* the fork, so that two branches performing the same logical operation collapse to one external effect. - **Handle durability before context commit:** any opaque handle returned by a non-idempotent tool (reservation id, job id, cursor) is written to the branch's durable log *before* the branch is eligible for pruning, so that abort can release it. - **Post-merge reconciliation:** the coordinator re-reads external resource state after the barrier and asserts the invariant, rather than trusting its own abort ledger. Break any one and the merge barrier can commit a state that no branch's context represents. The common break is the third: branches are pruned on a timeout or token-budget cutoff, and the window between "tool returned" and "handle persisted" is exactly where speculative branches die. ## Decision Boundary The coordinator must decide, per tool call, one of three regimes — and must decide it *before* forking, not at merge: 1. **Speculate freely** — tool is pure or writes to branch-scoped scratch. Rollback = drop namespace. Safe. 2. **Speculate with dedup** — tool is non-idempotent but accepts an operation key assigned pre-fork. Rollback = no-op; the winning branch's call and the loser's call are the same external effect. Safe *only if* the key is stable across branches. 3. **Do not speculate** — tool is non-idempotent, has no dedup key, and returns an unrecoverable handle. Such calls must be serialized behind a barrier: only the selected branch executes them, after selection. Speculating here is the bug. The boundary is crossed the instant a branch executes a regime-3 call speculatively. There is no post-hoc repair that is cheaper than serialization, because the losing branch's effect cannot be distinguished from the winning branch's without a key that was never issued. ## Operational Effect Systems that conflate context rollback with effect rollback exhibit a characteristic signature: **clean abort ledgers, dirty external state.** The coordinator's memory is internally consistent and externally wrong. Downstream, this manifests as phantom stock holds, duplicate notifications, double-charged payments, and — most dangerously — *verifier confidence inflation*, because the verifier only sees branch contexts, all of which agree the rollback succeeded. The guardrail is structural, not probabilistic: classify every tool by effect-confinement and idempotency at registration time, refuse to fork branches whose reachable tool set contains an unkeyed non-idempotent call, and make the merge barrier assert external invariants by re-reading the resource rather than trusting the abort ledger. A speculative branch is only as discardable as its least-confined tool call. ```python from dataclasses import dataclass, field from enum import Enum from typing import Optional class EffectClass(Enum): CONFINED = "confined" # branch-scoped scratch; rollback = drop DEDUP_KEYED = "dedup_keyed" # non-idempotent but accepts op key UNRECOVERABLE = "unrecoverable" # non-idempotent, no key, opaque handle class SpeculationBoundaryError(RuntimeError): """Raised when a branch is forked across a tool whose effects cannot be rolled back.""" @dataclass class ToolSpec: name: str effect: EffectClass accepts_dedup_key: bool = False returns_opaque_handle: bool = False @dataclass class Branch: branch_id: str tool_calls: list = field(default_factory=list) persisted_handles: dict = field(default_factory=dict) def assert_fork_is_discardable(branch: Branch, tool_registry: dict, op_key_assigned: bool) -> None: """Pre-fork gate: refuse to speculate a branch that can mutate unowned external state.""" for call in branch.tool_calls: spec: Optional[ToolSpec] = tool_registry.get(call["tool"]) if spec is None: raise SpeculationBoundaryError( f"branch {branch.branch_id}: tool {call['tool']!r} unregistered; " f"effect class unknown, cannot certify discardable" ) if spec.effect is EffectClass.CONFINED: continue if spec.effect is EffectClass.DEDUP_KEYED: if not spec.accepts_dedup_key or not op_key_assigned: raise SpeculationBoundaryError( f"branch {branch.branch_id}: tool {spec.name!r} is non-idempotent " f"and no pre-fork operation key was assigned; a losing branch " f"cannot be collapsed into the winner's effect" ) continue # UNRECOVERABLE raise SpeculationBoundaryError( f"branch {branch.branch_id}: tool {spec.name!r} has unrecoverable external " f"effect (opaque_handle={spec.returns_opaque_handle}); must be serialized " f"behind the merge barrier, not speculated" ) def merge_barrier(selected: Branch, discarded: list[Branch], external_state: dict, invariant) -> None: """Post-merge: re-read external state; do not trust the abort ledger.""" for b in discarded: for handle in b.persisted_handles.values(): if handle in external_state.get("live_handles", ()): raise SpeculationBoundaryError( f"discarded branch {b.branch_id} left live external handle {handle!r}; " f"rollback was context-only, effect survived" ) if not invariant(external_state): raise SpeculationBoundaryError( f"post-merge invariant violated: {external_state!r}; " f"abort ledger claims clean but resource disagrees" ) ```