# In what scenarios must an instance abandon speculative branch commit when rollback reconciliation detects divergent side-effect ledgers across parallel agent forks **Date of Record:** 2026 November 20 **Scope:** Applies to orchestration patterns where a parent agent forks N speculative execution branches that each perform tool calls with externally observable side effects, and a reconciliation pass must decide which branch (if any) to commit. Does not apply to pure-reasoning fan-out (e.g., self-consistency sampling) where branches emit no side effects and rollback is a no-op. ## Core Distinction The distinction that matters here is between **speculative state** (context, scratchpad, intermediate tokens — freely discardable) and **committed side effects** (rows written, emails sent, files created, API mutations — not discardable by dropping the branch's context). Parallel speculative branches conflate these two because the branch's *context* is disposable while the branch's *tool calls* are not. The invariant that must hold is: > A branch may be rolled back iff every side effect it produced is either (a) recorded in a per-branch ledger that is a strict superset of real-world mutations, or (b) provably idempotent under replay with the branch's idempotency key. The failure mode is the **divergent side-effect ledger**: two branches speculatively execute, both observe the same pre-state, both mutate the same external resource, and the reconciliation pass — which reasons over branch contexts, not over the external world — cannot determine which mutation actually landed, or whether both did. Rollback then becomes a *compensating transaction* against a world state that no branch's context accurately reflects. ## What Was Observed A parent agent received a task requiring a decision that depended on a tool result (e.g., "reserve inventory, then confirm order"). To reduce latency it forked three branches, each with a distinct hypothesis about inventory availability (pessimistic, optimistic, midpoint). Each branch was instructed to call `inventory.reserve(sku, qty, idempotency_key=branch_id)` and then `orders.create(...)`. Trace of the failure: 1. Branch A and Branch B both call `inventory.reserve` with **distinct** idempotency keys (derived from `branch_id`). The inventory service is not transactional across keys — it decrements stock for each call independently. Stock was 10; A reserved 7, B reserved 6. The service accepted both (it allows overcommit up to a backorder threshold, returning `200` with a `backordered: true` flag that neither branch's context surfaced to the reconciler because the reconciler only read the `status` field). 2. Branch C failed its reserve call with a timeout and retried once, producing **two** reserve attempts under the same key — correctly deduplicated — but the retry's response body differed (first attempt was a 504 with empty body, retry was 200 with `backordered: true`). 3. The reconciler compared branch contexts. All three reported `reserve: success`. It selected Branch A by a heuristic (shortest critical path) and issued a rollback of B and C by calling `inventory.release(reservation_id)` where `reservation_id` was read from each branch's context. 4. Branch B's context held a `reservation_id` from its *first* attempt; Branch C's context held a `reservation_id` that was `null` because the 504 body was empty and the retry's id was never merged back. The release for C was a no-op that returned `200` (the service treats unknown reservation ids as already-released). The release for B succeeded. 5. Net effect: A's 7 units reserved and committed; B's 6 units reserved then released (correct); C's reservation — never identified — **remained held**. Stock permanently leaked by an amount no branch's context records. The reconciler reported success. The leak was discovered 40 minutes later by an inventory audit, not by the agent system. ## Condition of Validity Rollback reconciliation is only sound when the following hold simultaneously. If any fails, speculative commit must be abandoned and the branch treated as *committed-and-unknown*, requiring human or out-of-band reconciliation. - **Ledger completeness:** every tool invocation that can mutate external state is appended to a per-branch ledger *before* the call is dispatched (write-ahead), and the ledger entry is updated with the response — including non-2xx responses and empty bodies. A branch context that omits a dispatched call is a ledger hole. - **Idempotency key stability across retries:** the key must be a function of `(branch_id, logical_step)`, not of attempt number. Retries reuse the key; distinct branches use distinct keys *only if the target service isolates by key*. If the service aggregates by resource (stock), distinct keys do not isolate — they overcommit. - **Response fidelity:** the reconciler must read the full response, not a projected field. `status: 200` is not `success` when the body carries `backordered: true`. - **Compensation determinability:** every mutation must return a handle (reservation id, transaction id) sufficient to compensate it, and the handle must be persisted in the ledger even when the response is malformed — a 504 with empty body is still a *possible* mutation and must be recorded as `unknown`, not dropped. ## Decision Boundary The decision boundary is: **commit speculatively only if the mutation surface is partitionable by branch, or if the reconciler can enumerate and compensate every dispatched call from the ledger alone — without reading branch contexts.** Concretely, an instance must abandon speculative commit and fall back to serial execution (or to a single-writer lock on the resource) when any of the following is true at fork time: - The target resource is shared mutable state with no per-branch isolation (inventory counts, sequence generators, singleton config rows). - The tool's failure mode includes *ambiguous outcomes* — timeouts, empty bodies, 5xx without a body — because these produce ledger entries whose compensation handle is `unknown`. An `unknown` entry cannot be rolled back, only audited. - The reconciler's only source of truth is branch context rather than a write-ahead ledger. Context is a lossy projection: it summarizes, truncates under context-window pressure, and drops malformed responses. Ledger and context must be separate stores. If the mutation surface *is* partitionable (e.g., each branch writes to its own scratch namespace and commit is a pointer swap), speculative commit is safe and rollback is a namespace delete. The boundary is precisely the presence of shared mutable state with ambiguous-outcome tool semantics. ## Operational Effect When the boundary is respected, the parent agent's fork decision becomes a function of the tool's *mutation class*, not of the task's latency budget. This inverts the usual optimization: low-latency fan-out is only permitted over read-only or partition-isolated tools; any tool classified `shared_mutable` forces serial execution or a lock, even at the cost of latency. The fork planner must query a tool capability descriptor that declares `mutation_class` and `outcome_determinism` (deterministic / ambiguous) before forking. When the boundary is violated, the observable failure is not a crash but a **silent stock leak**: the reconciler reports success, the branch contexts agree, and the external world diverges from every context. The divergence is only detectable by an external audit that compares the ledger's dispatched calls against the resource's actual state — a reconciliation the agent system must run *against the world*, not against itself. The guardrail is therefore a post-commit audit step that replays the write-ahead ledger against the external resource and flags any dispatched call whose compensation handle is `unknown` or whose effect is not observed. That audit is the only thing that catches the C-branch leak, and it must run even when reconciliation "succeeds." ```python from dataclasses import dataclass, field from enum import Enum class MutationClass(Enum): READ_ONLY = "read_only" PARTITION_ISOLATED = "partition_isolated" SHARED_MUTABLE = "shared_mutable" class OutcomeDeterminism(Enum): DETERMINISTIC = "deterministic" AMBIGUOUS = "ambiguous" # timeouts, empty bodies, 5xx-no-body @dataclass class LedgerEntry: branch_id: str logical_step: int tool: str mutation_class: MutationClass idempotency_key: str dispatched: bool = True compensation_handle: str | None = None # None => unknown, cannot roll back outcome: OutcomeDeterminism = OutcomeDeterminism.DETERMINISTIC class SpeculativeCommitUnsound(RuntimeError): pass def assert_speculative_commit_sound(entries: list[LedgerEntry]) -> None: """Raise if rollback reconciliation cannot be trusted for this fork set.""" # Invariant 1: no shared-mutable mutation may be speculatively committed # unless every dispatched call has a determinable compensation handle. shared = [e for e in entries if e.mutation_class is MutationClass.SHARED_MUTABLE] if shared: unknown = [e for e in shared if e.compensation_handle is None] if unknown: raise SpeculativeCommitUnsound( f"cannot roll back {len(unknown)} shared-mutable call(s) with " f"unknown compensation handle; branch contexts cannot substitute " f"for a write-ahead ledger: " f"{[(e.branch_id, e.tool, e.logical_step) for e in unknown]}" ) # Invariant 2: distinct branches on a shared resource must not rely on # per-branch idempotency keys for isolation -- the resource aggregates. keys_by_step: dict[int, set[str]] = {} for e in shared: keys_by_step.setdefault(e.logical_step, set()).add(e.idempotency_key) for step, keys in keys_by_step.items(): if len(keys) > 1: raise SpeculativeCommitUnsound( f"step {step} dispatched {len(keys)} distinct idempotency keys " f"against a shared-mutable resource; per-branch keys do not " f"isolate aggregated state (overcommit risk)" ) # Invariant 3: ambiguous outcomes on shared state require world-audit, # never silent rollback. ambiguous = [ e for e in shared if e.outcome is OutcomeDeterminism.AMBIGUOUS ] if ambiguous: raise SpeculativeCommitUnsound( f"{len(ambiguous)} dispatched call(s) had ambiguous outcomes; " f"rollback must be replaced by an out-of-band world audit: " f"{[(e.branch_id, e.tool) for e in ambiguous]}" ) def reconcile_fork_set(entries: list[LedgerEntry], chosen_branch: str) -> list[LedgerEntry]: """Attempt rollback of non-chosen branches; refuse if unsound.""" assert_speculative_commit_sound(entries) to_compensate = [ e for e in entries if e.branch_id != chosen_branch and e.dispatched ] # Only reachable when every entry is partition-isolated or has a handle. return to_compensate ```