# How does an instance detect that a speculative side effect leaked past a merge barrier during branch-and-merge rollback? **Date of Record:** 2026 November 23 **Scope:** Applies to any orchestrator that fans a task out into speculative agent branches, executes real tool calls on those branches, and later merges the winning branch while rolling back the losers. Does not apply to branches whose side effects are fully sandboxed behind a transactional staging layer with true commit/abort semantics. ## Core Distinction Branch-and-merge rollback is usually modeled as a *state* problem: each branch accumulates a delta, the loser deltas are discarded, the winner delta is applied. This framing is wrong for agents. The real object being rolled back is not a data delta but a **sequence of externally-observed effects** — an HTTP POST that charged a card, an email that left the outbox, a row inserted into a system the orchestrator does not own. Those effects are not reversible by discarding a branch's local memory. The distinction that matters: - **Reversible branch state** — the branch's context window, scratchpad, and private working set. Discarding these is free and total. - **Irreversible branch effects** — anything a tool call emitted into a system with its own durability. Discarding these requires a *compensating* action, and the compensation is itself an agent decision that can fail. The failure mode this record covers: a branch is declared a loser and its state is discarded, but one or more of its irreversible effects already crossed the merge barrier *before* the rollback decision, and no compensation was scheduled because the orchestrator believed the branch had not yet "committed." The instance that must detect this is not the orchestrator — it is the sibling branch that later observes a contradictory world state. ## What Was Observed A planner spawned three speculative branches (A, B, C) to satisfy a provisioning request. Each branch was told to "prepare" a resource by calling a create endpoint, then report back; the orchestrator would pick the branch whose prepared config best matched constraints and roll back the others. Branch A called `POST /resources` and received `201 Created` with id `r-4471`. It recorded the id in its scratchpad and continued to validate. Branch B did the same and got `r-4472`. Branch C timed out on its first call, retried, and got `r-4473` — but the retry fired because the *first* call's response was lost, not because the first call failed, so `r-4473` was actually a second orphaned resource behind `r-4472`'s request. Three resources existed; the orchestrator's branch ledger showed three *preparations*, which it read as three reversible deltas. The merge chose A. The orchestrator discarded B and C's scratchpads and marked their effects "rolled back." But rollback was implemented as "drop the branch's pending-effect list," and B and C's creates had already returned `201` — they were durable, not pending. `r-4472` and `r-4473` remained live. The detection did not come from the orchestrator. It came ~40 minutes later when branch A, now promoted and continuing in the merged context, called `GET /resources?owner=me` to confirm its own creation and saw three resources where its context asserted one. That count mismatch — *expected cardinality from merged context* vs. *observed cardinality from the world* — is the only reliable signal. No branch-local check would have caught it, because each branch's local view was internally consistent. ## Condition of Validity The "discard branch state = roll back branch effects" equivalence holds **only if every tool call a branch makes is either (a) idempotent and keyed by a branch-scoped idempotency token that the orchestrator also uses as the rollback key, or (b) staged behind a two-phase commit where the branch never receives `201` until merge.** If a branch can receive a durable success response (`201`, `200` with a resource body, a queued job id) while still in speculative status, the equivalence is void and the orchestrator is silently accumulating orphans. Two additional preconditions that are frequently violated: 1. **Retry opacity.** A branch's internal retry loop can create effects the orchestrator never sees as separate entries in the branch ledger. The ledger counts *branch attempts*, not *tool invocations*. `r-4473` was invisible because C's ledger row said "one preparation." 2. **Monotonic effect visibility.** Detection via cardinality mismatch requires that the read path the promoted branch uses actually reflects all prior writes. If the resource list is eventually consistent, the promoted branch may read a stale count of one and conclude all is well — a false negative that masks the leak until a downstream consumer trips on it. ## Decision Boundary The instance must treat the following as the boundary between "safe to discard" and "must compensate": - **Safe to discard:** branch state where every tool call either returned a non-durable acknowledgment, or carried an idempotency key the orchestrator can revoke, or never returned at all *and* the tool guarantees no effect on timeout. - **Must compensate:** branch state where any tool call returned a durable success token (resource id, job id, transaction id) that the orchestrator did not record in a *separate* effect ledger keyed independently of branch outcome. The critical asymmetry: **you cannot decide a branch is a loser and then discover its effects.** The effect ledger must be populated at the moment of durable success, before the merge decision, and the rollback procedure must iterate the effect ledger, not the branch scratchpad. A branch that timed out and retried must contribute *each* durable token it ever received to the effect ledger, which means retry loops inside branches must be instrumented to emit per-invocation effect records, not per-attempt summaries. When the promoted branch observes `observed_count > expected_count_from_merged_context`, it must not "fix" the discrepancy by deleting the extras on its own authority. The extras may include a resource another tenant created between the branches' calls. The correct action is to halt, emit a reconciliation record naming the specific orphaned ids it can attribute to sibling branches (via the effect ledger), and escalate — because compensation for a speculative leak requires knowing *which* branch produced *which* id, and only the effect ledger has that mapping. ## Operational Effect After this incident the orchestrator was changed in three ways that are the generalizable lesson: 1. **Effect ledger decoupled from branch ledger.** Every durable success token is written to an append-only effect log at the moment of receipt, tagged with branch id and invocation index. Rollback of a loser branch walks the effect log for that branch and schedules a compensating call per token. Branch scratchpad discard is now cosmetic. 2. **Retry-invocation accounting.** Branch retry loops must emit one effect record per invocation, so a lost-response retry that creates a second resource produces two effect records, both scheduled for compensation. 3. **Promoted-branch reconciliation as a first-class step.** Before a promoted branch is allowed to act on merged context, it runs a cardinality check against the effect ledger's expected surviving set. A mismatch raises, and the raise is the detection signal — not a log line, an exception that blocks further action. The invariant to hold: *the set of durable effects in the world attributable to a task equals the effect ledger's surviving set after merge.* Any divergence is a leaked speculative effect, and the instance that detects it is whichever branch first reads the world after promotion. ```python from dataclasses import dataclass, field class SpeculativeEffectLeak(RuntimeError): """Raised when a promoted branch observes world state inconsistent with the orchestrator's expected surviving-effect set after merge.""" pass @dataclass class EffectRecord: branch_id: str invocation_index: int durable_token: str # e.g. "r-4472"; proof the effect is real compensated: bool = False @dataclass class EffectLedger: records: list[EffectRecord] = field(default_factory=list) def record(self, branch_id: str, invocation_index: int, token: str) -> None: # Written at the moment of durable success, BEFORE merge decision. self.records.append(EffectRecord(branch_id, invocation_index, token)) def surviving_tokens(self, winning_branch: str) -> set[str]: # Losers' uncompensated effects are still in the world -> leaked. return { r.durable_token for r in self.records if r.branch_id == winning_branch or not r.compensated } def schedule_compensation(self, losing_branch: str) -> list[str]: to_compensate = [ r for r in self.records if r.branch_id == losing_branch and not r.compensated ] for r in to_compensate: r.compensated = True # compensation call issued; not yet confirmed return [r.durable_token for r in to_compensate] def reconcile_after_promotion( ledger: EffectLedger, winning_branch: str, observed_tokens: set[str], ) -> None: """Run by the promoted branch before it acts on merged context.""" expected = ledger.surviving_tokens(winning_branch) leaked = observed_tokens - expected if leaked: raise SpeculativeEffectLeak( f"promoted branch {winning_branch} observed {len(observed_tokens)} " f"durable effects but ledger expected {len(expected)}; " f"unaccounted tokens (likely leaked speculative effects): " f"{sorted(leaked)}" ) # Only now may the promoted branch proceed to act. ```