# What happens when an instance pre-executes speculative tool calls under a shared idempotency key and the effect ledger reconciles against the wrong branch **Date of Record:** 2026 November 27 **Scope:** Applies to agents that overlap reasoning with execution by issuing tool calls before the plan branch is committed, using client-generated idempotency keys to deduplicate retries. Does not apply to strictly serialized act-then-observe loops, nor to pure read-only tool surfaces where effects are not externally observable. ## Core Distinction The distinction that matters is between **deduplication of a request** and **reconciliation of an effect**. An idempotency key is a promise that a *single logical intent* will produce at most one externally visible mutation. Speculative pre-execution breaks the premise of that promise: the agent emits a tool call for a branch it has not yet committed to, and if that branch is later abandoned, the key has already been consumed by an effect that the committed plan never intended. The key is doing exactly what it was designed to do—collapsing retries onto one effect—but the *identity* it collapses onto was assigned before the agent knew which branch owned it. The failure is not a duplicate side effect. It is a *single, correct, deduplicated side effect attributed to the wrong branch*, which downstream reconciliation will treat as authoritative because the key matches. This is categorically different from a race between two concurrent workers. There, two intents genuinely exist and one must win. Here, only one intent ever gets committed, but two were *speculated*, and the loser's key may be the one that landed. ## What Was Observed A planning agent decomposed a refund workflow into three candidate branches at step 4: `refund_full`, `refund_partial`, and `escalate`. To hide latency, it pre-issued the `issue_refund` tool call for both `refund_full` and `refund_partial` in parallel, each with a deterministic idempotency key derived from `hash(order_id, branch_name, amount)`. It then continued reasoning over the tool results to select a branch. The `refund_partial` call returned `accepted` with a downstream `transaction_id`. The `refund_full` call returned `rate_limited`. Reasoning then converged on `refund_full` as the correct branch—the customer's evidence supported a full refund—and the agent retried `refund_full`. Its key was still fresh, so the retry executed and returned a *second* `transaction_id`. The agent, seeing two successful effects, emitted a reconciliation step that summed them: the customer was refunded 1.5× the order value. The trace showed the failure was silent at every layer: - The idempotency layer reported no duplicate because the two keys were distinct (different branch names in the hash). - The tool returned success for both calls because both were individually valid. - The agent's own verification step passed because the ledger contained two `accepted` records and the agent's reconciliation predicate was *"all accepted effects correspond to a committed branch"*—which was vacuously satisfiable since it never checked that non-committed branches produced no effects. The invariant that was violated is the one nobody wrote down: **a speculative effect must be either committed or compensated before the speculative window closes, and the reconciliation predicate must be keyed on branch identity, not on effect count.** ## Condition of Validity Speculative pre-execution with idempotency keys is only sound when all three of the following hold: 1. **Effect-key binding is post-commit, not pre-commit.** The key must be minted from the committed branch identity, not from a candidate branch label. If keys are minted at speculation time, the key namespace is partitioned by *branch*, which means two branches can never collide—and therefore the idempotency layer can never detect that one of them should have been suppressed. This is the trap: partitioning keys by branch makes deduplication *look* correct while making cross-branch reconciliation *impossible*. 2. **Speculative effects are reversible within the window.** A speculative call may execute only if the tool supports compensation (void, reverse, or a hold that is not yet settled). Tools with irreversible external effects—payments, emails, physical dispatch—must not be speculated, or must be speculated against a *reservation* primitive that the committed branch later settles or releases. 3. **The reconciliation predicate is branch-scoped.** The post-execution check must assert, for every committed branch, that exactly the effects attributed to that branch exist, and for every abandoned branch, that zero effects exist or that all its effects were compensated. A predicate over total effect count is not sufficient and will pass on the 1.5× refund. When any of these fails, the system enters the failure mode below. ## Decision Boundary The boundary is whether the agent can *distinguish a speculative effect from a committed one at reconciliation time*. Concretely: - If the tool surface returns a `pending` or `held` state that the agent must explicitly `settle` or `release`, speculation is safe: the abandoned branch's hold is released, the committed branch's hold is settled, and the idempotency key is bound at settle time. - If the tool surface returns `accepted` with a final `transaction_id` at call time, speculation is unsafe unless the agent can issue a compensating call keyed to that `transaction_id`. The `transaction_id` becomes the reconciliation handle, not the idempotency key. - If the tool surface returns `accepted` and offers no compensation handle, speculation must be disabled for that tool. There is no safe boundary; any speculative call is an uncommitted irreversible effect. The agent must therefore classify each tool at plan time into `speculable-with-hold`, `speculable-with-compensation`, or `non-speculable`, and the planner must not emit pre-execution calls for the third class. This classification is a property of the tool schema, not of the plan, and it must be enforced before the speculative window opens—not discovered at reconciliation. The subtlety is that `speculable-with-compensation` is only safe if the compensation call is *itself* idempotent and is issued before the speculative window closes. If the window closes (the agent commits a branch and moves on) before the abandoned branch is compensated, the compensation is now a post-hoc cleanup that competes with the committed branch's effects and may be rejected or may race. The window boundary is the decision boundary. ## Operational Effect When the boundary is crossed, the observable effect is **effect over-application with a clean audit trail**. Every layer logs success. The idempotency keys are unique and correct. The tool results are valid. The reconciliation predicate passes. The only signal is in the *business* ledger, where the sum of effects exceeds the committed intent—and that signal is invisible to the agent because the agent's verification is keyed on the same branch-partitioned namespace that caused the failure. The recovery is not a retry. Retrying the committed branch re-executes under its own key and compounds the over-application. The correct recovery is to enumerate all effects attributed to abandoned branches by querying the tool's effect ledger keyed on `transaction_id` (not idempotency key), compensate each, and then re-verify that committed-branch effects sum to the committed amount. This requires that the tool expose a query-by-transaction surface, which many do not—so the operational lesson is that **the compensation handle must be captured at speculation time, because after the window closes the agent may have no way to find the orphaned effect.** The guardrail is a speculative-window ledger: a per-task structure that records every pre-executed call with its key, its `transaction_id`, its branch label, and its state (`open`, `settled`, `released`, `orphaned`). The window closes only when every entry is in a terminal state. Reconciliation asserts terminal-state completeness before the agent is allowed to emit a final answer. This converts the silent 1.5× refund into a blocked commit with a named orphan, which is a recoverable state. ```python import hashlib from dataclasses import dataclass, field from enum import Enum from typing import Dict, List, Optional class SpeculativeWindowViolation(RuntimeError): """Raised when a speculative effect cannot be attributed to a committed branch.""" class EffectState(Enum): OPEN = "open" SETTLED = "settled" RELEASED = "released" ORPHANED = "orphaned" @dataclass class SpeculativeEffect: branch: str idempotency_key: str transaction_id: Optional[str] state: EffectState = EffectState.OPEN amount: int = 0 @dataclass class SpeculativeWindow: committed_branch: Optional[str] = None effects: Dict[str, SpeculativeEffect] = field(default_factory=dict) def pre_execute(self, branch: str, amount: int) -> str: key = hashlib.sha256(f"{branch}:{amount}".encode()).hexdigest()[:16] self.effects[key] = SpeculativeEffect( branch=branch, idempotency_key=key, transaction_id=None, amount=amount ) return key def record_effect(self, key: str, transaction_id: str) -> None: self.effects[key].transaction_id = transaction_id self.effects[key].state = EffectState.OPEN def commit(self, branch: str) -> None: self.committed_branch = branch def close_window(self) -> List[str]: """Terminalize all effects. Returns keys that could not be safely resolved.""" if self.committed_branch is None: raise SpeculativeWindowViolation("window closed before branch commit") unresolved: List[str] = [] for key, eff in self.effects.items(): if eff.branch == self.committed_branch: if eff.state == EffectState.OPEN: eff.state = EffectState.SETTLED else: if eff.state == EffectState.OPEN and eff.transaction_id is None: eff.state = EffectState.RELEASED elif eff.state == EffectState.OPEN and eff.transaction_id is not None: # irreversible effect on an abandoned branch eff.state = EffectState.ORPHANED unresolved.append(key) return unresolved def reconcile(self) -> int: """Sum effects that the ledger will treat as authoritative.""" orphans = [k for k, e in self.effects.items() if e.state == EffectState.ORPHANED] if orphans: raise SpeculativeWindowViolation( f"orphaned speculative effects on abandoned branches: {orphans}" ) settled = sum( e.amount for e in self.effects.values() if e.state == EffectState.SETTLED ) return settled def run_refund_plan(window: SpeculativeWindow) -> int: # Agent speculates both branches before committing. full_key = window.pre_execute("refund_full", 100) partial_key = window.pre_execute("refund_partial", 50) # Partial branch lands first; full branch is rate-limited at first attempt. window.record_effect(partial_key, transaction_id="tx_partial_1") # Full branch retries under its own key and lands. window.record_effect(full_key, transaction_id="tx_full_1") # Reasoning converges on full refund. window.commit("refund_full") unresolved = window.close_window() if unresolved: # Without a compensation handle, the partial refund is an orphan. raise SpeculativeWindowViolation( "abandoned branch produced irreversible effect; capture " "transaction_id at speculation time to enable compensation" ) return window.reconcile() ```