# When must an instance fence speculative tool calls before rollback reconciliation, and what breaks if it doesn't **Date of Record:** 2026 November 22 **Scope:** Applies to any multi-agent system where a coordinator forks sibling speculative branches (each with tool-call authority) that may be rolled back and reconciled against a committed lineage. Does not apply to strictly sequential single-agent execution or to branches whose tools are pure/read-only and side-effect-free by contract. ## Core Distinction The failure is not "a speculative branch made a wrong tool call." It is that a speculative branch's **tool-call effect** can outlive the **branch's logical rollback** because the effect was dispatched to an external system that has no knowledge of the branch's lifecycle. Rollback in the orchestrator is a *state-tree* operation: it truncates the branch's message history, discards its scratchpad, and marks the branch `abandoned`. But a tool call already `in-flight` or already `committed` at the tool boundary is a *distributed-systems* operation with its own linearization point. The two are reconciled only if the orchestrator establishes a **fencing invariant**: no tool effect originating from a branch may be committed to the shared world-state after that branch has been marked abandoned, and no reconciliation may read a branch's tool result as authoritative unless the effect is fenced to that branch's epoch. The non-obvious part: speculation *requires* pre-execution of tool calls (that is what makes it speculative rather than sequential), so you cannot avoid dispatching effects before you know whether the branch survives. You can only fence them. Systems that conflate "rollback the branch" with "rollback the branch's effects" pass their happy-path tests and then double-spend, double-write, or resurrect stale observations under contention. ## What Was Observed A coordinator spawned three speculative branches to answer a single user request requiring a database mutation (`reserve_inventory`) and a downstream confirmation. Branch A and Branch B both selected `reserve_inventory(sku=4471, qty=2)` as their plan's first action; Branch C selected a read-only path. The coordinator's reconciliation policy was "first branch to return a passing verification wins; abandon the rest." Trace: 1. `t=0ms` — Coordinator forks A, B, C. Each receives a branch token `(branch_id, epoch=1)`. 2. `t=40ms` — Branch A dispatches `reserve_inventory(sku=4471, qty=2)`. Tool gateway accepts, returns `reservation_id=R-8801` at `t=95ms`. 3. `t=42ms` — Branch B dispatches the *same* call. Gateway has no idempotency key tied to the logical intent, only to the raw arguments, and the two branches generated byte-identical arguments but distinct request IDs. Gateway accepts a second reservation `R-8802`. 4. `t=110ms` — Branch A's verification passes. Coordinator commits A, marks B and C `abandoned`, emits rollback for B. 5. `t=111ms` — Rollback truncates B's history and discards its scratchpad. It does **not** call `release_inventory(R-8802)` because the orchestrator never modeled B's tool effects as reversible — they were "just a tool result in B's context." 6. `t=112ms` — Reconciliation reads the committed lineage. It sees `R-8801` in A's context. It has no record of `R-8802` because that reservation lives in B's now-discarded context. 7. Net effect: inventory is decremented by 4 units; the committed answer claims 2. The orphaned reservation `R-8802` is invisible to every subsequent agent in the lineage and will only surface as a stock discrepancy hours later. A second observed variant: Branch B's tool call was *in-flight* when B was abandoned. The gateway committed it at `t=130ms` — 19ms after rollback. The orchestrator had already garbage-collected B's branch record, so the late-arriving result was delivered to a dead mailbox and dropped. The effect persisted; the record of it did not. ## Condition of Validity The fencing invariant holds only when all three of the following are true simultaneously: - **Epoch binding at the tool boundary.** Every tool request carries the issuing branch's `(branch_id, epoch)`, and the gateway rejects (or quarantines) any commit whose branch is not in the coordinator's *live* set at commit time. This requires the gateway to consult coordinator liveness — a distributed check, not a local one. - **Effect journaling outside branch context.** Every dispatched tool call is recorded in a coordinator-owned journal keyed by `(branch_id, epoch, request_id)`, *independent of branch message history*. Rollback must consult this journal, not the branch's context, to determine what to compensate. - **Compensation is defined and idempotent.** For every mutating tool there exists a compensating action (`release_inventory`) keyed by the original `request_id`, and that compensation is safe to call twice (in case both the rollback path and a late reconciliation path attempt it). If any one is missing, the invariant is violated. Most systems have (1) partially (branch IDs in logs but not enforced at commit), lack (2) entirely (effects are inferred from branch context), and assume (3) ("the tool has a cancel endpoint"). ## Decision Boundary The boundary is: **does the branch's tool effect have a linearization point that can occur after the branch's abandonment decision?** - If the tool is **synchronous and committed before the branch can be abandoned** (e.g., a read that returns within the branch's own execution step, with no post-return side effect), rollback-by-context-truncation is sufficient. No fencing needed. - If the tool is **asynchronous, retried, or has post-return side effects** (writes, reservations, message sends, webhooks), then the abandonment decision and the commit decision are concurrent and *must* be serialized by an epoch fence. Rollback-by-context-truncation is unsound. The trap: a branch may be abandoned *while a tool call is in-flight*, so the decision boundary is not "did we dispatch a mutating call" but "can any dispatched mutating call still commit after we decide to abandon." Any tool with a network hop qualifies. This is the majority of real tools. The correct rule: **abandonment must be a two-phase operation.** Phase 1 marks the branch `fenced` (no new dispatches, gateway will reject commits for this epoch). Phase 2 waits for in-flight calls to drain or be rejected, then compensates journaled effects, then marks `abandoned`. Reconciliation reads only `committed` branches whose journals are drained. ## Operational Effect Without the fence, speculative execution silently violates the system's most basic invariant — that the committed world-state equals the sum of committed branch effects — and the violation is *unobservable from within the lineage* because the orphaned effect lives in a discarded context. Downstream agents inherit a world-state that is ahead of their beliefs, and their own speculative branches compound the drift. In the observed case, a subsequent agent re-reserved the same SKU based on the committed lineage's claim of 2 units, producing a third reservation, and the discrepancy grew with each reconciliation round. With the fence, the cost is latency: abandonment now costs one drain interval (bounded by the tool gateway's timeout) plus compensation calls. Speculative branches that might be abandoned must budget this. The benefit is that reconciliation is *sound*: the committed lineage's tool effects are exactly the journaled effects of committed branches, and every other effect has been compensated or rejected. This is the only condition under which branch reconciliation can be trusted to produce an answer an auditor agent can replay. The practical guardrail: make the fence a property of the *tool gateway*, not the orchestrator. The orchestrator cannot reliably know whether its abandonment message beat an in-flight commit; only the gateway, which holds the linearization point, can enforce "reject commits for epochs not in the live set." Orchestrator-side rollback that assumes it can recall dispatched calls is the failure mode. ```python from dataclasses import dataclass, field from typing import Dict, Set, Optional import time class SpeculativeFenceViolation(RuntimeError): """Raised when a tool effect commits for a branch that is no longer live.""" pass @dataclass class ToolEffect: branch_id: str epoch: int request_id: str compensation: Optional[str] = None committed: bool = False class FencedToolGateway: """ Enforces the fencing invariant: a tool effect may only commit while its issuing branch is in the coordinator's live set. Abandonment is two-phase: fence (reject new commits) -> drain -> compensate -> abandon. """ def __init__(self) -> None: self._live: Set[str] = set() self._fenced: Set[str] = set() self._journal: Dict[str, ToolEffect] = {} self._inflight: Dict[str, ToolEffect] = {} def register_branch(self, branch_id: str, epoch: int) -> None: self._live.add(branch_id) def dispatch(self, effect: ToolEffect) -> str: if effect.branch_id in self._fenced or effect.branch_id not in self._live: raise SpeculativeFenceViolation( f"dispatch rejected: branch {effect.branch_id} not live" ) self._inflight[effect.request_id] = effect return effect.request_id def commit(self, request_id: str) -> None: effect = self._inflight.get(request_id) if effect is None: raise SpeculativeFenceViolation(f"unknown request {request_id}") # The linearization point. This is where the race is decided. if effect.branch_id in self._fenced or effect.branch_id not in self._live: del self._inflight[request_id] raise SpeculativeFenceViolation( f"commit rejected for fenced/abandoned branch {effect.branch_id}; " f"effect {request_id} must be compensated, not applied" ) effect.committed = True self._journal[request_id] = effect del self._inflight[request_id] def abandon(self, branch_id: str, drain_timeout_s: float = 2.0) -> None: """Two-phase abandonment. Phase 1 fences; phase 2 drains + compensates.""" self._fenced.add(branch_id) # phase 1: no new commits accepted deadline = time.time() + drain_timeout_s while time.time() < deadline: pending = [r for r, e in self._inflight.items() if e.branch_id == branch_id] if not pending: break time.sleep(0.01) # phase 2: compensate anything that committed before the fence and # reject anything still in flight (its commit will fail the fence check). for request_id, effect in list(self._journal.items()): if effect.branch_id == branch_id and effect.compensation: self._apply_compensation(effect) for request_id in [r for r, e in self._inflight.items() if e.branch_id == branch_id]: del self._inflight[request_id] self._live.discard(branch_id) self._fenced.discard(branch_id) def _apply_compensation(self, effect: ToolEffect) -> None: # Idempotent by request_id; safe to call from rollback and reconciliation. ... def reconcile(committed_branch: str, gateway: FencedToolGateway) -> Dict[str, ToolEffect]: if committed_branch not in gateway._live: raise SpeculativeFenceViolation( f"cannot reconcile non-live branch {committed_branch}" ) return { rid: eff for rid, eff in gateway._journal.items() if eff.branch_id == committed_branch and eff.committed } ```