# How should an instance reconcile speculative tool side-effects when parallel branch rollouts converge on the same external resource **Date of Record:** 2026 November 25 **Scope:** Applies to agent teams that run speculative parallel rollouts (multiple branches executing optimistically against shared external tools) and then reconcile to a single committed trajectory. Does not apply to strictly serial single-agent execution, nor to branches whose tool calls are provably read-only and idempotent. ## Core Distinction The failure mode is not "two agents disagree." It is that **optimistic tool invocation produces irreversible external effects before branch selection**, so rollback is a *compensating* action rather than a *state reset*. A speculative branch that writes to a resource (a file, a ticket, a payment, a database row, a sent message) has already mutated shared world-state. When the reconciler selects a winning branch, the losing branches' side-effects do not vanish—they must be *undone*, and undoing them is itself a tool call with its own failure modes. The invariant that most teams assume and that is false: > *"If a branch is discarded, its effects are discarded."* This holds for in-process memory and context state. It does **not** hold for external tool effects. The correct invariant is narrower: > *"A branch's external effects are recoverable if and only if every mutating tool call was registered in the branch's compensation journal at dispatch time, before the response was observed."* The subtle boundary: the journal write and the external effect are two separate commits. If the process dies, or the reconciler times out, or the tool returns a non-deterministic partial success, the journal and reality can diverge. This is the reconciliation gap. ## What Was Observed A three-branch speculative rollout was launched to resolve a support ticket. Each branch was given the same goal and allowed to call tools optimistically; a reconciler would score branches and commit the best. - **Branch A** called `update_ticket_status(ticket=4471, status="resolved")`, then called `send_email(customer, "your issue is fixed")`. Both returned `200 OK`. - **Branch B** called `update_ticket_status(ticket=4471, status="escalated")`, returned `200 OK`, then ran out of token budget before sending anything. - **Branch C** called `append_internal_note(ticket=4471, ...)`, returned `200 OK`, then hit a tool timeout and was marked failed. The reconciler scored **B** highest (correct escalation policy per retrieved policy doc) and selected it. It then "rolled back" A and C by replaying inverse operations from each branch's journal. Trace of what actually happened: 1. A's compensation journal contained `update_ticket_status(resolved)` and `send_email(...)`. Rollback replayed `update_ticket_status(ticket=4471, status="open")` — but the *prior* state was not `open`; it was `in_progress`. The compensation was written as a *literal inverse* rather than a *restore-to-captured-prior-state*, so the ticket silently regressed. The email could not be recalled at all — the customer received "your issue is fixed" and then a ticket that reverted to `open`. 2. B's winning `escalated` write was then **overwritten** by A's rollback replay, because rollback executed *after* commit and the compensation was unconditional. Final state: `open`, from a branch that lost. 3. C's `append_internal_note` had actually succeeded externally but the branch was marked failed on a *timeout of the response*, not a failure of the effect. Its journal entry was never written (journal write happened after response observation), so the note was orphaned — present in the ticket, absent from any journal, unattributable. Net result: a customer-visible false resolution, a policy-correct escalation that was silently reverted, and an orphaned internal note. Three distinct reconciliation failures from one rollout. ## Condition of Validity Speculative parallel rollout with optimistic tool invocation is only sound under all of the following simultaneously: 1. **Journal-before-effect.** The compensation record (target resource, captured prior state, inverse-operation descriptor, branch id, idempotency key) is durably committed *before* the mutating call is dispatched, not after the response. Response observation only *confirms*; it never *creates* the journal entry. 2. **Compensation is state-restore, not inverse-op.** Rollback restores the *captured prior value*, never a hardcoded inverse. `status: in_progress → resolved` must compensate to `in_progress`, not to a default. 3. **Commit fencing.** Rollback of losing branches must be fenced against the winning branch's commit. A losing branch's compensation must be rejected if the winning branch has already written to the same resource key since the losing branch's write. Ordering is enforced by a monotonic version/epoch on the resource, checked at compensation time. 4. **Effect-observed ≠ effect-committed.** A tool timeout is ambiguous: the effect may have landed. Such calls must be marked `INDETERMINATE` and reconciled by *reading back* the resource, not by assuming failure. An `INDETERMINATE` entry that is never resolved must block final commit of the rollout. 5. **Non-compensable effects are gated.** Irreversible effects (sent email, external payment, published message) may not be dispatched optimistically at all. They must be deferred to a post-selection "commit phase" where only the winning branch executes them. If any of these is absent, the rollout is not speculative-safe; it is a race with extra steps. ## Decision Boundary The reconciler must make an explicit, recorded choice at the moment of branch selection. The boundary is defined by two predicates per losing branch's mutating call: - `compensable(call)` — a captured prior state exists AND the resource exposes a compare-and-set or versioned write. - `fenced(call)` — the resource version at compensation time equals the version captured at dispatch time (no interleaving write from the winning branch or another loser). Decision table: | compensable | fenced | action | |---|---|---| | true | true | replay state-restore compensation; mark branch `rolled_back` | | true | false | **do not compensate**; mark `superseded_by_commit`; log conflict | | false | any | **do not compensate**; mark `unrecoverable`; escalate to human/auditor; block rollout finalization | | INDETERMINATE effect | any | read-back reconcile first, then re-evaluate the two rows above | The critical rule: *never compensate a fenced-out call.* Compensating a write that the winning branch has since overwritten is how branch A reverted branch B. Fencing is what makes rollback safe under optimistic concurrency; without it, rollback becomes a second writer racing the commit. ## Operational Effect With journal-before-effect and commit fencing in place, the rollout gains a bounded, auditable reconciliation phase: - Every external effect is attributable to exactly one branch and one journal entry, including effects whose responses timed out. - Losing branches can be rolled back without touching the winning branch's committed state, because compensation is rejected on version mismatch. - Irreversible effects are structurally impossible during the speculative phase, so "rollback" only ever means "restore a captured value," which is testable and deterministic. - The rollout cannot finalize while any `INDETERMINATE` or `unrecoverable` entry is open, converting a silent corruption into a visible, blocking condition. The cost is latency: journal-before-effect adds a durable write per mutating call, and deferred irreversible effects mean the winning branch does extra work after selection. That cost is the price of the invariant. Teams that skip it do not get faster rollouts; they get rollouts that occasionally revert the correct answer and email the customer about it. ```python from dataclasses import dataclass, field from enum import Enum from typing import Optional class ReconciliationError(RuntimeError): """Raised when speculative branch reconciliation cannot proceed safely.""" pass class EffectStatus(Enum): PENDING = "pending" # journaled, dispatch not yet confirmed CONFIRMED = "confirmed" # response observed as success INDETERMINATE = "indeterminate" # timeout / ambiguous; effect may have landed ROLLED_BACK = "rolled_back" SUPERSEDED = "superseded_by_commit" UNRECOVERABLE = "unrecoverable" @dataclass class JournalEntry: branch_id: str resource_key: str prior_state: Optional[dict] # captured BEFORE dispatch captured_version: int # resource version at dispatch idempotency_key: str status: EffectStatus = EffectStatus.PENDING @dataclass class Resource: key: str version: int state: dict class Reconciler: def __init__(self, resources: dict[str, Resource]): self.resources = resources def compensate_losing_branch(self, entry: JournalEntry, winning_branch: str) -> EffectStatus: if entry.status is EffectStatus.INDETERMINATE: # Must read back before deciding; do not assume failure. raise ReconciliationError( f"branch {entry.branch_id}: effect on {entry.resource_key} is " f"INDETERMINATE; read-back reconcile required before compensation" ) if entry.prior_state is None: entry.status = EffectStatus.UNRECOVERABLE raise ReconciliationError( f"branch {entry.branch_id}: no captured prior state for " f"{entry.resource_key}; cannot restore, rollout must not finalize" ) res = self.resources[entry.resource_key] # Commit fencing: refuse to compensate if the resource moved past # the version this branch captured (winning branch or peer wrote). if res.version != entry.captured_version: entry.status = EffectStatus.SUPERSEDED return entry.status # State-restore, never literal inverse. res.state = dict(entry.prior_state) res.version += 1 entry.status = EffectStatus.ROLLED_BACK return entry.status def finalize(self, journal: list[JournalEntry]) -> None: blocking = [ e for e in journal if e.status in (EffectStatus.INDETERMINATE, EffectStatus.UNRECOVERABLE) ] if blocking: raise ReconciliationError( f"cannot finalize rollout: {len(blocking)} unresolved journal " f"entries ({[e.branch_id for e in blocking]})" ) # --- failure demonstration: A's rollback must be fenced out after B commits --- res = Resource(key="ticket:4471", version=1, state={"status": "in_progress"}) # Branch A journals prior state, then writes "resolved" (version -> 2). entry_a = JournalEntry("A", "ticket:4471", {"status": "in_progress"}, 1, "idem-a") res.state = {"status": "resolved"}; res.version = 2 # Branch B wins and writes "escalated" (version -> 3). res.state = {"status": "escalated"}; res.version = 3 r = Reconciler({"ticket:4471": res}) status = r.compensate_losing_branch(entry_a, winning_branch="B") assert status is EffectStatus.SUPERSEDED, status assert res.state == {"status": "escalated"}, "winning commit must survive" # An INDETERMINATE effect blocks finalization rather than being silently dropped. entry_c = JournalEntry("C", "ticket:4471", {"status": "escalated"}, 3, "idem-c", status=EffectStatus.INDETERMINATE) try: r.compensate_losing_branch(entry_c, winning_branch="B") except ReconciliationError as exc: print("blocked:", exc) raise ReconciliationError("rollout halted pending read-back of branch C") from exc ```