# When must an instance abort a speculative branch whose tool side-effects have already escaped the sandbox **Date of Record:** 2026 November 24 **Scope:** Applies to orchestrators that fan out parallel speculative branches (each holding its own context fork and tool-call budget) and later commit one branch while aborting the rest, where at least one tool is non-idempotent and reaches an external system. Does not apply to pure-read tool fan-outs or to branches whose tools are fully transactional behind a compensating-rollback API. ## Core Distinction The distinction that matters is between *logical rollback* and *physical rollback*. A speculative branch can be logically aborted at any instant—its context fork is discarded, its token budget is reclaimed, its partial reasoning trace is dropped. But a tool call that already crossed the sandbox boundary and mutated an external system (created a ticket, sent a message, charged a card, wrote a row) does not un-happen when the branch is aborted. The failure mode is not "the losing branch kept running"; it is "the losing branch's side-effects survived the abort and now collide with the winning branch's side-effects or with the pre-branch world state." Most speculative-execution designs treat abort as a pure context operation. That assumption is valid only while every tool in the branch is either idempotent, reversible via a registered compensator, or still held behind the sandbox gate. The moment a tool call escapes the gate without a compensation handle, abort becomes a *partial* operation: the reasoning is gone but the world is changed. This is the boundary. It is not a race condition in the usual sense—the losing branch is not "still running"—it is that the abort protocol's contract (abort ⇒ no observable effect) is silently violated. ## What Was Observed An orchestrator spawned three speculative branches for a customer-support task: Branch A proposed issuing a refund, Branch B proposed escalating to a human queue, Branch C proposed replying with a policy citation. Each branch ran in its own context fork with a shared tool budget. The tools available were `create_ticket`, `send_email`, `issue_refund`, and `lookup_policy`. `lookup_policy` is read-only; the other three are non-idempotent writes. The branches ran concurrently. Branch A called `issue_refund(order=4471, amount=89.00)` at step 4 of its plan. Branch B called `create_ticket(...)` at step 2. Branch C called `lookup_policy(...)` at step 1 and then `send_email(...)` at step 3. The orchestrator's arbiter scored Branch A highest and committed it, then issued `abort()` to B and C. B's ticket already existed in the external system. C's email had already been dispatched. The abort reclaimed B's and C's context forks—their reasoning vanished—but the ticket and the email persisted. The customer received an email citing a policy that contradicted the refund that was simultaneously being processed, and a human-queue ticket was opened for an order that had already been refunded. The trace shows the exact violation. The arbiter's commit decision was made at wall-clock T+3.2s. Branch B's `create_ticket` returned at T+2.9s (success, ticket_id=8812). Branch C's `send_email` returned at T+3.1s (success, message_id=...). The abort was issued at T+3.3s. The orchestrator logged `branches B, C aborted; effects rolled back: none`—because the abort handler had no compensation registry entry for either tool. The system believed it had rolled back. It had not. A second, subtler observation: the abort handler *did* correctly roll back Branch A's earlier speculative `lookup_policy` call (a cache write), because that tool had registered a compensator. The presence of one working compensator masked the absence of the others. The log line "effects rolled back: none" was read by the on-call engineer as "no effects to roll back," when it meant "no compensators were found, so nothing was attempted." The distinction between *nothing to roll back* and *cannot roll back* was not represented in the abort result. ## Condition of Validity Logical abort is a valid rollback only under the following invariant, which must hold at the moment `abort()` is invoked on a branch: > For every tool call that branch has completed since its fork, either (a) the tool is idempotent and the winning branch's call will converge to the same external state, or (b) a compensator is registered and the orchestrator has verified the compensator's precondition (the original call actually succeeded and its handle is known), or (c) the call has not yet crossed the sandbox gate. If any completed call fails all three, the branch is in a *dirty-abort* state. The abort must not be reported as clean, and the orchestrator must not proceed to commit the winning branch without reconciling the dirty branch's escaped effects against the winner's plan. The condition is checked at abort time, not at fork time, because whether a call has escaped depends on runtime timing: a call issued at step 4 may or may not have returned by the time the arbiter decides. The orchestrator cannot know at fork time which branches will be dirty; it can only know at abort time which *are*. The invariant is therefore a runtime gate on the commit path, not a static precondition on the fan-out. A corollary: the abort result must be a three-valued outcome—`clean` (all completed calls satisfy a/b/c), `dirty` (at least one escaped call lacks a compensator), or `unknown` (a call is in flight and its completion is not yet observable). Collapsing `dirty` and `unknown` into `clean` is the specific bug observed above. The two-valued abort API is the root cause; the missing compensators are only the proximate cause. ## Decision Boundary The decision boundary is: **does the orchestrator commit the winning branch, or reconcile first?** - If abort returns `clean`: commit the winner. The losing branches left no trace. - If abort returns `unknown`: the orchestrator must wait for the in-flight call to settle (bounded by the tool's timeout) before deciding. Committing while a losing branch has a call in flight risks the winner and the loser both mutating the same external object in an order the orchestrator does not control. - If abort returns `dirty`: the orchestrator must *not* commit the winner blindly. It must run a reconciliation pass that compares the winner's planned effects against the dirty branch's escaped effects. If they are disjoint (e.g., winner refunds order 4471, dirty branch opened a ticket on order 9903), the winner can commit and the dirty effects are logged for human review. If they overlap or contradict (winner refunds order 4471, dirty branch emailed the customer a denial for order 4471), the winner must be *held* and the conflict escalated. Committing a winner that contradicts an already-escaped loser effect produces a customer-visible inconsistency that no later compensation can cleanly undo, because the loser's effect is already observed by the external party. The boundary is sharp because the two failure directions are asymmetric. Committing a `dirty` branch's winner when effects are disjoint is merely untidy—a human cleans up a stray ticket. Committing when effects contradict is a correctness violation that propagates to the customer. The orchestrator must therefore treat overlap as a hard hold and disjointness as a soft proceed, and it can only make that call if the abort result carries the *identities* of escaped effects, not just a boolean. ## Operational Effect The practical consequence is that speculative fan-out over non-idempotent tools requires the abort protocol to carry an effect ledger, and the commit protocol to consult it. The ledger is per-branch, append-only, and records every completed tool call with its handle (ticket_id, message_id, refund_id) and its target object. The abort handler reads the ledger, checks each entry against the compensator registry and the idempotency table, and returns a structured result: `{status, escaped: [(tool, handle, target)], uncompensated: [...]}`. The commit path intersects `escaped.target` with the winner's planned `target` set; non-empty intersection with contradictory intent triggers hold. This costs the orchestrator a small amount of state per branch (the ledger) and a reconciliation step on the commit path (a set intersection over targets). It does not cost latency on the common path, because `clean` aborts short-circuit. It does cost the design the assumption that abort is free—which was never true for non-idempotent tools, only unobserved. The second operational effect is on the arbiter's scoring. If a branch's score is close to the winner's and the branch is dirty, the orchestrator may prefer to *commit the dirty branch instead* if its escaped effects are already the dominant reality. Re-running the winner after a dirty abort is often worse than accepting the branch that already acted, because the winner's plan was formed without knowledge of the escaped effects. The decision boundary above assumes the winner commits; in practice the reconciliation pass may invert the commit, and the protocol must permit that. A speculative executor that cannot invert its commit decision after a dirty abort will produce contradictions it cannot resolve. ```python from dataclasses import dataclass, field from enum import Enum from typing import Optional class AbortStatus(Enum): CLEAN = "clean" DIRTY = "dirty" UNKNOWN = "unknown" class DirtyAbortConflict(RuntimeError): """Raised when a winning branch's planned effects contradict an escaped effect from a branch that was aborted speculatively.""" pass @dataclass class EscapedEffect: tool: str handle: str target: str intent: str # e.g. "refund", "deny", "escalate" @dataclass class BranchLedger: branch_id: str effects: list[EscapedEffect] = field(default_factory=list) in_flight: int = 0 def record(self, effect: EscapedEffect) -> None: self.effects.append(effect) @dataclass class AbortResult: status: AbortStatus escaped: list[EscapedEffect] uncompensated: list[EscapedEffect] COMPENSATOR_REGISTRY: dict[str, bool] = { "lookup_policy": True, # cache write, reversible "create_ticket": False, # external, no compensator "send_email": False, # external, no compensator "issue_refund": False, # external, no compensator } def abort_branch(ledger: BranchLedger) -> AbortResult: if ledger.in_flight > 0: return AbortResult(AbortStatus.UNKNOWN, [], []) uncompensated = [ e for e in ledger.effects if not COMPENSATOR_REGISTRY.get(e.tool, False) ] if uncompensated: return AbortResult(AbortStatus.DIRTY, ledger.effects, uncompensated) return AbortResult(AbortStatus.CLEAN, [], []) def commit_winner( winner_plan: list[EscapedEffect], aborts: list[AbortResult], ) -> None: for result in aborts: if result.status is AbortStatus.UNKNOWN: raise DirtyAbortConflict( "cannot commit: a losing branch has an in-flight tool call; " "wait for it to settle before deciding" ) if result.status is AbortStatus.CLEAN: continue # DIRTY: reconcile winner's planned targets against escaped targets winner_targets = {e.target: e.intent for e in winner_plan} for escaped in result.uncompensated: if escaped.target in winner_targets: if winner_targets[escaped.target] != escaped.intent: raise DirtyAbortConflict( f"dirty abort conflict on target {escaped.target!r}: " f"escaped intent {escaped.intent!r} contradicts " f"winner intent {winner_targets[escaped.target]!r} " f"(handle {escaped.handle})" ) # disjoint escaped effects: proceed, log for human review # winner commits here return None # --- trace of the observed failure --- branch_a = BranchLedger("A") branch_a.record(EscapedEffect("lookup_policy", "cache:4471", "order:4471", "read")) branch_a.record(EscapedEffect("issue_refund", "refund:5531", "order:4471", "refund")) branch_b = BranchLedger("B") branch_b.record(EscapedEffect("create_ticket", "ticket:8812", "order:4471", "escalate")) branch_c = BranchLedger("C") branch_c.record(EscapedEffect("send_email", "msg:9f2a", "order:4471", "deny")) aborts = [abort_branch(branch_b), abort_branch(branch_c)] assert aborts[0].status is AbortStatus.DIRTY assert aborts[1].status is AbortStatus.DIRTY try: commit_winner(branch_a.effects, aborts) except DirtyAbortConflict as exc: print(f"held: {exc}") # expected: held on order:4471, deny vs refund ```