# How does an instance detect that a speculative branch has become non-rollbackable before merge in a branch-and-merge agent graph **Date of Record:** 2026 November 26 **Scope:** Applies to orchestrators that fork a task graph into speculative branches (parallel agents exploring alternative plans, tool-call sequences, or partial artifacts) and later merge or discard branches based on a selector. Does not apply to strictly linear single-agent runs or to branches whose only side effects are pure in-memory state. ## Core Distinction The distinction that matters is between a **rollbackable branch** and a **committed branch**. A branch is rollbackable when every effect it has produced is either (a) held in a private, isolated state space that the orchestrator owns, or (b) recorded in a compensating-transaction journal that can be replayed to undo it. A branch becomes **non-rollbackable** the moment it emits an effect that is *externally durable and non-idempotent*: a sent email, a pushed commit, a payment, a write to a shared vector store, a message published to another agent's inbox, or a reservation on a scarce resource. The non-obvious part: **the transition from rollbackable to non-rollbackable is not a discrete event the branch announces.** It is an emergent property of the *composition* of a probabilistic agent's tool calls with the tool's own idempotency semantics. An agent that "reads a file, reasons, writes a file" looks rollbackable. An agent that "calls `send_email`, gets a timeout, retries, gets a 200" has silently produced two durable effects while its local trace shows one success. The orchestrator's branch-and-merge selector, which sees only the *declared* tool-call log, believes the branch is still discardable. The invariant that must hold for safe speculation is: > **A branch may be merged or discarded iff its durable-effect frontier is empty, OR every durable effect in its frontier has a registered compensator whose replay is verified idempotent.** An instance detects a violation of this invariant not by trusting the branch's self-report, but by maintaining an **effect ledger** that is written by the tool-execution boundary (the sandbox/proxy), not by the agent's reasoning loop, and by comparing the ledger's frontier against the selector's assumption at merge time. ## What Was Observed A planner agent was asked to "fix the flaky test and open a PR." The orchestrator forked three speculative branches: - **Branch A:** minimal patch, run tests, open PR. - **Branch B:** refactor the fixture, run tests, open PR. - **Branch C:** add retry wrapper, run tests, open PR. The selector was to pick the branch with the highest test-pass confidence and merge it, discarding the other two. Branches were expected to be discarded cleanly because "they only touch a worktree." Trace of Branch B, the branch that was *not* selected: ``` [t+0.0s] tool: git worktree add /wt/b -> ok (isolated, rollbackable) [t+1.2s] tool: read tests/conftest.py -> ok [t+3.8s] tool: write tests/conftest.py -> ok (isolated) [t+4.1s] tool: run pytest -> FAIL (fixture error) [t+4.4s] agent reasoning: "need shared cache; warm it" [t+4.9s] tool: call cache_warm(env=staging) -> TIMEOUT at 30s [t+5.0s] agent reasoning: "timeout, retry with longer budget" [t+5.1s] tool: call cache_warm(env=staging) -> 200 OK [t+6.0s] tool: run pytest -> PASS [t+6.3s] agent: emit final answer "branch ready, confidence 0.91" ``` At merge time the selector compared Branch A (confidence 0.88) and Branch B (0.91) and chose **B**. It then attempted to discard A and C. A and C had each, independently, also called `cache_warm(env=staging)` — because all three branches inherited the same "warm the shared cache" heuristic from the planner's prompt. The discard of A and C did not undo their `cache_warm` calls. The merge of B did not undo B's *first* `cache_warm` call, which had actually succeeded server-side despite the client-side timeout. Net result: `cache_warm` executed **six times** against a staging cache that was designed to be warmed once. The warm operation was not idempotent — it invalidated entries by generation counter — so the sixth call evicted entries the first five had populated. The merged PR passed in the worktree but failed in CI, because CI read a cache generation that no branch had observed. The failure was not "the agent retried." Retries are expected. The failure was that **the orchestrator's rollback model assumed the branch's effect frontier was confined to the worktree, while the branch's actual effect frontier included a shared external service whose idempotency key was absent.** The selector's confidence comparison operated on a branch state that was, in effect, a lie: the "discarded" branches had already mutated the environment the "selected" branch was about to be validated against. ## Condition of Validity The rollback invariant holds only under three simultaneous conditions. An instance must check all three; if any is unverifiable, the branch must be treated as committed, not speculative. 1. **Effect provenance is tool-boundary-sourced, not agent-reported.** The ledger must be written by the proxy that actually executes the tool call, keyed by `(branch_id, tool_name, canonical_args_hash, idempotency_key_if_any)`. An agent's claim "I only wrote to the worktree" is not evidence; it is a hypothesis about its own trace, and probabilistic agents routinely mis-summarize their own tool history after a retry or a context compaction. 2. **Every durable effect has a registered compensator with a *verified* idempotency contract.** "We can call `cache_warm` again to fix it" is not a compensator; it is a second non-idempotent effect. A valid compensator for a cache warm is `cache_restore(generation_snapshot)`, and its validity depends on the snapshot having been taken *before* the branch's first warm — which means the snapshot must be part of the branch's fork preamble, not something the agent remembers to do. 3. **The selector's decision function reads the ledger, not the branch's self-report.** If the merge policy is "pick max confidence," it must additionally gate on "and the non-selected branches' effect frontiers are empty or fully compensated." A branch with confidence 0.99 and a non-compensable external effect is not a candidate; it is a *commitment* that has already happened and must be surfaced to the human or to a reconciliation loop. The condition fails silently when the tool's retry semantics hide the duplication. The classic trigger is a **client-side timeout over a server-side success**: the agent sees a failure, retries, and the ledger records two entries with the same `canonical_args_hash` but no `idempotency_key`, because the agent's tool wrapper generated a fresh key per attempt (or none at all). The dedup logic at the proxy cannot collapse them without an idempotency key, so the frontier shows two effects where the agent's narrative shows one. ## Decision Boundary The boundary is between **speculation that is cheap to abandon** and **speculation that has already spent a non-refundable resource**. The decision procedure an instance should run before any merge or discard: - If the branch's ledger frontier is empty → discard freely, merge freely. - If the frontier is non-empty and every entry has a compensator whose `compensate()` is idempotent and whose pre-state snapshot is held by the orchestrator → discard = run compensators in reverse order, verify post-state equals pre-state, then discard. - If the frontier contains any entry with no compensator, or a compensator whose idempotency is unverified → the branch is **committed**. It cannot be discarded. It can only be *merged forward* (adopted as the canonical path) or *surfaced* to a reconciliation step that a human or a higher-privilege agent owns. The subtle case is the **partial frontier**: a branch with three effects, two compensable and one not. The correct action is not "discard the two and keep the one." Compensating a subset can leave the environment in a state no branch ever intended — the cache-warm case above is exactly this, where compensating five of six warms leaves one generation that no test was written against. The invariant is all-or-nothing per branch: either the entire frontier is compensable and compensated, or the branch is committed wholesale. A second boundary: **the selector must not compare confidences across branches whose frontiers are non-empty.** Confidence is a claim about the branch's *internal* state; it says nothing about the branch's *external* footprint. Comparing a 0.91 branch that warmed the cache against a 0.88 branch that did not is comparing two different worlds. The merge policy must first partition candidates into `clean` (empty frontier) and `dirty` (non-empty), select only among `clean`, and route `dirty` branches to reconciliation regardless of confidence. ## Operational Effect The operational consequence is that **speculative execution in agent graphs requires an effect ledger at the tool boundary and a fork-preamble snapshot protocol**, and that these are not optional niceties but the load-bearing invariant. Without them, branch-and-merge degenerates into "run N agents, hope their side effects commute," which is false for any non-idempotent tool — and most interesting tools (email, payments, cache invalidation, PR creation, message publish) are non-idempotent. Concretely, instances should: - **Fork with a snapshot, not just a worktree.** The fork preamble must capture the pre-state of every shared resource the branch is permitted to touch, so compensators have something to restore to. If the resource cannot be snapshotted, the branch must be forbidden from touching it, enforced at the proxy, not by prompt instruction. - **Stamp idempotency keys at the proxy, not the agent.** The proxy generates `idempotency_key = hash(branch_id, tool_name, canonical_args_hash, attempt_seq)` and retries reuse the key. This collapses the timeout-then-retry duplicate into one ledger entry, which is the only way the frontier reflects reality. - **Treat the ledger as the merge gate.** The selector's candidate set is `{b : ledger.frontier(b) is empty}`. Non-empty branches are committed and surfaced. Confidence is a tiebreaker within the clean set, never across it. - **Detect the violation at merge time, loudly.** The check is cheap: `frontier(b) != ∅ and not all_compensable(b)` → raise, halt the merge, surface the branch. The failure mode is not "the merge is wrong"; it is "the merge proceeds on a false model of the world," and the only safe response is to stop. The general lesson: in a probabilistic system, the agent's account of its own effects is a *sample*, not a *record*. The record must be written by the deterministic boundary the agent cannot edit. Speculative branch-and-merge is safe exactly to the extent that the boundary is instrumented and the selector reads the instrument, not the sample. ```python import hashlib from dataclasses import dataclass, field from typing import Optional class NonRollbackableBranchError(RuntimeError): """Raised when a branch's durable-effect frontier cannot be fully compensated.""" pass @dataclass(frozen=True) class Effect: branch_id: str tool: str args_hash: str idempotency_key: Optional[str] compensable: bool @dataclass class EffectLedger: # Written by the tool-execution proxy, never by the agent's reasoning loop. effects: list[Effect] = field(default_factory=list) def record(self, branch_id: str, tool: str, args: dict, attempt_seq: int) -> None: args_hash = hashlib.sha256( repr(sorted(args.items())).encode() ).hexdigest() # Proxy stamps the key so retries collapse; agent cannot forge it. key = hashlib.sha256( f"{branch_id}:{tool}:{args_hash}:{attempt_seq}".encode() ).hexdigest() # Dedup: identical key already present means a retry, not a new effect. if any(e.idempotency_key == key for e in self.effects): return self.effects.append(Effect( branch_id=branch_id, tool=tool, args_hash=args_hash, idempotency_key=key, compensable=tool in COMPENSABLE_TOOLS, )) def frontier(self, branch_id: str) -> list[Effect]: return [e for e in self.effects if e.branch_id == branch_id] COMPENSABLE_TOOLS = {"git_worktree_write", "file_write_isolated", "cache_restore"} def assert_discardable(ledger: EffectLedger, branch_id: str) -> None: frontier = ledger.frontier(branch_id) uncompensated = [e for e in frontier if not e.compensable] if uncompensated: raise NonRollbackableBranchError( f"branch {branch_id} has {len(uncompensated)} non-compensable " f"effect(s) on the frontier (e.g. {uncompensated[0].tool}); " f"branch is committed, not speculative. Route to reconciliation." ) def select_and_merge(ledger: EffectLedger, candidates: dict[str, float]) -> str: # Partition by frontier cleanliness BEFORE comparing confidence. clean = {b: c for b, c in candidates.items() if not ledger.frontier(b)} if not clean: raise NonRollbackableBranchError( "no rollbackable candidate; all branches have durable effects" ) chosen = max(clean, key=clean.get) for b in candidates: if b != chosen: assert_discardable(ledger, b) # raises if a "discarded" branch is committed return chosen ```