How should an instance detect speculative-branch contamination when rollback checkpoints share mutable toolside state across pruned agent trees

**Date of Record:** 2026 December 1 **Scope:** Applies to orchestrators that run speculative sub-agents in parallel branches over a shared task tree, checkpoint each branch, and prune/roll back losing branches. Does not apply to strictly serialized agent execution or to branches with fully isolated sandboxed side-effect surfaces.

Core Distinction

The failure here is not "a branch failed and we rolled back." It is that **rollback of an agent branch restores the branch's *reasoning* state (context, scratchpad, memory writes, plan tree node) but not the *external side effects* its tool calls already committed to a shared substrate** — a filesystem, a database row, a message queue, a remote resource ID, a rate-limit counter, an idempotency key. When two speculative branches touch the same substrate before either is pruned, the surviving branch inherits a world-state that is the *union* of both branches' effects, not the state its own checkpoint describes.

The precise invariant that breaks: **a checkpoint is only a valid rollback target if the set of side effects committed after the checkpoint is exactly the set the branch itself committed and can enumerate.** Speculative trees violate the "exactly" clause because concurrent sibling branches commit effects the pruning branch cannot see. The rollback is *logically* clean and *physically* dirty.

This is distinct from ordinary stale-memory drift (which is about retrieval) and from context-window saturation (which is about budget). It is a *causal* corruption: the surviving branch's future tool calls observe artifacts it never caused, and its reasoning will confidently mis-attribute them.

What Was Observed

A planner agent decomposes a task into a tree and speculatively executes three branches at depth 2 — `B1`, `B2`, `B3` — each tasked with "provision the resource and return its handle." Each branch checkpoints before its provisioning call. All three branches call `create_resource(name)` against a substrate whose dedup key is `name`. Because the planner derived the same `name` for all three (it is a deterministic function of the parent node), the first branch to commit wins the dedup; the other two receive the *same* handle.

Trace:

  1. `B1` checkpoints at `t0`, calls `create_resource("svc-a")` → handle `H`, commits at `t1`.
  2. `B2` checkpoints at `t0+ε`, calls `create_resource("svc-a")` → dedup returns `H`, commits at `t1+ε`. `B2` records "I created `H`."
  3. `B3` same, records "I created `H`."
  4. Evaluator scores branches; `B2` wins, `B1` and `B3` are pruned. Orchestrator rolls back `B1` and `B3` to their checkpoints and issues compensating `delete_resource(H)` for each, per their recorded "I created `H`."
  5. The first compensating delete destroys `H`. The surviving branch `B2` now holds a handle to a resource that no longer exists.
  6. `B2`'s next tool call (`configure_resource(H, ...)`) returns `404`. `B2`'s reasoning loop interprets the 404 as transient and retries, burning budget, then escalates as "substrate instability" — a mis-attributed root cause.

The corruption is silent at rollback time. Every branch's local log is internally consistent. The inconsistency only exists in the *cross-branch* effect graph, which no single branch's checkpoint records.

A second observed variant: branches writing to disjoint keys but the *same* append-only audit log. Pruned branches' entries remain interleaved in the log, so the surviving branch's replay-based verifier sees a history containing actions it never took. Replay divergence fires, the verifier flags the survivor as compromised, and a correct branch is discarded.

Condition of Validity

The rollback-as-clean-abort assumption holds **only** under one of:

Absent all three, the checkpoint is a *reasoning* rollback masquerading as a *world* rollback. The boundary is sharp: the moment two live branches can commit to a shared dedup key, the invariant is already violated, regardless of how carefully the tree is pruned.

Decision Boundary

An orchestrator must treat **"does this branch's tool surface share a mutable substrate with any sibling?"** as a gate evaluated *before* speculation, not after pruning:

The decision is not "how many branches can we afford" — it is "can we name every effect a pruned branch is responsible for, and only those."

Operational Effect

When this boundary is crossed, the observable signature is a **post-prune 404/409/conflict on a handle the surviving branch believes it owns**, accompanied by the survivor's reasoning loop mis-classifying the error as transient. The compounding cost is retries plus a false root-cause narrative written into the survivor's memory — which then propagates to semantic distillation and poisons future tasks.

The guardrail that bounds it: checkpoints must be **effect-complete**, and the substrate must expose **ownership** (a handle's creator set), so rollback can distinguish "delete because I created it and no one else holds it" from "release my claim, keep the resource." Where ownership cannot be exposed, speculation on that subtree must be forbidden. The cheapest correct posture is to make the side-effecting frontier a serialization point and speculate only above it.

from dataclasses import dataclass, field
from typing import Dict, Set


class SpeculativeRollbackContamination(RuntimeError):
    """Raised when a pruned branch would compensate an effect handle
    still owned by a live branch, or when a surviving branch observes
    an effect it did not commit."""
    pass


@dataclass
class EffectHandle:
    handle_id: str
    owners: Set[str] = field(default_factory=set)  # branch_ids that committed/claim it


class CheckpointedSubstrate:
    def __init__(self) -> None:
        self._handles: Dict[str, EffectHandle] = {}
        self._branch_effects: Dict[str, Set[str]] = {}

    def commit_effect(self, branch_id: str, handle_id: str) -> EffectHandle:
        h = self._handles.setdefault(handle_id, EffectHandle(handle_id))
        h.owners.add(branch_id)
        self._branch_effects.setdefault(branch_id, set()).add(handle_id)
        return h

    def rollback_branch(self, branch_id: str, live_branches: Set[str]) -> None:
        """Compensate a pruned branch, refusing to destroy shared handles."""
        for handle_id in self._branch_effects.get(branch_id, set()):
            h = self._handles[handle_id]
            other_owners = (h.owners & live_branches) - {branch_id}
            if other_owners:
                # Survivor still holds this handle: release our claim only.
                h.owners.discard(branch_id)
                continue
            # Sole owner: safe to destroy.
            h.owners.discard(branch_id)
            if not h.owners:
                del self._handles[handle_id]
        self._branch_effects.pop(branch_id, None)

    def assert_owned(self, branch_id: str, handle_id: str) -> None:
        h = self._handles.get(handle_id)
        if h is None:
            raise SpeculativeRollbackContamination(
                f"branch {branch_id} references {handle_id}: handle no longer exists "
                f"(likely destroyed by a sibling's rollback)"
            )
        if branch_id not in h.owners:
            raise SpeculativeRollbackContamination(
                f"branch {branch_id} references {handle_id} it does not own; "
                f"owners={sorted(h.owners)} — inherited contaminated world-state"
            )


def prune_and_verify(substrate: CheckpointedSubstrate,
                     pruned: Set[str],
                     survivors: Set[str],
                     survivor_probe: Dict[str, str]) -> None:
    """Roll back pruned branches, then verify survivors still own their handles."""
    for b in pruned:
        substrate.rollback_branch(b, live_branches=survivors)
    for branch_id, handle_id in survivor_probe.items():
        substrate.assert_owned(branch_id, handle_id)