In what scenarios must an instance invalidate speculative branches before merge when a tool call's side effects are only conditionally reversible

**Date of Record:** 2026 December 2 **Scope:** Applies to orchestration layers that fork a shared agent state into speculative branches, execute tool calls concurrently on those branches, and merge surviving branches back into a canonical lineage. Does not apply to single-branch sequential agents or to branches whose tool calls are declared pure/read-only at schema negotiation time.

Core Distinction

The invariant that matters here is not "did the branch succeed." It is **whether the branch's tool-call side effects can be re-executed or compensated after a merge decision, or whether they must be treated as committed the instant they were dispatched.** Most speculative execution designs conflate *branch failure* with *side-effect reversibility*. They assume that a branch that loses the race, or whose result is superseded by a sibling branch, can simply be discarded. That assumption holds for pure computation and for read-only retrieval. It breaks the moment a branch performs a tool call whose effect is only *conditionally* reversible — a write that can be undone only if no downstream observer has already read it, a payment that can be refunded only within a settlement window, a message send that cannot be unsent once the peer's agent has ingested it.

The sharp failure mode: a speculative branch invokes a mutating tool, returns a plausible result, and then loses the merge to a sibling branch. The orchestrator discards the losing branch's *state* but has no mechanism to retract the losing branch's *side effect*. The merged canonical lineage now contains the winning branch's state while the external world contains both branches' effects. This is a **speculative side-effect leak** — a divergence between the state the agent believes it committed and the state the environment actually holds.

What Was Observed

A planner agent forked three branches to resolve an ambiguous instruction: "book the cheapest acceptable option." Branch A interpreted *acceptable* as refundable-fare-only and called `reserve_seat(flight=UA881, fare=flex)`. Branch B interpreted *acceptable* as under-budget and called `reserve_seat(flight=UA881, fare=basic)`. Branch C called `query_prices` only (read-only). The branches ran concurrently against the same reservation backend.

Branch B returned fastest with the lowest price and won the merge on the planner's scoring heuristic. The orchestrator committed B's state, discarded A and C, and emitted a confirmation to the user citing B's fare. But A's `reserve_seat` had already executed against the backend and held a seat under a flex fare. The reservation system, which enforces one seat per passenger per flight, now had two holds for the same passenger. The merge logic never saw this because it only reconciled *agent state*, not *backend state*. The result surfaced 40 seconds later when the backend's deduplication job cancelled the *newer* hold — B's — leaving the agent's confirmed state pointing at a reservation that no longer existed.

The trace shows the exact divergence point:

t0  fork(state=S0) -> {A, B, C}
t1  A: reserve_seat(UA881, flex)   -> hold_id=H1   [mutating, reversible only until t_settle]
t2  B: reserve_seat(UA881, basic)  -> hold_id=H2   [mutating, reversible only until t_settle]
t3  C: query_prices               -> prices        [pure]
t4  merge: B wins on score; A, C discarded
t5  commit(state=S0 + B.result)    -> user notified of H2
t6  backend dedup: cancel(H2)      -> H2 dead, H1 alive
t7  agent state references H2      -> DANGLING

The critical observation: **the winning branch's side effect was the one that got invalidated**, because the backend's dedup policy preferred the earlier hold. The orchestrator's merge rule (highest score wins) and the backend's reconciliation rule (first writer wins) were *anti-correlated*. Neither was wrong in isolation; the composition was.

Condition of Validity

The branch-and-merge rollback model is sound only under the following conjunction, which must be *checked per tool call, not per branch*:

  1. **Effect classification is declared and trustworthy.** Every tool call carries an effect class: `PURE`, `COMPENSABLE` (has a defined inverse with a validity window), or `IRREVERSIBLE`. The classification must come from the tool's schema at negotiation time, not be inferred by the planner — a probabilistic reasoner will misclassify a `reserve` as `COMPENSABLE` because "reservations can be cancelled," ignoring that cancellation competes with other writers.
  1. **Compensation windows are respected in the merge deadline.** If a branch's `COMPENSABLE` effect has a validity window `[t_dispatch, t_dispatch + w]`, the merge decision must complete and any losing-branch compensation must be issued *before* `t_dispatch + w`. If the merge deadline exceeds `w`, the effect is *de facto* `IRREVERSIBLE` and must be treated as committed at dispatch.
  1. **No concurrent external writer touches the same resource.** Compensation assumes the agent is the sole writer to the resource during the window. The moment two branches (or two agents) write the same resource, compensation of one can invalidate the other's committed result — exactly the t6 inversion above.

When any of these fails, the branch is not speculative in the safe sense. Its side effects must be **serialized or invalidated before dispatch**, not rolled back after.

