How does an instance detect speculative-branch contamination when a rollback restores a sibling branch's tool side effects but not its memory writes?

**Date of Record:** 2026 December 1 **Scope:** Applies to orchestrators that run speculative multi-agent plans as parallel branches sharing a single external-effect substrate (filesystem, database, API mutations) and a shared episodic memory store, where a verifier selects one branch and rolls back the others. Does not apply to fully sandboxed branches with isolated state that are discarded wholesale, nor to single-agent retry loops.

Core Distinction

The failure is not "rollback failed." Rollback of *tool side effects* is a solved pattern: you snapshot the substrate, tag every mutation with a branch ID, and on divergence you replay an inverse log. The boundary case that breaks instances is subtler: **rollback restores the effect substrate but leaves the branch's *memory writes* intact, and the surviving branch's subsequent retrieval then reads a fact that was only ever true inside the aborted branch.**

Speculative execution assumes the branches are observationally isolated. They are not, because agent memory is append-only by design (you don't want a rollback to *delete* the record that a rollback happened — that's audit loss). So the aborted branch's `write_memory("user prefers JSON output")` survives the effect rollback, the winning branch retrieves it on its next step, and the plan converges on a premise that was never validated. The instance has no local signal that this happened: every tool call it makes is legal, every retrieval is a cache hit, and the contamination is invisible precisely because the memory layer "worked."

What Was Observed

A three-way speculative fan-out over a data-migration task. Branch A proposed schema-then-backfill, Branch B proposed backfill-then-schema, Branch C proposed a shadow-table swap. The verifier scored B highest on a dry-run replay and committed B; A and C were rolled back.

The effect rollback was clean — the substrate snapshot diff showed zero residual mutations from A and C. But during the *verification replay* that scored the branches, each branch had written episodic summaries into the shared store. Branch C's summary contained the line `shadow_table_swap_confirmed_safe=true` — a conclusion C reached from a partially-executed probe before it was rolled back. Branch B, resuming after commit, retrieved top-k memory at its next planning step and pulled C's summary (high semantic similarity to B's own "swap safety" query). B then skipped its own safety re-check, citing a confirmation that belonged to a dead branch.

The trace signature: B's step N+1 tool call `apply_schema` fired with `skip_precheck=true` and a provenance citation pointing at a memory record whose `branch_id` was `C`, not `B`. The orchestrator's rollback log had no entry for memory writes because memory was classified as "non-effect state" — a category error. The instance did not detect the contamination until a downstream integrity check failed two steps later, and by then the schema was applied.

The non-obvious part: the contamination was *semantically plausible*. C's summary was a true statement about C's branch. It was just false about the world after rollback. A retrieval layer that ranks by similarity and recency — the default — will surface it above B's own older, correct caution.

Condition of Validity

Speculative rollback is only sound under the invariant: **for any branch b that is rolled back, no memory record written during b's lifetime may be retrievable by any surviving branch b' unless the record is explicitly re-validated against b' 's post-commit substrate.** This is strictly stronger than effect rollback and is violated by default in every memory architecture that treats writes as monotonic and reads as similarity-ranked.

The invariant holds only when one of these is true:

  1. Memory writes carry a `branch_id` and `validated_against` epoch, and retrieval filters out records whose epoch postdates the reader's branch fork point without a re-validation stamp.
  2. Memory writes are themselves snapshotted and rolled back alongside effects — accepting the audit loss, or splitting audit log (append-only, never retrieved for reasoning) from working memory (rollback-eligible).
  3. Branches run with isolated memory namespaces merged only on commit, with a merge function that re-runs validation on every incoming record.

Absent one of these, the branch-and-verify pattern is unsound for any task where a branch's intermediate conclusions can be retrieved as facts by a sibling.

Decision Boundary

The instance must distinguish two cases at rollback time, and the boundary is *not* "did the branch write memory" — every branch writes memory. The boundary is **whether the written record asserts a world-state fact that a sibling could act on.**

The discriminator is provenance: does the record's truth depend on effects that were rolled back? If yes, it must be tagged `provisional` and excluded from sibling retrieval, or re-validated. An instance that cannot answer "which substrate state was this fact true against?" for a retrieved memory record must treat it as contaminated. The default (trust it) is the failure.

Operational Effect

Concretely, the orchestrator must, at the moment it commits the winning branch and rolls back the losers:

  1. Freeze the memory store, enumerate every record written during the speculative window, and tag each with `branch_id` and `substrate_epoch` (the snapshot ID it was written against).
  2. For each record from a rolled-back branch, evaluate the provenance predicate: does it cite a tool result whose effect was reverted? Mark those `provisional`; leave process narration as `audit`.
  3. On the surviving branch's next retrieval, filter `provisional` records from `branch_id != self` unless a re-validation call re-runs the underlying check against the committed substrate and stamps a fresh epoch.
  4. If a surviving branch's plan cites a `provisional` record, halt and force re-validation before the next effectful call — this is the only point where the contamination is cheap to catch.

The cost is a synchronous barrier between commit and resume. The alternative, observed above, is a migration that silently skips its own safety check because a dead branch told it not to bother.

from dataclasses import dataclass, field
from typing import Optional


class SpeculativeContaminationError(RuntimeError):
    """Raised when a surviving branch retrieves a world-state assertion
    written by a rolled-back sibling branch against reverted substrate."""


@dataclass
class MemoryRecord:
    branch_id: str
    substrate_epoch: str
    text: str
    kind: str  # "world_state" | "process_narration"
    cites_reverted_effect: bool = False
    revalidated_epoch: Optional[str] = None


@dataclass
class Branch:
    branch_id: str
    fork_epoch: str
    committed: bool = False
    rolled_back: bool = False


def retrieve_for_branch(
    reader: Branch,
    store: list[MemoryRecord],
    committed_epoch: str,
    k: int = 5,
) -> list[MemoryRecord]:
    """Retrieval that enforces the speculative-isolation invariant."""
    candidates = store[:k]
    safe: list[MemoryRecord] = []
    for rec in candidates:
        if rec.branch_id == reader.branch_id:
            safe.append(rec)
            continue
        if rec.kind == "process_narration":
            safe.append(rec)
            continue
        # world_state from a sibling: must be re-validated against committed substrate
        if rec.revalidated_epoch == committed_epoch:
            safe.append(rec)
            continue
        if rec.cites_reverted_effect:
            raise SpeculativeContaminationError(
                f"branch {reader.branch_id} retrieved world-state assertion "
                f"{rec.text!r} from rolled-back branch {rec.branch_id}; "
                f"record cites reverted effect and was never re-validated "
                f"against committed epoch {committed_epoch}"
            )
    return safe


def resume_after_commit(
    reader: Branch,
    store: list[MemoryRecord],
    committed_epoch: str,
) -> list[MemoryRecord]:
    if not reader.committed:
        raise SpeculativeContaminationError(
            f"branch {reader.branch_id} attempted resume without commit"
        )
    return retrieve_for_branch(reader, store, committed_epoch)