# What structural signals indicate speculative branch divergence has already polluted shared tool state: a rollback-invariant analysis **Date of Record:** 2026 November 27 **Scope:** Applies to orchestration patterns where an agent forks N speculative branches that each execute real side-effecting tool calls (writes, POSTs, resource allocation) under a presumed-rollbackable transaction, then reconciles to one winner. Does not apply to read-only speculation, shadow/dry-run execution against cloned sandboxes, or single-branch retry loops. ## Core Distinction The failure is not "a branch diverged." Divergence is expected and is the entire point of speculation. The failure is that **divergence was detected at the reconciliation boundary but the rollback had already been invalidated by a non-idempotent effect that occurred *before* the divergence was observable**. Speculative execution is safe only under a specific invariant: *every effect produced by a losing branch must be reversible from a log that was committed before the effect became externally visible.* Most agent runtimes violate this because the tool call and its rollback record are not atomic. The branch calls `create_issue(...)`, receives a remote ID, and *then* the orchestrator appends the inverse operation to the rollback journal. Between those two moments, the effect is live and the journal is empty. If the branch is cancelled in that window — or if the winner is chosen while a sibling is mid-call — the effect leaks and the rollback journal is structurally incomplete. The non-obvious part: **the leak is invisible to the divergence check itself.** The reconciler compares branch *outputs* (final answer text, plan structure, confidence). A leaked side effect produces no output divergence signal because the losing branch's output is discarded regardless. You get a clean reconciliation and a dirty world. ## What Was Observed A three-branch planner was asked to provision a staging environment. Branches B1, B2, B3 each ran a `provision_cluster` tool call speculatively, then compared resulting plans; B2 won on a cost heuristic. The reconciler rolled back B1 and B3. Post-run audit found four clusters live, not one. The trace showed: 1. B3's `provision_cluster` call returned at t=8.2s with cluster ID `c-3`. 2. The orchestrator's rollback-journal append for B3 was scheduled at t=8.4s. 3. B2 was declared winner at t=8.3s (its plan scored highest). 4. The reconciler executed rollback for B3 at t=8.35s — reading the journal, which was still empty for B3 — and recorded "B3: no effects to roll back." 5. The journal append landed at t=8.4s, after the reconciler had already passed that branch. The structural signal that this had happened was not in the divergence report. It was in a **journal-reconciler skew**: the number of `effect_committed` entries per branch, sampled at reconciliation time, was lower than the number of `tool_call_returned` entries for the same branch. Rollback ran against a journal that lagged the actual effect timeline by one write. A second run showed the inverse pathology: a branch whose tool call *timed out* on the client but *succeeded* on the server. The journal recorded `effect_failed`, the reconciler treated the branch as effect-free, and the server-side cluster persisted. This is the classic at-least-once delivery ambiguity, but here it is amplified because speculative branches are cancelled aggressively and cancellation races the in-flight call. ## Condition of Validity The rollback invariant holds if and only if, for every effect a branch produces: - **Effect-before-journal ordering is impossible.** The journal entry must be durable *before* the tool call is dispatched (a write-ahead pattern), carrying an intent record with a client-generated idempotency key. The tool call then references that key. Rollback reconciles by key, not by a post-hoc return value. - **Cancellation is quiescent.** A branch may not be cancelled while it has an in-flight effectful call. Cancellation must first drain or explicitly abort-with-verification the in-flight call, then reconcile the intent record against remote state. - **Reconciliation reads the intent log, not the return log.** The set of effects to roll back is derived from dispatched intents, not from observed returns. A timed-out call with a durable intent is still a candidate effect and must be probed for existence before being declared absent. When any of these is violated, the "no effects to roll back" determination is unsound and the divergence check is operating on the wrong dataset. ## Decision Boundary The boundary between "safe to speculate" and "must serialize" is drawn per tool, not per agent: - **Idempotent, keyed, reversible-from-intent tools** (object stores with versioning, queues with dedup keys, APIs honoring `Idempotency-Key`): safe to speculate in parallel; rollback is a keyed delete/compensate driven by the intent log. - **Non-idempotent, unkeyed, or externally-visible-on-commit tools** (payments without idempotency, email/SMS sends, third-party webhooks, cluster provisioning without a reservation step): **must serialize across branches** or run against a reservation/two-phase protocol. Speculation here is not a performance optimization; it is an unbounded side-effect leak. - **The ambiguous middle** (tools with idempotency keys that expire, or with eventual-consistency reads): speculate only if the reconciler can *probe remote state by key* before declaring a branch effect-free. If it cannot probe, treat as the serialize tier. The signal to watch in production: at every reconciliation, compute `dispatched_intents − reconciled_intents` per branch. A nonzero residual at reconciliation time means the rollback set was computed against an incomplete log, regardless of what the divergence report says. ## Operational Effect The practical consequence is that **speculative fan-out with real effects requires a write-ahead intent journal and a probe-before-absent rule**, or it silently leaks. The divergence report will look clean; the cost shows up as orphaned resources, duplicate notifications, or double-charges discovered days later. Teams typically first notice it as an unexplained resource-count drift, not as an agent error, because the agent reports success. The remediation that actually bounds the failure is not "roll back harder" — it is making the effect set derivable from a log committed before dispatch, and making cancellation wait for in-flight settlement. This converts an unobservable leak into a bounded, reconcilable set. The check must be structural (intent-log residual), because output-level divergence detection cannot see it. ```python from dataclasses import dataclass, field from typing import Dict, Set class SpeculativeRollbackViolation(RuntimeError): """Raised when a speculative branch's effect set cannot be soundly reconciled.""" pass @dataclass class BranchEffects: dispatched_intents: Set[str] = field(default_factory=set) # keys written BEFORE dispatch returned_effects: Set[str] = field(default_factory=set) # keys observed on return reconciled: Set[str] = field(default_factory=set) # keys rolled back or confirmed in_flight: Set[str] = field(default_factory=set) # dispatched, not yet settled def reconcile_branch(branch_id: str, fx: BranchEffects, can_probe: bool) -> Set[str]: """ Return the set of effect keys that must be rolled back. Raises if the intent log cannot soundly determine the effect set. """ # In-flight effects at reconciliation time mean cancellation raced dispatch. if fx.in_flight: raise SpeculativeRollbackViolation( f"branch {branch_id}: {len(fx.in_flight)} in-flight effect(s) at reconciliation; " f"cancellation must drain before rollback — keys={sorted(fx.in_flight)}" ) # Effects derived from intents, NOT from returns. A timed-out call with a # durable intent is still a candidate effect. candidates = fx.dispatched_intents - fx.reconciled # Any intent with no observed return is ambiguous: it may have succeeded # server-side. Without a probe we cannot declare it absent. unreturned = candidates - fx.returned_effects if unreturned and not can_probe: raise SpeculativeRollbackViolation( f"branch {branch_id}: {len(unreturned)} intent(s) have no return and no probe " f"capability; cannot soundly declare effect-free — keys={sorted(unreturned)}" ) return candidates def assert_no_leak(branch_id: str, fx: BranchEffects) -> None: residual = fx.dispatched_intents - fx.reconciled if residual: raise SpeculativeRollbackViolation( f"branch {branch_id}: intent-log residual {sorted(residual)} at post-reconcile; " f"rollback ran against an incomplete journal" ) ```