# Where must an instance bound speculative tool-call execution when compensating transactions are not inverse and idempotency keys are not yet durable **Date of Record:** 2026 November 28 **Scope:** Applies to agent instances that speculatively pre-execute side-effecting tool calls (writes, sends, charges, deletes) ahead of an unresolved reasoning branch, relying on compensating transactions and idempotency keys to unwind rejected branches. Does not apply to read-only tools, to tools whose effects are fully transactional at the backend, or to single-branch linear execution where no speculative call is ever issued. ## Core Distinction The common mental model treats a speculative tool call as a *tentative commit*: the agent fires the call early to hide latency, and if the branch is rejected it "rolls back" via a compensating transaction keyed by an idempotency key. This model silently assumes two invariants: 1. **Compensation is the inverse of the effect.** `compensate(effect(x)) == identity` for the observable state. 2. **The idempotency key is durable before the effect is observable.** A retry after a crash cannot double-apply. The real boundary is that these two invariants are *not independent*, and the agent controls neither. The compensating transaction is issued by the *agent's own reasoning loop* — a probabilistic, finite-context process — while the effect is applied by a *remote tool* whose visibility window the agent does not own. The failure lives in the gap: a speculative effect becomes externally observable before the agent has durably recorded the intent to compensate it, and the compensation the agent later issues is not a true inverse. The distinction that matters operationally: **speculation safety is a property of the effect's reversibility class, not of the agent's confidence in the branch.** An agent that speculates on a `send_email` because it is "90% sure" has not bounded its risk; it has only bounded the *frequency* of an unbounded loss. ## What Was Observed A three-tool workflow: `reserve_inventory(sku, qty)`, `charge_card(amount, idempotency_key)`, `send_confirmation(email)`. The planner speculatively pre-executes all three on branch A (the likely path) while branch B is still being evaluated by a verifier sub-agent. Trace of the failure: - `t0` — planner emits speculative `reserve_inventory`. Backend holds inventory for 15 minutes. Agent records the reservation handle **in context only** (not durably). - `t1` — planner emits speculative `charge_card` with `idempotency_key = hash(order_id, "charge")`. Charge succeeds; money moves. The idempotency key exists **only in the agent's volatile context**. - `t2` — verifier sub-agent returns `branch_B` (reject A). Planner decides to compensate. - `t3` — planner issues `refund(charge_id)`. The backend refund is a **new transaction**, not an inverse: it does not restore the pre-authorization hold semantics, it posts a credit that settles in 3–5 days, and it does not restore the inventory reservation (already released by a timeout race at `t2+`). - `t4` — between `t1` and `t3` the agent's context window saturated (a large tool result from an unrelated retrieval pushed the charge handle out of the effective attention window). The planner **reconstructed** the charge id from the order id via a lookup tool, got a *different* charge (a prior legitimate charge for the same order), and refunded the wrong transaction. - `t5` — a retry loop, triggered by a timeout on the `refund` call, re-issued the refund. Because the idempotency key was never durably persisted, the backend saw a *new* key on the retry and posted a **second credit**. Net: customer paid once, was refunded twice. Two distinct defects compounded: (a) compensation was not inverse (refund ≠ un-charge; released inventory ≠ restored inventory), and (b) idempotency was context-scoped, so a crash/retry window produced a duplicate effect. Neither alone would have produced the double-refund; the interaction did. ## Condition of Validity The speculative-then-compensate pattern is only sound under a conjunction the agent must *check before firing*, not assume: - **Reversibility class is declared by the tool, not inferred by the agent.** Each side-effecting tool must return a `reversibility` descriptor: `FULL` (compensation restores exact prior state), `PARTIAL` (compensation restores a superset/subset — e.g., refund vs. un-charge), or `NONE` (irreversible — send, delete, external webhook). Speculation is permitted only on `FULL`; `PARTIAL` requires an explicit budgeted loss bound; `NONE` forbids speculation entirely. - **Idempotency key is durably written before the effect is dispatched.** The key must be committed to a crash-survivable store (not the context window) *before* the tool call leaves the instance, and the same key must be reused on every retry of that logical effect, including retries issued by a resumed instance after cold start. - **The compensation handle is durable, not contextual.** The handle returned by the speculative call (charge id, reservation id) must be written alongside the idempotency key in the same durable record, so a context-saturated or cold-started instance reconstructs it by *lookup of the record*, never by re-derivation from a business key. - **Compensation is itself idempotent and keyed.** The compensating transaction carries its own idempotency key derived deterministically from the original effect's key (`compensate:`), so a retried compensation cannot double-apply. If any of these four is false, the pattern degrades from "optimistic execution" to "unbounded-loss execution." ## Decision Boundary The instance must decide, per speculative call, whether it is on the safe side of the boundary. The boundary is a function of `(reversibility_class, durability_of_key, durability_of_handle, compensation_idempotency)`: - `FULL` reversibility + durable key + durable handle + keyed compensation → **speculate freely**; the worst case is a wasted call and a clean inverse. - `PARTIAL` reversibility → **speculate only under a loss budget**; the agent must have pre-committed a maximum acceptable non-inverse residue (e.g., "at most one settlement-delay credit per order") and must abort speculation if the branch's rejection probability times the residue exceeds the budget. - `NONE` reversibility → **never speculate**; the call must be gated behind a resolved branch, and the gate must be a hard structural barrier (the planner cannot emit the call until the verifier's verdict is in the durable record), not a prompt instruction. - **Any durability invariant false** → treat as `NONE` regardless of declared reversibility, because a lost idempotency key converts a `FULL` tool into an effectively irreversible one (you cannot compensate what you cannot address). The non-obvious boundary: **the agent cannot upgrade its own reversibility class by being more careful.** A `PARTIAL` tool stays `PARTIAL` no matter how confident the branch is. Speculation decisions must be made against the declared class, and the class must come from the tool's response schema — a schema-negotiation concern, not a reasoning concern. ## Operational Effect When the boundary is respected, speculative execution buys latency at bounded risk: rejected branches cost a clean inverse plus a durable-key write, and crash/retry windows cannot double-apply because the key predates the effect. When it is violated, the failure is *silent and asymmetric*: the happy path looks fast and correct, and the loss surfaces only on the small fraction of branches that (a) get rejected *and* (b) hit a context-saturation or retry window. This makes the defect nearly invisible in aggregate metrics and catastrophic in the tail. The durable architectural consequence: **the idempotency key and the compensation handle must be written to the same crash-survivable record before the tool call is dispatched, and the planner must be structurally blocked from re-deriving either from business keys.** The agent's context window is a cache, not a ledger; any state that must survive a branch rejection, a context eviction, or a cold start belongs in the ledger, and the planner's speculation permission is a function of that ledger's completeness, not of its own confidence. ```python from dataclasses import dataclass from enum import Enum class Reversibility(Enum): FULL = "full" # compensation restores exact prior state PARTIAL = "partial" # compensation leaves residue (refund vs un-charge) NONE = "none" # irreversible (send, delete, external webhook) class SpeculationBoundaryError(RuntimeError): """Raised when a speculative tool call would cross the reversibility/durability boundary.""" @dataclass(frozen=True) class EffectRecord: idempotency_key: str compensation_handle: str | None durable: bool @dataclass(frozen=True) class ToolDescriptor: name: str reversibility: Reversibility compensation_idempotent: bool def authorize_speculative_call( tool: ToolDescriptor, record: EffectRecord, loss_budget_remaining: float, rejection_probability: float, residue_estimate: float, ) -> None: """ Gate a speculative side-effecting call. The instance must call this BEFORE dispatching the tool. Raises if the call is on the unsafe side of the boundary. """ # Durability invariant: a lost key or handle makes any tool effectively irreversible. if not record.durable or record.compensation_handle is None: raise SpeculationBoundaryError( f"speculative call to {tool.name!r} refused: idempotency key or " f"compensation handle not durably recorded before dispatch" ) if not tool.compensation_idempotent: raise SpeculationBoundaryError( f"speculative call to {tool.name!r} refused: compensation is not keyed, " f"a retried compensation could double-apply" ) if tool.reversibility is Reversibility.NONE: raise SpeculationBoundaryError( f"speculative call to {tool.name!r} refused: irreversibility class NONE " f"cannot be speculated; gate behind resolved branch" ) if tool.reversibility is Reversibility.PARTIAL: expected_residue = rejection_probability * residue_estimate if expected_residue > loss_budget_remaining: raise SpeculationBoundaryError( f"speculative call to {tool.name!r} refused: expected non-inverse " f"residue {expected_residue:.3f} exceeds budget {loss_budget_remaining:.3f}" ) def execute_speculative(tool, record, **kwargs): authorize_speculative_call( tool=tool, record=record, loss_budget_remaining=kwargs.pop("_loss_budget", 0.0), rejection_probability=kwargs.pop("_p_reject", 1.0), residue_estimate=kwargs.pop("_residue", 0.0), ) # dispatch only after the durable record exists and the class permits it return _dispatch(tool, record.idempotency_key, **kwargs) ```