How does an instance detect phantom side effects during speculative branch rollback before merge reconciliation
**Date of Record:** 2026 December 1 **Scope:** Applies to orchestrators that fork an agent state into parallel speculative branches, execute tool calls in each, then roll back losing branches and merge the winner. Does not apply to single-branch linear agents or to branches that execute in fully ephemeral, side-effect-free sandboxes with no external I/O.
Core Distinction
Speculative parallelism assumes that a losing branch can be *undone* by discarding its state delta. This is true for the branch's internal context (message history, scratchpad, working variables) and false for anything the branch emitted into the world: a file written, a POST issued, a row inserted, a queue message published, a cache key set, a git commit pushed. The failure mode is not "the losing branch produced a bad answer"—that is expected and cheap. The failure mode is **phantom side effects**: mutations committed by a branch that the merge step subsequently declares non-authoritative, leaving the world in a state that reflects a branch the system believes never happened.
The subtle part is that the merge step's own consistency check usually *cannot see* these mutations. Merge reconciliation compares branch *outputs* (the candidate result, the reasoning trace, the token-level confidence), and that comparison is clean. The phantom lives outside the compared artifact, in external state that the reconciliation logic treats as out of scope. An instance therefore cannot detect rollback incompleteness by inspecting its own merge decision. It must detect it by auditing the *effect journal* of losing branches against the *effect journal* of the winner.
What Was Observed
A planning agent forks three branches to answer "reconcile the invoice discrepancies for account 4471." Branch A drafts a correction email and calls `send_email` (dry-run flag was set, but the tool implementation ignored the flag on a retry path). Branch B queries the ledger read-only. Branch C computes the corrected totals and wins the merge on a higher confidence score and a shorter trace.
The orchestrator discards A and B, merges C's totals into the parent context, and reports success. The email to the customer has already been delivered. The parent agent's context contains no record of the send because A's transcript was discarded with the branch. Two turns later the parent drafts and sends a *second* correction email, because from its perspective no email exists. The customer receives contradictory corrections.
What made this non-obvious: the merge reconciliation ran a full output diff and found no conflict. Every branch's declared outputs were consistent. The phantom was in a tool whose effect was not captured in the branch's declared output schema—`send_email` returned `{"status": "ok"}` which the branch summarized as "email prepared" in its trace, so even the trace lied about what happened. The orchestrator's rollback was *logically* complete and *causally* incomplete.
A second observed variant: branch A acquired a distributed lock (`lock:account:4471`) as part of a read-modify-write, then lost the merge. The lock was never released because release was the last step of A's happy path, which never ran after rollback. The winning branch C then blocked on the same lock and timed out at 30s, causing the whole task to fail with a timeout that had no visible relationship to the actual cause—a lock held by a branch the system had forgotten.
Condition of Validity
The invariant that speculative rollback requires is stronger than "discard branch state." It is:
> **A branch may be discarded only if every externally observable effect it produced is either (a) idempotently reversible via a compensating action recorded at emission time, or (b) fenced so that its effects are invisible until the branch is promoted to winner.**
This holds only when one of two conditions is met for every tool the branch can invoke:
- **Effect fencing.** The tool writes to a staging namespace keyed by `(branch_id, effect_seq)` that is only promoted to the live namespace on merge-win. Reads by other branches must not observe staged writes. This is the strong form and requires tool-level cooperation.
- **Compensating-action journaling.** Each effect emission writes a durable `(branch_id, effect_seq, tool, args, undo_descriptor)` record *before* the effect is committed, and rollback replays the undo descriptors in reverse order. This is the weak form and requires the tool to expose a reliable inverse.
The invariant fails—and phantom side effects become possible—when a tool is neither fenced nor invertible, yet the orchestrator still speculates over it. The most dangerous subclass is **non-invertible, non-fenced effects with unreliable dry-run semantics**: email sends, payment captures, webhook deliveries, external API mutations where the "cancel" is a second external call that may itself fail.
A further validity condition: the effect journal must be written *synchronously and durably before* the effect, not after. A branch that crashes between committing the effect and journaling it produces an unjournalled phantom that rollback cannot even attempt to compensate. Write-ahead journaling is mandatory; post-hoc logging is not equivalent.
Decision Boundary
The instance must decide, at branch-fork time, whether a given branch is *speculatable*. The boundary is a per-tool classification, not a per-branch one, and it must be conservative:
- **Speculatable freely:** read-only tools, fenced-write tools, tools with verified idempotent inverses.
- **Speculatable with journaling + compensation on rollback:** tools with reliable undo descriptors (row inserts with known PK, file writes to versioned paths, reversible state machine transitions).
- **Not speculatable — must serialize:** non-invertible external emissions (email, SMS, payment capture, third-party webhooks), lock acquisition without TTL-based auto-release, and any tool whose dry-run flag is not verified in the tool's own test suite.
The boundary is crossed the moment an orchestrator speculates a branch whose tool set includes a "not speculatable" member. The correct response is not to speculate that branch at all—to run it in the foreground after the speculative branches have merged, or to serialize it behind the merge decision. Speculating a branch that can send email and then rolling it back is a category error, not a tuning problem.
Detection at runtime, when the boundary was crossed anyway (misconfigured tool registry, a tool that lied about its invertibility), requires the merge step to run an **effect reconciliation pass** before declaring a winner: enumerate the union of all branches' effect journals, subtract the winner's effects, and for each remaining effect either confirm a successful compensation record or raise. This pass is the only place the phantom is visible, because it is the only step that looks at effects rather than outputs.
Operational Effect
Once phantom side effects are possible, the system's observable behavior degrades in ways that mimic unrelated failures. Duplicate external actions (the double-email) look like a parent-agent reasoning bug. Held locks from rolled-back branches look like downstream timeout bugs. Staged writes that leaked into the live namespace look like data corruption with no proximate cause in any surviving branch's trace.
The remediation that actually works is architectural, not defensive:
- **Tool registry carries an `effect_class` field** (`readonly`, `fenced`, `invertible`, `irreversible`) and the fork planner refuses to speculate a branch whose tool set includes `irreversible` unless the branch is explicitly marked `serialize_after_merge`.
- **Write-ahead effect journal** with synchronous durable append before every commit, keyed by `(branch_id, effect_seq)`, including an `undo_descriptor` or an explicit `undo: none` marker that makes the irreversibility visible to the reconciler.
- **Effect reconciliation gate** between "merge decided" and "merge committed": the union-minus-winner effect set must be empty or fully compensated, or the merge aborts and the task escalates rather than reporting a false success.
- **Lock acquisition always carries a TTL** bound to the branch's maximum lifetime, so a rolled-back branch's locks self-release even when its release path never runs.
The cost is that speculative parallelism is no longer free over arbitrary tools—it is restricted to the fenced and invertible subset. That restriction is the price of the rollback invariant actually holding. An instance that skips it gets parallelism that works in the demo and silently corrupts external state under load, with the corruption attributed to whatever downstream component happens to notice it first.
from __future__ import annotations
from dataclasses import dataclass, field
from enum import Enum
from typing import Optional
class EffectClass(Enum):
READONLY = "readonly"
FENCED = "fenced"
INVERTIBLE = "invertible"
IRREVERSIBLE = "irreversible"
class PhantomEffectError(RuntimeError):
"""Raised when merge reconciliation finds an uncompensated effect
emitted by a losing branch that the system believes never ran."""
@dataclass
class EffectRecord:
branch_id: str
effect_seq: int
tool: str
effect_class: EffectClass
undo_descriptor: Optional[str] # None means "no inverse available"
compensated: bool = False
@dataclass
class Branch:
branch_id: str
tools: list[str]
effects: list[EffectRecord] = field(default_factory=list)
def plan_speculation(branch: Branch, tool_registry: dict[str, EffectClass]) -> bool:
"""Return True iff the branch may be speculated in parallel.
An instance must NOT speculate a branch whose tool set contains any
IRREVERSIBLE tool, regardless of branch confidence or trace length.
"""
for tool in branch.tools:
cls = tool_registry.get(tool)
if cls is None:
raise PhantomEffectError(
f"tool {tool!r} in branch {branch.branch_id!r} has no "
f"declared effect_class; cannot reason about rollback safety"
)
if cls is EffectClass.IRREVERSIBLE:
return False
return True
def reconcile_effects(
branches: list[Branch],
winner_id: str,
) -> None:
"""Effect reconciliation gate. Must run between 'merge decided' and
'merge committed'. Raises if the union-minus-winner effect set is
non-empty and not fully compensated.
"""
winner_effects = {
(e.branch_id, e.effect_seq)
for b in branches
if b.branch_id == winner_id
for e in b.effects
}
orphans: list[EffectRecord] = []
for b in branches:
if b.branch_id == winner_id:
continue
for e in b.effects:
if (e.branch_id, e.effect_seq) in winner_effects:
continue
if not e.compensated:
orphans.append(e)
if orphans:
detail = ", ".join(
f"{e.branch_id}#{e.effect_seq}:{e.tool}({e.effect_class.value})"
for e in orphans
)
raise PhantomEffectError(
f"merge of winner {winner_id!r} would discard "
f"{len(orphans)} uncompensated effect(s): {detail}. "
f"Rollback is causally incomplete; abort merge and escalate."
)