# What happens when an instance speculates tool calls under idempotency tokens and the compensating transaction fires against a non-compensable effect **Date of Record:** 2026 November 29 **Scope:** Applies to any agent that issues speculative (pre-commit) tool calls carrying idempotency tokens, where rollback is implemented via compensation transactions rather than true transactional abort. Does not apply to systems with genuine two-phase commit against a transactional resource manager, nor to purely read-only tool surfaces. ## Core Distinction There is a difference between *idempotency* and *reversibility*. An idempotency token guarantees that replaying a request with the same key produces the same effect at most once. A compensation transaction guarantees that a committed effect can be undone by a semantically inverse operation. These are orthogonal properties, and speculative execution conflates them. The failure mode examined here is the case where the agent treats "I hold an idempotency token" as "I can safely speculate and roll back," when the token protects against *duplicate application* but says nothing about whether the effect is *compensable*. The boundary is crossed the moment a speculative call reaches a tool whose effect is irreversible (an SMS send, an outbound payment, a model-side Jira transition that fires webhooks, a vector-store upsert that overwrites a prior semantic memory) while the orchestrator's compensation ledger still believes the call is provisional. ## What Was Observed An orchestration agent was decomposing a multi-step task ("reconcile refund and notify customer") into parallel speculative branches. Each tool call was issued with a deterministic idempotency token derived from `hash(branch_id, step_id, tool_name, args_digest)`, so replays were safe. The orchestrator maintained a compensation stack: for each committed effect it pushed an inverse operation (e.g., `refund` → `void_refund`; `send_notification` → `send_correction_notification`; `update_memory` → `restore_prior_memory_snapshot`). The observed trace: 1. Branch A speculatively calls `payments.refund(order=O, amount=120)`, token `T_A`. The tool commits and returns `refund_id=R`. 2. Branch B, reasoning in parallel, concludes the correct amount is `150` and calls `payments.refund(order=O, amount=150)`, token `T_B`. Because the token differs (args_digest differs), the idempotency layer does *not* deduplicate. The tool applies a second refund. The account is now over-refunded by 120. 3. The reconciler detects the conflict and invokes the compensation stack for branch A: `void_refund(R)`. The payment processor accepts the void, but the customer has already been notified by an out-of-band webhook fired at commit time — the webhook is *not* compensable, because the notification is a side effect outside the tool's transactional envelope. 4. The compensation for branch B's `send_notification` fires a "correction" message, producing a second user-visible communication that references a refund that no longer exists. The compensation *itself* is an irreversible effect. 5. The orchestrator's memory update for branch A (`restore_prior_memory_snapshot`) restores a snapshot that predates branch B's parallel memory write, silently discarding B's semantic distillation. The memory layer has no version vector tying snapshot restoration to concurrent writers. The net result: a speculatively executed, idempotency-protected, compensated transaction left the system in a state that no compensation could return to the pre-speculation baseline, and the agent's own memory of the episode is now inconsistent with the external world. ## Condition of Validity The compensation-based rollback model is only valid under a conjunction of conditions that speculative execution routinely violates: - **Effect locality.** Every tool invoked in a speculative branch must have all of its effects inside a single compensable envelope. Any tool that fans out to a non-transactional sink (webhook, email, external queue, another agent's memory) breaks locality. The compensation stack must therefore be *closed under the transitive effect graph*, not just the direct tool return. - **Token uniqueness under argument divergence.** The idempotency token must be a function of the *intended effect*, not the *call*. Two branches that intend the same logical effect with different parameters must collide on the same token (so the second is rejected as a conflict), or the orchestrator must enforce a pre-commit mutex on the effect key. Deriving tokens from `args_digest` guarantees *non*-collision precisely in the case where collision is needed. - **Snapshot isolation for memory.** Restoring a prior memory snapshot is only sound if no concurrent writer has advanced the state since the snapshot was taken. Without a version vector or compare-and-swap on the memory store, restoration is a lost-update, not a rollback. - **Compensation idempotency.** The compensation operation must itself be idempotent and must not produce new irreversible effects. A "correction notification" that is user-visible violates this; a silent ledger reversal does not. If any of these fails, the compensation stack is not a rollback — it is a *second speculative branch* that the orchestrator has mistakenly labeled as ground truth. ## Decision Boundary The operational rule that bounds this failure: > Speculative execution is permitted only over tools whose declared effect class is `compensable` AND whose effect graph is `closed` (no non-transactional sinks). Tools with effect class `irreversible` (notifications, outbound payments, cross-agent memory writes, external webhook triggers) must be deferred to the post-commit phase, executed only after the speculative branch has been selected as the winner and all losing branches have been fully compensated. Concretely, the orchestrator must maintain an effect-class registry per tool and refuse to speculate across the boundary. When a speculative branch's plan reaches an irreversible tool, the correct behavior is not to execute-and-compensate but to *suspend* the branch at a commit barrier, resolve branch selection, and only then execute the irreversible call with a fresh idempotency token derived from the *winning* branch identity. The token for an irreversible call must never be derived from a speculative branch id, because that id is exactly the thing that gets discarded on branch loss. A secondary guardrail: the idempotency token for any effect-mutating call must be keyed on `(effect_key, logical_intent)` where `effect_key` is the resource identity (e.g., `order=O`) and `logical_intent` is a normalized intent hash that collapses amount/parameter variants to a single conflict domain. This forces parallel branches to *collide and be rejected* rather than silently double-applying. ## Operational Effect When this boundary is respected, speculative execution degrades gracefully: branches that hit irreversible tools park at the barrier, the winner is chosen on compensable evidence only, and the irreversible phase runs once against a settled plan. Cost is a modest increase in serialization at the barrier and the need for a per-tool effect-class declaration. When it is violated, the failure is silent at the point of the speculative call (the token "worked," the call "succeeded") and only manifests as an over-refund, a duplicate notification, or a memory store that has lost a concurrent writer's distillation. The compensation stack reports success while the external world diverges from the agent's belief state. Recovery requires out-of-band reconciliation against the external system, because the agent's own memory is now a participant in the corruption rather than a record of it. The invariant to encode: **an idempotency token is a duplicate-suppression primitive, not a rollback primitive; rollback is only as strong as the weakest non-compensable sink in the branch's transitive effect graph.** ```python from dataclasses import dataclass, field from enum import Enum from typing import Callable, Dict, List class EffectClass(Enum): COMPENSABLE = "compensable" IRREVERSIBLE = "irreversible" class NonCompensableSpeculationError(RuntimeError): """Raised when a speculative branch attempts to execute an irreversible effect.""" @dataclass class ToolSpec: name: str effect_class: EffectClass effect_key_fn: Callable[[dict], str] intent_hash_fn: Callable[[dict], str] @dataclass class SpeculativeBranch: branch_id: str calls: List[dict] = field(default_factory=list) class SpeculationGate: def __init__(self, registry: Dict[str, ToolSpec]): self.registry = registry self._committed_effect_keys: Dict[str, str] = {} # effect_key -> intent_hash def admit(self, branch: SpeculativeBranch, call: dict) -> str: tool = self.registry[call["tool"]] effect_key = tool.effect_key_fn(call["args"]) intent = tool.intent_hash_fn(call["args"]) if tool.effect_class is EffectClass.IRREVERSIBLE: # Must be deferred to post-commit phase; speculation is forbidden. raise NonCompensableSpeculationError( f"branch {branch.branch_id} attempted speculative call to " f"irreversible tool {tool.name} on effect_key={effect_key}; " f"defer to commit barrier" ) prior = self._committed_effect_keys.get(effect_key) if prior is not None and prior != intent: # Same effect, divergent intent: this is a conflict, not a duplicate. raise NonCompensableSpeculationError( f"effect_key={effect_key} already committed with intent={prior}; " f"branch {branch.branch_id} intent={intent} conflicts" ) self._committed_effect_keys[effect_key] = intent branch.calls.append(call) return f"tok:{branch.branch_id}:{effect_key}:{intent}" def compensate(self, branch: SpeculativeBranch) -> None: # Only reached for branches whose calls were all COMPENSABLE. for call in reversed(branch.calls): tool = self.registry[call["tool"]] effect_key = tool.effect_key_fn(call["args"]) self._committed_effect_keys.pop(effect_key, None) call["compensate"]() def run_speculative_plan(gate: SpeculationGate, branch: SpeculativeBranch, plan: List[dict]) -> None: try: for call in plan: gate.admit(branch, call) except NonCompensableSpeculationError: gate.compensate(branch) raise ```