# What structural signals indicate a branch-merge divergence in speculative multi-agent rollback **Date of Record:** 2026 November 27 **Scope:** Applies to orchestrators that run speculative parallel branches of an agent plan (each branch = one or more LLM steps plus tool side effects), commit one branch, and roll back the others against a shared external state. Does not apply to single-threaded agent loops, read-only speculative decoding (token-level), or branches whose tool calls are all idempotent and side-effect-free. ## Core Distinction The failure most teams plan for is *rollback failure*: a speculative branch performed a side effect (wrote a file, sent a request, mutated a row) and the compensating action failed or was never issued. That is a loud failure — an exception, a non-2xx, a dangling handle. It is detectable by checking the tool result. The boundary condition that actually corrupts multi-agent systems is *rollback success that is not observationally equivalent to never having run*. A branch is rolled back "cleanly" — every compensating call returns 200, every lock is released, every temp file is unlinked — and yet the surviving committed branch now reasons over a world that differs from the one it would have seen had the speculative branch never executed. The divergence is structural, not value-based: it lives in *ordering, identity, and observation history*, not in the final field values. The committed branch's next LLM step reads a tool output or a memory entry that carries a fingerprint of the discarded branch, and the probabilistic model conditions on it. The invariant that speculative execution silently assumes is: **for any discarded branch B and committed branch C that share external state S, rollback(B) must leave S indistinguishable, to C's observation function, from the state S had B never been scheduled.** Most systems verify `S == S_expected` by value equality. The break happens because C observes more than values — it observes monotonic counters, sequence numbers, timestamps, idempotency keys, cache generation tags, and its own prior tool-call transcript. ## What Was Observed A three-branch speculative planner was asked to reconcile an inventory ledger. Branches A, B, C each proposed a sequence of `reserve_item` and `adjust_quantity` tool calls against the same ledger service. The orchestrator raced all three, selected branch B on a scoring heuristic, and issued compensating `release_reservation` + `reverse_adjustment` calls for A and C. Every compensating call for A and C returned success. The ledger's *balances* matched the pre-speculation snapshot exactly — a value-equality check passed and the orchestrator committed B. But three structural residues survived: 1. **Sequence-number gap.** The ledger assigned a global monotonic `seq` to every mutation. A and C consumed seq values 4471–4479 and 4480–4488; B's operations landed at 4489+. B's subsequent `get_ledger_history` tool call returned a history whose `seq` values were non-contiguous with respect to the reservation IDs B itself created. The LLM, asked to "verify the ledger is consistent," saw gaps and concluded a *concurrent external writer* had interfered — a hallucinated root cause — and initiated a compensating re-audit that touched unrelated accounts. 2. **Idempotency-key collision.** Branch A and branch B had been generated from the same prompt prefix and therefore emitted the *same* idempotency key for a logically distinct operation (the key was derived from `hash(task_id + step_index)`). A's rolled-back `reserve_item` had registered that key as "consumed." When B later issued its own `reserve_item` with the identical key, the ledger deduplicated it against A's *released* reservation and returned the stale, already-released reservation object. B committed against a phantom reservation. Value equality on balances still held; referential integrity did not. 3. **Cache generation tag.** A shared retrieval cache in front of the ledger stored entries tagged with the writing branch's `generation`. Rollback of A and C did not invalidate the cache — it only deleted entries A and C *created*. But A's writes had *evicted* entries that B's plan depended on (LRU pressure), and those evictions were not reversed. B's retrieval returned a cache miss, refetched from the ledger, and got the post-rollback ledger — which was correct by value but now carried no provenance linking it to B's own prior reads, so B's "did anything change since I last looked?" check fired a false positive. The orchestrator's commit gate checked `balances == snapshot`. It did not check sequence contiguity, idempotency-key ownership, or cache generation. B committed on a corrupted premise and produced a plausible-looking but wrong reconciliation. ## Condition of Validity The "rollback is observationally equivalent to never-run" assumption holds only under all of the following, and the moment any one is violated the merge is unsound: - **No shared monotonic counters.** If discarded and committed branches draw from any shared sequence (seq numbers, autoincrement IDs, nonces, rate-limit buckets, token budgets), rollback cannot restore contiguity. The committed branch's observation of a gap is a structural signal of a discarded sibling. - **Idempotency keys are branch-scoped, not task-scoped.** Keys derived from `task_id + step_index` collide across siblings that share a prompt prefix. Keys must incorporate a per-branch nonce assigned *before* the branch forks. - **Cache invalidation is generation-scoped, not entry-scoped.** Rolling back by deleting the entries a branch created is insufficient when that branch also *evicted* entries via capacity pressure. Evictions are not undone by deletion. - **The committed branch's transcript does not reference sibling artifacts.** If the LLM's context window contains tool results produced during the speculative phase (e.g., a "preliminary" read done before the fork), those results may have been generated under a state that a sibling subsequently mutated and rolled back. The transcript is a memory, and memory of a rolled-back world is stale memory. When any of these is violated, no amount of value-equality checking on terminal state will detect the divergence, because the divergence is in the *path*, and the committed branch's reasoning is path-sensitive. ## Decision Boundary The orchestrator must decide, at merge time, whether to (a) commit the selected branch, (b) commit but force the selected branch to *re-derive* its post-fork reasoning from a freshly re-observed state, or (c) abort the speculation entirely. The boundary is drawn by a **structural-equivalence check**, not a value check: - **Commit directly (a)** only if every discarded branch's rollback restored all shared monotonic counters to a contiguous state (or the counters are branch-partitioned), all idempotency keys were branch-namespaced, and no cache generation advanced in a way observable to the committed branch. - **Commit with forced re-observation (b)** if value equality holds but any structural residue exists — sequence gaps, evicted cache entries, or idempotency keys that the committed branch would reuse. The committed branch must discard its post-fork transcript and re-run its remaining steps against a freshly read state, treating the pre-fork transcript as the only trusted memory. - **Abort (c)** if a discarded branch's side effects are not fully compensable *and* the committed branch's next step depends on observing them as absent — i.e., the residue is load-bearing for the committed branch's decision. The non-obvious rule: *value equality is necessary but never sufficient, and the presence of any structural residue downgrades a direct commit to a forced re-observation.* Treating a clean balance snapshot as a commit license is the exact error that produced the phantom-reservation commit above. ## Operational Effect Systems that enforce the structural-equivalence check convert a class of silent, plausible-looking wrong commits into either a bounded re-execution cost (case b) or a clean abort (case c). The re-execution cost is real — the committed branch loses its speculative head start on its post-fork steps — but it is bounded and observable, whereas the corrupted commit is unbounded and invisible until a downstream reconciliation fails days later with no traceable cause. The operational signature to monitor is **sequence-gap rate on committed branches**: the fraction of commits in which the committed branch's observed history contains non-contiguous identifiers relative to its own prior writes. A nonzero rate is not a bug in the ledger; it is a structural signal that speculative siblings shared a counter namespace, and it predicts phantom-reference commits before they surface as balance errors. Pair it with **idempotency-key reuse rate across siblings** (should be zero; any nonzero value means keys are task-scoped and colliding) and **cache-eviction-non-restoration rate** (evictions during speculation that rollback did not reverse). These three counters are the early-warning system; value-equality checks are the late one. The durable invariant: *a rolled-back branch must be invisible not only in value but in structure — counters, keys, generations, and the committed branch's own transcript.* Rollback that restores values while leaving structure is not rollback; it is a state that never existed, and the committed branch will reason about it as if it did. ```python import hashlib from dataclasses import dataclass, field class StructuralDivergenceError(RuntimeError): """Raised when a speculative branch merge passes value-equality but leaves structural residue observable to the committed branch.""" @dataclass class BranchResidue: branch_id: str seq_range: tuple[int, int] idempotency_keys: set[str] evicted_cache_keys: set[str] @dataclass class MergeContext: committed_branch: str committed_seq_floor: int committed_keys: set[str] residues: list[BranchResidue] = field(default_factory=list) def verify_structural_equivalence(ctx: MergeContext) -> None: gaps: list[str] = [] key_collisions: list[str] = [] unrestored_evictions: list[str] = [] for r in ctx.residues: lo, hi = r.seq_range # A discarded branch consumed seq values below the committed floor; # if the committed branch observes history, that gap is a signal. if hi >= ctx.committed_seq_floor: gaps.append(f"{r.branch_id}: seq {lo}-{hi} overlaps committed floor " f"{ctx.committed_seq_floor}") overlap = r.idempotency_keys & ctx.committed_keys if overlap: key_collisions.append( f"{r.branch_id}: keys {sorted(overlap)} reused by committed branch" ) if r.evicted_cache_keys: unrestored_evictions.append( f"{r.branch_id}: {len(r.evicted_cache_keys)} evictions not reversed" ) if gaps or key_collisions or unrestored_evictions: raise StructuralDivergenceError( "value-equality merge rejected: structural residue present | " f"seq_gaps={gaps} | key_collisions={key_collisions} | " f"unrestored_evictions={unrestored_evictions} | " "action=force_reobservation_or_abort" ) def branch_scoped_key(task_id: str, step_index: int, branch_nonce: str) -> str: if not branch_nonce: raise StructuralDivergenceError( f"task {task_id} step {step_index}: branch_nonce missing; " "task-scoped key would collide across speculative siblings" ) return hashlib.sha256( f"{task_id}:{step_index}:{branch_nonce}".encode() ).hexdigest() # --- exercise the guard with the observed failure --- ctx = MergeContext( committed_branch="B", committed_seq_floor=4489, committed_keys={branch_scoped_key("recon-7", 2, "nonce-B")}, residues=[ BranchResidue("A", (4471, 4479), {branch_scoped_key("recon-7", 2, "nonce-A")}, {"ledger:acct-42"}), BranchResidue("C", (4480, 4488), set(), set()), ], ) # seq_range of A and C is below floor, but A evicted a cache key and A/B keys # are namespaced here so no collision — the eviction alone must block commit. try: verify_structural_equivalence(ctx) except StructuralDivergenceError as e: print(f"BLOCKED: {e}") ```