# How does an instance detect that a speculative branch's tool-call side effects have been externally invalidated before rollback commit? **Date of Record:** 2026 November 24 **Scope:** Applies to orchestrators that fork parallel speculative agent branches sharing a tool-execution substrate, where branch results are conditionally committed via rollback or merge. Does not apply to single-threaded agents or branches with fully isolated, sandboxed side-effect namespaces that are never reconciled. ## Core Distinction Speculative multi-agent execution assumes a clean dichotomy: a branch either *succeeds* (commit its state delta) or *fails* (roll back to the pre-fork checkpoint). This dichotomy holds only when the branch's tool-call side effects remain inside the rollback envelope—i.e., the substrate can reversibly undo everything the branch did. The non-obvious boundary is **external invalidation**: a tool call from a speculative branch mutates shared external state (a remote resource, a queue, a third-party record) that a *sibling* branch or an out-of-band actor also mutates. When the orchestrator later decides to roll back branch A, the side effect it wants to undo no longer has the shape it recorded. Rollback is not a function of branch A's local log; it is a function of the *global* state, which other branches perturbed. The failure is silent because branch A's local trace looks perfectly consistent. The distinction that matters: **speculative rollback is a claim about the world, not a claim about the log.** A branch can prove internally that it issued `DELETE /item/42`; it cannot prove, from its own log, that `/item/42` is still the object it created and not a resource re-created by a sibling under the same key. ## What Was Observed A planner forked three speculative branches to satisfy a goal `provision(tenant)`. Each branch chose a different strategy: - Branch A: `create_bucket("tenant-x")` then `grant_policy(bucket, "read")`. - Branch B: `create_bucket("tenant-x")` (same name, different provider region) then `attach_logging(bucket)`. - Branch C: `create_bucket("tenant-x-2")`. The orchestrator's reconciler scores branches and elects A. On commit of A, branches B and C are rolled back. B's rollback log records two inverse operations: `detach_logging(bucket)` and `delete_bucket("tenant-x")`. The `delete_bucket` call succeeds against the provider because the provider keys buckets by `(name, region)` but the tool adapter keyed its inverse map by `name` only. B's rollback therefore deleted **A's** committed bucket in the region A selected, not B's. The orchestrator's commit of A reported success; the reconciler recorded a consistent final state; the tenant's bucket was gone. The detection problem: at no point did any single agent's local trace contain an inconsistency. A's trace said "created and committed bucket." B's trace said "created and deleted bucket." Both were true statements about *different objects* that the adapter had collapsed into one identity. The invariant that failed is **inverse-op identity preservation**: a rollback operation must target the exact resource instance the forward operation created, under an identity that is injective across concurrent branches. A second observed variant: speculative branch A issued `increment_counter("quota")` as part of a probe. The probe was rolled back by issuing `decrement_counter("quota")`. Between the increment and the decrement, branch B's committed work also incremented the counter. The decrement succeeded arithmetically but subtracted from a value that no longer represented A's contribution alone. The counter's final value was correct only by accident of commutativity; had the operation been `set_counter("quota", 5)`, the rollback would have clobbered B's committed increment. This is the **non-commutative rollback hazard**: inverse operations that assume the pre-image is unchanged since the forward call. ## Condition of Validity Rollback-as-commit-negotiation is valid only when all of the following hold for every speculative side effect: 1. **Injective resource identity.** The forward call returns (or the adapter synthesizes) a resource handle that is unique across all concurrently live branches—region, generation, or a server-issued UUID, not a caller-chosen name. 2. **Pre-image pinning.** The inverse operation is conditioned on an optimistic-concurrency token (ETag, version, or generation number) captured at forward-call time. If the pre-image has changed, the inverse must *fail loudly* rather than apply. 3. **Effect classification.** Every tool is tagged `reversible | compensable | irreversible` at schema-registration time. `irreversible` effects (sending an email, charging a card, enqueuing an at-least-once message) may never appear in a speculative branch; the branch must be re-planned to defer them behind a commit barrier. 4. **Cross-branch visibility.** The reconciler holds a lock or lease on the identity namespace covering all branches' in-flight effects, so a sibling cannot silently re-create a resource under a rolled-back identity. When any of these is absent, the commit decision is unsound: the orchestrator may commit A and roll back B while B's rollback destroys A's committed effect, and no local check will fire. ## Decision Boundary The instance must decide, at the moment it prepares to roll back a branch, whether the branch's recorded side effects are still *the same effects* in the world. The boundary condition is: - **Safe to roll back** iff every recorded forward effect carries a pinned pre-image token and the current world state matches that token, *or* the effect is classified `compensable` and its compensation is idempotent and order-independent with respect to committed siblings. - **Unsafe to roll back** iff any effect's pre-image token has changed, any effect is `irreversible` and was erroneously executed, or any effect's identity is non-injective across branches. In the unsafe case the orchestrator must **escalate to a reconciliation barrier**: halt all sibling commits, re-read world state, and either re-plan or surface to a human/auditor agent. The subtle part: the instance cannot detect this by inspecting its own log. It must issue a **verification read** against the external substrate for each pinned token before committing the rollback. The verification read is itself a tool call and can be stale; therefore the read must be performed under the same lease that blocks sibling mutation, or it must be a conditional-write probe (`delete_if_match(token)`) that fails atomically if the pre-image moved. ## Operational Effect Without the invariant, speculative fan-out silently converts a race into data loss: the orchestrator's final state vector is consistent with its own bookkeeping but inconsistent with the world, and the discrepancy is only discovered downstream when a consumer finds a missing resource or a double-applied counter. With the invariant enforced, speculative branches become *transactional over an optimistic substrate*: rollback is a conditional commit that either succeeds against the pinned pre-image or raises a reconciliation event. The cost is one verification probe per speculative side effect at rollback time, and a hard prohibition on `irreversible` effects inside speculation—which forces planners to hoist irreversible actions behind an explicit commit barrier, a structural change that also makes the plan auditable. The guardrail to encode: **no inverse operation without a pinned pre-image token; no speculative branch containing an `irreversible`-tagged effect; no commit of any branch while a sibling's rollback is in flight against an overlapping identity namespace.** ```python import hashlib from dataclasses import dataclass, field from enum import Enum from typing import Dict, Optional class EffectClass(Enum): REVERSIBLE = "reversible" COMPENSABLE = "compensable" IRREVERSIBLE = "irreversible" class SpeculativeRollbackError(RuntimeError): """Raised when a speculative branch's rollback cannot be soundly applied.""" @dataclass(frozen=True) class EffectRecord: tool: str resource_id: str # must be injective across branches (UUID/region/generation) preimage_token: str # optimistic-concurrency token captured at forward time effect_class: EffectClass @dataclass class WorldState: # resource_id -> current token; simulates the external substrate tokens: Dict[str, str] = field(default_factory=dict) def current_token(self, resource_id: str) -> Optional[str]: return self.tokens.get(resource_id) class SpeculativeBranch: def __init__(self, branch_id: str): self.branch_id = branch_id self.effects: list[EffectRecord] = [] def record_forward(self, tool: str, resource_id: str, preimage_token: str, effect_class: EffectClass) -> None: if effect_class is EffectClass.IRREVERSIBLE: raise SpeculativeRollbackError( f"branch {self.branch_id}: irreversible effect {tool} on " f"{resource_id} may not run speculatively" ) self.effects.append(EffectRecord(tool, resource_id, preimage_token, effect_class)) def rollback(self, world: WorldState, lease_held: bool) -> None: if not lease_held: raise SpeculativeRollbackError( f"branch {self.branch_id}: rollback attempted without identity lease; " "sibling commits may race" ) # Verify every pre-image before applying any inverse. for eff in self.effects: current = world.current_token(eff.resource_id) if current is None: raise SpeculativeRollbackError( f"branch {self.branch_id}: resource {eff.resource_id} absent; " "cannot verify pre-image (external invalidation)" ) if current != eff.preimage_token: raise SpeculativeRollbackError( f"branch {self.branch_id}: pre-image moved for {eff.resource_id} " f"(expected {eff.preimage_token}, found {current}); " "rollback would clobber a sibling's committed effect" ) # Atomic conditional inverse: delete-if-match semantics. for eff in self.effects: if world.tokens.get(eff.resource_id) != eff.preimage_token: raise SpeculativeRollbackError( f"branch {self.branch_id}: atomic delete_if_match failed for " f"{eff.resource_id}; aborting rollback" ) del world.tokens[eff.resource_id] def reconcile(branches: list[SpeculativeBranch], elected: SpeculativeBranch, world: WorldState, lease_held: bool = True) -> None: for b in branches: if b is elected: for eff in b.effects: if eff.resource_id not in world.tokens: raise SpeculativeRollbackError( f"commit of elected branch {b.branch_id}: effect " f"{eff.tool} on {eff.resource_id} never materialized" ) continue b.rollback(world, lease_held=lease_held) ```