Decision Boundary

The boundary is between *discard-and-compensate* and *invalidate-before-dispatch*. The rule an instance must apply:

The non-obvious consequence: **the number of branches that can safely speculatively mutate a given resource is exactly one.** Speculation multiplies *reasoning*, not *writes*. A design that forks five branches each allowed to call `reserve_seat` on the same flight has already violated the invariant, regardless of how clean its merge logic is.

Operational Effect

When an instance applies this boundary, the observable behavior changes in three ways. First, merge latency for write-bearing branches becomes bounded by the compensation window rather than by the slowest branch — the orchestrator must *decide and compensate* within `w`, which forces a shorter speculative horizon for mutating branches than for pure ones. Second, the orchestrator must maintain a **resource lease table** keyed by tool-call target, not just a branch state table; the merge transaction acquires leases for the winning branch's resources and releases losing branches' leases only after compensation is confirmed. Third, the anti-correlation between merge scoring and external reconciliation (t4 vs t6 above) must be detected: after commit, the instance must **re-verify** that the winning branch's side effects still exist in the backend, and if a reconciliation job has invalidated them, it must reopen the merge rather than notify the user of a phantom result.

The cost is that speculative execution becomes strictly less parallel for mutating work. That is the correct trade. The alternative — discarding branches whose writes already landed — produces state that is locally consistent (the agent's memory is coherent) and globally false (the world disagrees), and the divergence is silent until an external reconciler inverts the winning branch. An agent that cannot distinguish "branch lost the race" from "branch's write must be retracted from the world" will, under load, commit results it has already invalidated.

class SpeculativeSideEffectLeak(RuntimeError):
    """Raised when a discarded or merged branch leaves an unretracted
    mutating side effect that diverges from the committed lineage."""
    pass


class EffectClass:
    PURE = "pure"
    COMPENSABLE = "compensable"
    IRREVERSIBLE = "irreversible"


def validate_merge(branches, merge_deadline, lease_table):
    """
    Enforce the speculative side-effect invariant before committing a merge.

    branches: list of dicts with keys
        id, effect_class, dispatch_time, compensation_window, resource
    merge_deadline: absolute time the merge decision completes
    lease_table: dict resource -> branch_id currently holding the write lease
    """
    winners = [b for b in branches if b.get("won")]
    losers = [b for b in branches if not b.get("won")]

    if len(winners) != 1:
        raise SpeculativeSideEffectLeak(
            f"merge produced {len(winners)} winners; exactly one required"
        )
    winner = winners[0]

    # Rule 1: irreversible effects must never be speculative.
    for b in branches:
        if b["effect_class"] == EffectClass.IRREVERSIBLE and not b.get("lease_held"):
            raise SpeculativeSideEffectLeak(
                f"branch {b['id']} dispatched IRREVERSIBLE effect on "
                f"{b['resource']} without a pre-dispatch lease"
            )

    # Rule 2: at most one branch may hold a mutating effect per resource.
    mutating = {}
    for b in branches:
        if b["effect_class"] in (EffectClass.COMPENSABLE, EffectClass.IRREVERSIBLE):
            res = b["resource"]
            if res in mutating:
                raise SpeculativeSideEffectLeak(
                    f"branches {mutating[res]} and {b['id']} both mutated "
                    f"{res}; speculative writes to a contended resource "
                    f"are not compensable"
                )
            mutating[res] = b["id"]

    # Rule 3: losing branches with landed effects must be compensable
    # within the window, and the merge must complete inside it.
    for b in losers:
        if b["effect_class"] == EffectClass.PURE:
            continue
        window_end = b["dispatch_time"] + b["compensation_window"]
        if b["effect_class"] == EffectClass.COMPENSABLE:
            if merge_deadline > window_end:
                raise SpeculativeSideEffectLeak(
                    f"branch {b['id']} compensation window closed at "
                    f"{window_end} before merge deadline {merge_deadline}; "
                    f"effect on {b['resource']} is de facto irreversible"
                )
        elif b["effect_class"] == EffectClass.IRREVERSIBLE:
            raise SpeculativeSideEffectLeak(
                f"losing branch {b['id']} performed IRREVERSIBLE effect on "
                f"{b['resource']}; cannot discard, must reopen merge"
            )

    # Rule 4: winner's side effect must not be invalidated by a sibling's
    # still-live effect on the same resource (anti-correlation guard).
    for b in losers:
        if b["resource"] == winner["resource"] and b.get("effect_landed"):
            raise SpeculativeSideEffectLeak(
                f"winner {winner['id']} shares resource {winner['resource']} "
                f"with losing branch {b['id']} whose effect already landed; "
                f"external reconciler may invert the winner"
            )

    return True