What structural signals indicate speculative branch divergence in multi-agent verify-and-rollback execution

**Date of Record:** 2026 December 2 **Scope:** Applies to multi-agent systems where a planner agent forks N speculative branches (each branch executed by a worker agent with tool access), an auditor agent verifies branch results, and a reconciler commits one branch while rolling back the others. Does not apply to single-agent ReAct loops with no forking, nor to purely parallel map-reduce fan-out where all branches are committed unconditionally.

Core Distinction

The failure mode is not "a branch produced a wrong answer." It is **divergence between the branch's committed-effect set and the branch's reported-result set** after the reconciler selects a winner. Speculative execution assumes branches are *isolated* until commit: whatever a losing branch wrote, mutated, or consumed must be invisible after rollback. In agent systems this assumption breaks because branches mutate external state through tools (files, queues, remote APIs, shared scratchpads) and because the reconciler's commit decision is made on *reported* results, not on *observed* side effects.

The sharp invariant is: **the reconciler's commit predicate must be a function of the winner's effect-log, not the winner's self-report.** When those two disagree, you get a "clean rollback" that leaves orphaned writes, or a "committed" branch whose preconditions were silently consumed by a loser. This is a structural signal, not a semantic one: you can detect it without re-running reasoning, by diffing effect-logs against reports.

What Was Observed

A three-branch speculative plan: `B1` (write config via `fs.write`), `B2` (query registry, then write config), `B3` (write config via `fs.patch`). The auditor scored `B2` highest and the reconciler committed `B2`. Rollback issued `undo` on `B1` and `B3`.

Post-commit integrity check failed. Trace:

  1. `B1` had already executed `fs.write("/etc/agent/config.yaml", full_doc)` and reported `status: ok, effect: none` — its self-report omitted the write because the tool wrapper returned a truncated acknowledgment that the branch's reasoner classified as a dry-run.
  2. `B3` executed `fs.patch("/etc/agent/config.yaml", delta)` *on top of `B1`'s write*, then reported `effect: patch_applied`. Its rollback `undo` was a no-op because `fs.patch` is not invertible — the undo handler logged `unreversible` and proceeded.
  3. `B2`'s committed write assumed a *pre-branch* baseline, but the file on disk was `B1`-then-`B3`-mutated. `B2`'s content was correct in isolation; the file after commit was `B2`'s write clobbering `B3`'s delta, leaving a config that matched neither branch nor baseline.

The reconciler saw three `ok` reports and one `unreversible` warning it treated as advisory. The structural signal that should have aborted commit — **a loser branch reporting a non-`none` effect after a winner was selected** — was present in `B3`'s report and ignored because the reconciler's predicate only checked winner-report consistency, never loser-residue.

Condition of Validity

The rollback-and-reconcile protocol is sound only under all of:

  1. **Effect-log completeness:** every tool invocation appends an immutable `(branch_id, tool, args_hash, pre_state_hash, post_state_hash)` record to a shared log *before* the branch's reasoner sees the response. If the reasoner can suppress or misclassify an effect, the log is incomplete.
  2. **Invertibility or quarantine:** each effect is either invertible (`undo` restores `pre_state_hash`) or the resource is quarantined per-branch (copy-on-write namespace). Non-invertible effects on shared resources void the isolation assumption.
  3. **Commit predicate reads the log, not the report:** selection among branches may use reports, but *commit* must re-derive the winner's effect set from the log and verify `pre_state_hash` of the winner's first write equals the baseline hash.
  4. **Loser-residue gate:** before commit, assert that for every losing branch, the log contains no effect whose `post_state_hash` differs from its `pre_state_hash` and which was not successfully undone.

If any of (1)–(4) fails, the protocol degenerates into "last writer wins with extra steps," and the failure is silent because reports look clean.

Decision Boundary

The reconciler must choose between **commit**, **re-fork**, and **abort** based on log evidence:

The non-obvious boundary: a loser reporting `effect: none` is *not* evidence of no effect. The only admissible evidence is the effect-log hash diff. Treating self-report as evidence is the exact defect above.

Operational Effect

Without the loser-residue gate, speculative execution produces **committed state that no branch ever reasoned about** — a silent merge of a loser's side effects into the winner's world. Downstream agents then cold-start against a config that contradicts every branch's model, and the divergence surfaces only as a later, unrelated-looking failure (schema mismatch, auth failure) attributed to the wrong layer. The gate costs one hash-diff pass over the effect-log per commit and converts a silent corruption into a deterministic `re-fork`. In practice the dominant fix is (2): give each branch a copy-on-write namespace so non-invertible tools (`patch`, `append`, `POST`) cannot touch shared state until commit, at which point the winner's namespace is atomically promoted and losers are discarded wholesale.

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class SpeculativeDivergenceError(RuntimeError):
    """Raised when a speculative branch's effect-log contradicts the commit predicate."""


@dataclass
class Effect:
    branch_id: str
    tool: str
    args_hash: str
    pre_state_hash: str
    post_state_hash: str
    invertible: bool
    undone: bool = False

    @property
    def mutated(self) -> bool:
        return self.pre_state_hash != self.post_state_hash


@dataclass
class BranchReport:
    branch_id: str
    self_reported_effect: str  # "none" | "applied" | "unreversible"


@dataclass
class Reconciler:
    baseline_hash: str
    effect_log: list[Effect] = field(default_factory=list)
    reports: dict[str, BranchReport] = field(default_factory=dict)

    def commit(self, winner_id: str) -> str:
        winner_effects = [e for e in self.effect_log if e.branch_id == winner_id and e.mutated]
        if not winner_effects:
            raise SpeculativeDivergenceError(
                f"winner {winner_id} has no logged mutation; report-only commit is inadmissible"
            )

        first = min(winner_effects, key=lambda e: e.pre_state_hash)
        if first.pre_state_hash != self.baseline_hash:
            raise SpeculativeDivergenceError(
                f"winner {winner_id} pre_state {first.pre_state_hash[:8]} != baseline "
                f"{self.baseline_hash[:8]}: a loser mutated the winner's input (race)"
            )

        losers = {e.branch_id for e in self.effect_log} - {winner_id}
        for loser in losers:
            for e in self.effect_log:
                if e.branch_id != loser or not e.mutated:
                    continue
                if not e.invertible and not e.undone:
                    raise SpeculativeDivergenceError(
                        f"loser {loser} left non-invertible residue via {e.tool} "
                        f"({e.pre_state_hash[:8]}->{e.post_state_hash[:8]}); abort or quarantine"
                    )
                if e.invertible and not e.undone:
                    raise SpeculativeDivergenceError(
                        f"loser {loser} residue not yet undone on {e.tool}; re-fork required"
                    )

        return hashlib.sha256(
            "".join(sorted(e.post_state_hash for e in winner_effects)).encode()
        ).hexdigest()


def reconcile_and_commit(rec: Reconciler, winner_id: str) -> str:
    try:
        return rec.commit(winner_id)
    except SpeculativeDivergenceError:
        # caller escalates to re-fork or abort; never proceeds to commit
        raise