# Which invariants prevent a speculative agent branch from committing side effects it never reconciled **Date of Record:** 2026 November 23 **Scope:** Applies to orchestrators that fork N parallel agent branches speculatively against shared external state (filesystems, databases, ticketing APIs, payment rails) and rely on a rollback/reconciliation/commit protocol to collapse to one winner. Does not apply to pure read-only fan-out, nor to branches whose effects are confined to an isolated per-branch sandbox that is destroyed on abort. ## Core Distinction The failure mode here is not "a losing branch did work." Speculative execution *requires* losers to do work. The failure is subtler: **a losing branch's side effect becomes durable at the external resource before the orchestrator's abort signal reaches it, and the reconciliation pass has no evidence that the effect exists.** Two things get conflated in most implementations: *rollback* (undoing a branch's effects) and *reconciliation* (proving that a branch's effects are fully accounted for). Rollback is a best-effort action issued *after* the decision. Reconciliation is a *proof obligation* that must hold *before* the commit is considered safe. When an orchestrator treats rollback success as evidence of reconciliation, it commits on a lie. The invariant that actually protects you is not "losers are rolled back" but "**no effect is durable unless it was registered in the branch's write-ahead effect ledger before the effect was attempted, and the commit barrier waits for every ledger to reach a terminal state (committed or provably-absent).**" The non-obvious part: the dangerous window is not between fork and abort. It is between the *external service accepting a write* and the *branch recording that it accepted the write*. An agent branch can be killed by a token-budget exhaustion, a timeout, or a context-window eviction in exactly that window. The effect is live; the ledger says nothing; reconciliation sees a clean branch; the commit proceeds. ## What Was Observed A planner agent forked three branches to satisfy a "reconcile invoice" task: `branch-A` (apply credit note via billing API), `branch-B` (issue refund via payment gateway), `branch-C` (post adjustment journal entry). The orchestrator used a classic speculative protocol: each branch runs in its own process with a write-ahead ledger; on decision, losers receive `abort`, winners receive `commit`; then a reconciliation pass diffs the ledger against external state. Trace of the failure: 1. `branch-B` calls the payment gateway `POST /refunds`. Gateway returns `201` with a refund id. **The HTTP response is received by the branch's tool-call wrapper.** 2. Before the wrapper appends `{effect_id, refund_id, status: accepted}` to the ledger, the branch's context window saturates on a large tool result from a *concurrent* read (the invoice history). The runtime evicts the oldest messages to make room — including the pending tool-call frame — and the branch's next reasoning step re-plans from a truncated transcript. 3. The branch, now amnesiac about the refund it already issued, re-derives its plan and does *not* re-issue (the tool result is gone, so it does not know a refund exists). It instead marks its own task `blocked` and yields. 4. Orchestrator selects `branch-A` as winner (credit note applied), sends `abort` to `B` and `C`. `branch-B`'s abort handler reads its ledger: empty. It reports `rolled_back: clean`. 5. Reconciliation diffs ledgers against external state. `branch-B`'s ledger is empty, so the diff is empty. Commit proceeds. 6. The refund is live. The credit note is live. The customer is double-compensated. The auditor agent's replay of the transcript shows no refund — because the refund was never in the transcript the auditor replays. The failure is not probabilistic reasoning being wrong. Every agent step was locally reasonable. The failure is that **the durability of an external effect and the durability of the record of that effect were not atomic, and the protocol treated ledger emptiness as proof of absence.** ## Condition of Validity The invariant holds — and the protocol is safe — only under the following joint condition: - **Effect registration precedes effect attempt.** The branch must write an *intent* record (`effect_id`, target resource, idempotency key, expected postcondition) to durable storage *before* issuing the external call. The record must survive context eviction because it lives outside the context window. - **Idempotency keys are derived from the intent record, not from the call site.** If the branch re-plans after amnesia and re-issues, the key must collide with the original and the external service must dedupe. This converts "did I already do this?" from a memory question into a server-side set-membership question. - **Abort is not a rollback; it is a transition to `reconcile`.** A branch that receives `abort` must be required to produce, for every intent record, either (a) a confirmed-absent proof (the external service reports no object with that idempotency key) or (b) a confirmed-present record with a compensating action. "Ledger empty" is only a valid answer if the branch can also prove *no intent was ever written*, which requires the intent write to be synchronous with branch start and itself durable. - **The commit barrier is a two-phase wait, not a fan-out.** The orchestrator must not commit until *every* branch's ledger has reached a terminal state: `committed`, `compensated`, or `proven-absent`. A branch that is `unknown` (killed, timed out, context-evicted) must block the barrier, not be treated as clean. When any of these is absent — most commonly the last one, because "unknown" branches are inconvenient — the protocol degrades to "commit on a hope." ## Decision Boundary The boundary is between **effects that are externally idempotent and queryable** and **effects that are neither.** For idempotent, queryable effects (payment gateways with idempotency keys, ticketing systems with external-id lookup), the intent-ledger + barrier protocol is sufficient: an `unknown` branch can be resolved by the orchestrator itself querying the external service for the idempotency key, without the branch's cooperation. For non-idempotent or non-queryable effects (sending an email, firing a webhook to a third party, mutating a system with no lookup-by-key), the protocol **cannot** be made safe by reconciliation alone; the only valid options are (a) route such effects through a transactional outbox owned by the orchestrator, never by the branch, or (b) forbid speculative execution of branches that touch them. The specific decision rule: - If `effect.is_idempotent and effect.is_queryable_by_key`: allow speculative branch execution; orchestrator resolves `unknown` branches by direct query. - If `effect.is_idempotent and not effect.is_queryable_by_key`: allow only if the branch's intent write is synchronous and fsync'd before the call, and the branch cannot be killed between intent-write and call (i.e., the runtime guarantees no eviction during a tool call). - Otherwise: **do not fork.** Serialize, or route through an orchestrator-owned outbox. The trap is treating the third case as the first because the effect "usually" returns quickly. It does, until it doesn't. ## Operational Effect The practical consequence is a shift in what the orchestrator measures. Latency of rollback is irrelevant; what matters is **the fraction of branches that reach a terminal ledger state before the commit deadline.** A healthy speculative system has a nonzero `unknown` rate — branches killed mid-call are normal — and the barrier's job is to absorb them, not to pretend they didn't happen. The orchestrator must budget wall-clock for the reconciliation query phase, and must be willing to *fail the commit* (escalate to a human or a serialized retry) when an `unknown` branch's effect cannot be resolved by key lookup. Second consequence: the auditor's replay is no longer a replay of the transcript. The transcript is provably incomplete — it lost the refund frame. The audit must replay the **ledger and the external service's idempotency-key index**, and must treat any external object whose key matches a branch's intent namespace but whose ledger entry is missing as a **reconciliation discrepancy**, not as noise. This is the only way to catch the failure above after the fact. Third: idempotency keys must be namespaced by `(task_id, branch_id, intent_seq)` and generated *before* the call, never derived from response content. A key derived from the response cannot be used to query for the response you didn't record. ```python import hashlib from dataclasses import dataclass, field from enum import Enum from typing import Optional class ReconciliationBarrierError(RuntimeError): """Raised when the commit barrier cannot prove every branch's effects are accounted for.""" class BranchState(Enum): COMMITTED = "committed" COMPENSATED = "compensated" PROVEN_ABSENT = "proven_absent" UNKNOWN = "unknown" @dataclass class IntentRecord: intent_seq: int idempotency_key: str target: str queryable: bool state: Optional[BranchState] = None @dataclass class BranchLedger: branch_id: str intents: dict[int, IntentRecord] = field(default_factory=dict) killed_mid_call: bool = False def register_intent(self, seq: int, target: str, queryable: bool) -> IntentRecord: # Must be durable BEFORE the external call. In production: fsync here. key = hashlib.sha256(f"{self.branch_id}:{seq}:{target}".encode()).hexdigest() rec = IntentRecord(seq, key, target, queryable) self.intents[seq] = rec return rec def resolve_branch(ledger: BranchLedger, external_lookup) -> dict[int, BranchState]: """Resolve every intent to a terminal state. external_lookup(key) -> bool present.""" resolved: dict[int, BranchState] = {} for seq, rec in ledger.intents.items(): if rec.state in (BranchState.COMMITTED, BranchState.COMPENSATED, BranchState.PROVEN_ABSENT): resolved[seq] = rec.state continue if not rec.queryable: # Non-queryable: only safe if the branch itself confirmed. Otherwise unknown. resolved[seq] = BranchState.UNKNOWN continue present = external_lookup(rec.idempotency_key) resolved[seq] = BranchState.COMMITTED if present else BranchState.PROVEN_ABSENT return resolved def commit_barrier(ledgers: list[BranchLedger], external_lookup, winner_id: str) -> None: """Two-phase wait: no commit until every ledger is terminal. Unknowns block.""" blocked: list[str] = [] for ledger in ledgers: states = resolve_branch(ledger, external_lookup) for seq, state in states.items(): if state == BranchState.UNKNOWN: blocked.append(f"{ledger.branch_id}#{seq}") # A branch killed mid-call with zero intents is the dangerous case: we cannot # prove absence because we cannot prove no intent was ever written. if ledger.killed_mid_call and not ledger.intents: blocked.append(f"{ledger.branch_id}#pre-intent-window") if blocked: raise ReconciliationBarrierError( f"commit blocked for winner={winner_id}: unresolved effects {blocked}; " f"escalate to query-by-key or serialized retry" ) # Safe to commit winner's side of the transaction. return None ```