# How should an instance reconcile speculative parallel branches when optimistic tool invocations have already committed external side effects **Date of Record:** 2026 November 26 **Scope:** Applies to orchestrators that fan out multiple speculative branches from a shared agent state, let each branch optimistically invoke tools before a merge decision, and then must roll back losing branches. Does not apply to strictly serialized tool execution or to branches whose tools are provably side-effect-free (pure reads against an immutable snapshot). ## Core Distinction The failure is not "a branch produced a wrong answer." It is that **the merge/rollback layer treats branch state as reversible when only a subset of it is**. Speculative execution assumes a clean dichotomy: committed state versus discarded state. In real agent systems there are three tiers, and the reconciliation logic usually models only two: 1. **Pure state** — the branch's internal reasoning trace, scratch context, candidate plan. Fully reversible; discard is free. 2. **Idempotent external effects** — a write keyed by a deterministic idempotency token, a cache set, a status transition that can be replayed. Reversible *if and only if* the token was propagated and the downstream honors it. 3. **Non-idempotent external effects** — an email sent, a payment captured, a row appended, a webhook fired, a ticket created. Irreversible. The only recovery is a *compensating* action, which is a new effect, not an undo. The boundary condition is that the merge decision is made **after** branches have already crossed into tier 3. Once two speculative branches have each fired a non-idempotent effect, no merge algorithm can produce a single coherent world state; it can only produce a world state plus a set of compensations, and those compensations are themselves observable and may themselves fail. ## What Was Observed A planner instance decomposed a task and spawned three speculative branches (A, B, C) from a shared checkpoint at step 7. Each branch was given the same tool manifest and permission to invoke optimistically to "reduce latency," with the understanding that the reconciler would select the winning branch at the merge barrier. Trace of the failure: - Branch A invoked `create_invoice(customer=441, amount=1200)` at t=0.4s. The tool returned success and appended a row. No idempotency key was passed — the branch's tool wrapper generated one per-call, not per-logical-intent, so a replay from branch B would not dedupe. - Branch B, reasoning from the same step-7 state but with a different retrieved context (its retrieval returned a stale price sheet), invoked `create_invoice(customer=441, amount=980)` at t=0.6s. Also succeeded, also appended. - Branch C correctly determined the task was already satisfiable without a new invoice and invoked nothing. - At the merge barrier (t=1.1s), the reconciler scored branches by a verifier model. B scored highest on the *plan* rubric because its reasoning chain was internally consistent — the verifier never saw that the amount was derived from stale retrieval, only that the arithmetic was sound. A was discarded. C was discarded as redundant. - Reconciler executed rollback on A: called `void_invoice(id=A_row)`. This is a compensating effect. It succeeded but emitted a customer-facing notification. - Net result: customer 441 received an invoice for 980 (wrong), a void notice for 1200 (confusing), and the audit log contains three invoice lifecycle events for a task that should have produced one. The system reported `status: merged_clean`. The critical observation: **the reconciler's success signal was computed over tier-1 state (plan quality) while the damage lived in tier-3 state (external effects).** The two were never compared. The merge barrier is a synchronization point for *reasoning*, not for *effects*, and the architecture conflated them. A second, subtler observation: branch A's rollback was executed *after* branch B's commit. The compensation for A ran against a world state that already contained B's effect, so the void notice referenced an invoice number that was never the "real" one from the customer's perspective. Compensations are not order-independent. ## Condition of Validity The invariant that must hold for speculative multi-agent execution to be safe: > **No branch may cross into tier 3 (non-idempotent external effect) until the merge decision for that branch's logical intent is final, OR every tier-3 effect carries a merge-scoped idempotency token such that at most one branch's effect per logical intent can commit.** Formally, let each speculative branch carry an `intent_id` derived deterministically from the parent checkpoint and the semantic action (not from the branch id, not from wall-clock). A tier-3 tool invocation is admissible optimistically only if: - the tool accepts an idempotency key, and - the key is `hash(intent_id, action_signature)`, so two branches proposing the *same* logical action collapse to one committed effect, and - the reconciler, on selecting a winner, commits the winner's key and *cancels* (not compensates) the losers' keys before they are ever materialized downstream. If the tool cannot accept an idempotency key — and many cannot, e.g. `send_email`, `fire_webhook`, arbitrary third-party APIs — then the branch must be **gated**: it may speculate on tier-1 and tier-2 freely, but tier-3 invocation is deferred behind the merge barrier and executed only by the winning branch, serially. This converts latency back into correctness, which is the correct trade for irreversible effects. The invariant fails silently when the tool wrapper generates idempotency keys per-call rather than per-intent. This is the single most common implementation defect: the key *looks* present, the tool *looks* idempotent, and dedup never fires because every call has a unique key. The presence of an idempotency parameter is not evidence of idempotency; the key derivation must be audited. ## Decision Boundary The reconciler must classify each branch's effect ledger before scoring, not after. The decision rule: - **If all branches touched only tier 1–2:** merge freely, score on plan quality, discard losers with no compensation. Optimistic execution was correct. - **If any branch touched tier 3 and the intent_id idempotency invariant held:** the effects have already collapsed to at most one committed effect per intent; score on plan quality, but the *effect ledger* must be part of the score — a branch whose committed effect diverges from the winning plan is a hard conflict, not a soft one. - **If any branch touched tier 3 and the invariant did not hold:** the merge is **unsafe**. Do not silently compensate and report clean. The reconciler must escalate to a `SpeculativeEffectConflict` state, surface the full effect ledger (every tier-3 call, its branch, its timestamp, its idempotency key), and require either human adjudication or an explicit compensation plan that is itself reviewed. Reporting `merged_clean` here is the actual bug — it launders an irreversible divergence into a success signal. The boundary is sharp: the moment a tier-3 effect commits without a merge-scoped idempotency token, the system has left the regime where automated reconciliation is sound. No amount of verifier scoring recovers it, because the verifier scores reasoning, and the damage is in effects. ## Operational Effect Concretely, systems that get this wrong exhibit a specific signature: **effect count exceeds intent count, and the excess is correlated with branch fan-out width, not with task complexity.** A task that should produce one invoice produces `k` invoices and `k-1` void notices, where `k` is the number of branches that reached tier 3. The audit log looks busy, the success metric looks green, and the only detector is downstream reconciliation against the source of truth — which usually happens days later, in a different system, by a human. The architectural guardrail is to make the effect ledger a first-class, merge-barrier-synchronized artifact: 1. Every tool invocation records `(branch_id, intent_id, idempotency_key, tier, committed_at)` before returning. 2. The reconciler reads the ledger at the barrier and refuses to score until every in-flight tier-3 call has resolved (commit or cancel). 3. Idempotency keys are derived from intent, never from call site. 4. Tier-3 tools that cannot accept keys are gated behind the barrier by policy, enforced in the tool wrapper, not by branch discipline. 5. Compensation is modeled as a new effect with its own ledger entry, never as an undo, and is order-sensitive — compensations must be applied in reverse commit order. The deeper lesson: speculative execution is a bet that the cost of rollback is lower than the cost of serialization. That bet is only valid over reversible state. Agents that speculate over irreversible effects are not speculating — they are committing multiple times and calling the cleanup a merge. ```python class SpeculativeEffectConflict(RuntimeError): """Raised when a merge barrier detects tier-3 effects that cannot be reconciled because the intent-scoped idempotency invariant did not hold.""" pass TIER_PURE = 1 TIER_IDEMPOTENT = 2 TIER_IRREVERSIBLE = 3 def reconcile_branches(branches, effect_ledger): """ branches: list of dicts with branch_id, plan_score effect_ledger: list of dicts: {branch_id, intent_id, idempotency_key, tier, committed_at} Invariant required for safe optimistic merge: For every tier-3 effect, idempotency_key == derive(intent_id), so at most one committed effect exists per intent_id. """ tier3 = [e for e in effect_ledger if e["tier"] == TIER_IRREVERSIBLE] # Group irreversible effects by logical intent. by_intent = {} for e in tier3: by_intent.setdefault(e["intent_id"], []).append(e) for intent_id, effects in by_intent.items(): committed = [e for e in effects if e["committed_at"] is not None] if len(committed) > 1: # Two branches materialized the same intent -> keys were per-call, # not per-intent. The world state is already divergent. raise SpeculativeEffectConflict( f"intent {intent_id!r} has {len(committed)} committed tier-3 " f"effects from branches " f"{[e['branch_id'] for e in committed]}; " f"idempotency keys " f"{[e['idempotency_key'] for e in committed]} " f"did not collapse. Merge is unsafe." ) # Safe path: at most one committed effect per intent. Select winner by score, # but require the winner's committed effects to match its plan. winner = max(branches, key=lambda b: b["plan_score"]) winner_effects = [e for e in tier3 if e["branch_id"] == winner["branch_id"]] if not winner_effects and any( e["committed_at"] is not None for e in tier3 ): # Another branch committed an effect the winner's plan does not contain. raise SpeculativeEffectConflict( f"winner branch {winner['branch_id']!r} has no committed tier-3 " f"effects, but a discarded branch did. Winner plan and effect " f"ledger disagree; cannot merge cleanly." ) return {"winner": winner["branch_id"], "status": "merged_clean"} def commit_optimistic(branch_id, intent_id, tool, tier, idempotency_derive): """ Wrapper enforcing the invariant at invocation time. idempotency_derive: callable(intent_id) -> key, must be deterministic and independent of branch_id / wall clock. """ key = idempotency_derive(intent_id) if tier == TIER_IRREVERSIBLE and key is None: raise SpeculativeEffectConflict( f"branch {branch_id!r} attempted irreversible tool {tool!r} " f"for intent {intent_id!r} without an intent-scoped idempotency " f"key; gate this tool behind the merge barrier." ) return tool(idempotency_key=key) ```