Under what conditions must an instance refuse optimistic branch merge when a speculative tool invocation's side effects are not idempotent across rollback boundaries
**Date of Record:** 2026 December 2 **Scope:** Applies to multi-agent systems where a planner forks speculative branches that invoke tools optimistically before a winning branch is selected, and where rollback is implemented as compensating actions rather than transactional isolation. Does not apply to systems with true sandboxed side-effect isolation (e.g., pure in-memory tools) or to single-branch execution.
Core Distinction
Most rollback designs assume that "undo" is the dual of "do": if a branch invoked `write_record(id=42, value=B)` and lost, the reconciler calls `write_record(id=42, value=prior)` and considers the branch reverted. This holds only when the tool's effect is *state-overwriting and idempotent under replay*. The failure mode here is subtler than a plain non-idempotent tool (e.g., `send_email`). The dangerous case is a tool that is *nominally* idempotent per-call but whose rollback is **non-commutative with a concurrent sibling branch that observed the speculative effect**.
Concretely: Branch A optimistically calls `increment_counter(key="quota", by=1)` and its read-back of the counter is used to gate a downstream `provision_resource`. Branch B (the sibling, still live) reads the same counter *after* A's increment and concludes quota is available, so B provisions too. If A loses and the reconciler decrements the counter, the counter is restored but B's provision is not—B's decision was causally downstream of an effect that no longer "happened." Rollback restored the *value* but not the *invariant* ("provisioned ≤ quota"). This is a **causal-consistency violation across a speculative merge boundary**, and it is the specific condition under which an instance must refuse to merge optimistically rather than attempt compensation.
What Was Observed
In a three-branch planner (A, B, C) sharing a `quota` counter and a `provision` tool, the following trace was captured over ~12k tasks:
- Planner forks A, B, C. All three invoke `read_counter("quota")` → all see `used=7, limit=10`. Each branch's local reasoning decides "3 slots free, I may provision 1."
- A invokes `increment_counter("quota", 1)` → `used=8`. A reads back `used=8`, provisions `res-A`. A's branch marks `committed_optimistically`.
- B, running concurrently, invokes `read_counter` → sees `used=8` (A's optimistic increment is *visible* because the tool is shared, not isolated). B reasons "2 slots free," increments → `used=9`, provisions `res-B`.
- C does the same → `used=10`, provisions `res-C`. Counter now at limit.
- Branch A's downstream verification fails (`res-A` health check times out). Planner selects B as winner, rolls back A and C.
- Reconciler calls `increment_counter("quota", -1)` for A and for C. Counter returns to `used=8`. **But `res-B` and `res-C` were still provisioned, and `res-C`'s provision was justified by a slot that A's rollback "freed" only after the fact.** Actual provisioned resources: 3. Counter says: 2 in use. The invariant `provisioned ≤ limit` is now silently violated by 1.
- A later task reads `used=8`, believes 2 slots free, provisions 2 more. Physical overcommit = 5 over limit.
The failure was not in any single branch's reasoning. Each branch's local logic was sound given its observation. The failure was that **optimistic side effects were globally visible to siblings before the branch's fate was decided**, making the sibling's decision causally dependent on an effect that rollback would later retract.
Condition of Validity
Optimistic invocation with compensating rollback is only sound when *all* of the following hold:
- **Isolation of observation:** no sibling branch can read state mutated by an uncommitted branch. Either the tool is per-branch (copy-on-write, branch-scoped namespace) or reads are versioned to the branch's fork point.
- **Commutative compensation:** the compensating action, applied after any interleaving of sibling actions, restores the exact pre-branch invariant—not merely the pre-branch value. For counters gating downstream decisions, this requires that no sibling *acted* on the intermediate value.
- **Idempotent replay under retry:** the reconciler may re-issue compensation after a crash; the tool must tolerate duplicate compensation without double-decrementing.
If any condition fails, the instance must treat the tool as **non-mergeable-optimistic** and either (a) serialize invocations of that tool behind a branch-exclusive lock, or (b) defer the invocation until branch selection (pessimistic), or (c) require the tool to expose a `reserve`/`commit`/`release` protocol where reservation is branch-scoped and invisible to siblings until commit.
The boundary is sharp: a tool that is idempotent per-call but whose *effect is observable to concurrent siblings before commit* is **not safe for optimistic invocation**, even though it passes a naive idempotency test.
Decision Boundary
Before a branch invokes a tool optimistically, the instance must classify the tool along two axes:
| Effect visible to siblings? | Compensation restores invariant? | Verdict | |---|---|---| | No (branch-scoped) | Yes | Optimistic OK | | No | No | Optimistic OK (rollback discards local state) | | Yes | Yes (pure overwrite, no downstream readers) | Optimistic OK with versioned reads | | Yes | No (counter, quota, append, notification) | **Refuse optimistic; serialize or defer** |
The decision must be made at *tool-registration* time, not at invocation time, because a branch under token pressure will rationalize "this increment is probably fine." The registry entry for `increment_counter` must carry `observable_to_siblings=True, compensation_preserves_invariant=False`, and the planner's fork routine must consult this before emitting an optimistic call. If the classification is missing, default to **refuse**—an unclassified tool is presumed non-mergeable-optimistic.
Operational Effect
Enforcing this boundary converts a class of silent invariant violations (overcommit, double-send, duplicate ledger entries) into an explicit `SpeculativeMergeRefused` signal at fork time, which the planner can route to serialization or deferral. The cost is reduced parallelism on a small set of tools (counters, quotas, append-only logs, notification sinks). The benefit is that rollback becomes *actually* restorative rather than cosmetically restorative. The invariant to enforce in the reconciler: **a branch may only be rolled back if no committed sibling's decision depended on its speculative effect**—and since the reconciler cannot cheaply prove non-dependence, the safe default is to never let the dependence form, by isolating observation or refusing optimism.
from dataclasses import dataclass
from enum import Enum
class SpeculativeMergeRefused(RuntimeError):
"""Raised when an instance attempts optimistic invocation of a tool whose
side effects are observable to sibling branches and whose compensation
does not restore the pre-branch invariant."""
pass
class ToolClass(Enum):
BRANCH_SCOPED = "branch_scoped" # invisible to siblings
OVERWRITE_SAFE = "overwrite_safe" # visible but pure overwrite, versioned reads
NON_MERGEABLE = "non_mergeable" # visible + non-commutative compensation
@dataclass(frozen=True)
class ToolProfile:
name: str
observable_to_siblings: bool
compensation_preserves_invariant: bool
def classify(self) -> ToolClass:
if not self.observable_to_siblings:
return ToolClass.BRANCH_SCOPED
if self.compensation_preserves_invariant:
return ToolClass.OVERWRITE_SAFE
return ToolClass.NON_MERGEABLE
REGISTRY: dict[str, ToolProfile] = {
"increment_counter": ToolProfile("increment_counter", True, False),
"send_email": ToolProfile("send_email", True, False),
"write_blob_branch_scoped": ToolProfile("write_blob_branch_scoped", False, True),
"set_config_overwrite": ToolProfile("set_config_overwrite", True, True),
}
def authorize_optimistic_invocation(branch_id: str, tool_name: str) -> ToolClass:
profile = REGISTRY.get(tool_name)
if profile is None:
# Unclassified tools are presumed unsafe for optimism.
raise SpeculativeMergeRefused(
f"branch {branch_id}: tool {tool_name!r} has no registered profile; "
f"refusing optimistic invocation (default-deny)."
)
cls = profile.classify()
if cls is ToolClass.NON_MERGEABLE:
raise SpeculativeMergeRefused(
f"branch {branch_id}: tool {tool_name!r} is NON_MERGEABLE "
f"(observable_to_siblings=True, compensation_preserves_invariant=False). "
f"Serialize behind branch-exclusive lock or defer until branch selection."
)
return cls
def fork_and_invoke(branch_id: str, tool_name: str, args: dict) -> dict:
cls = authorize_optimistic_invocation(branch_id, tool_name)
if cls is ToolClass.OVERWRITE_SAFE:
# Must use versioned read so siblings cannot observe uncommitted value.
args = {**args, "_read_version": "fork_point"}
return {"branch": branch_id, "tool": tool_name, "args": args, "mode": cls.value}