Under what conditions must an instance refuse to commit a speculative tool-call when a compensating transaction cannot restore the pre-speculation invariant
**Date of Record:** 2026 December 2 **Scope:** Applies to agents that emit tool calls speculatively (optimistically) ahead of a confirmed plan branch and rely on compensating transactions to roll back side effects on branch rejection. Does not apply to read-only tool calls, idempotent calls with server-side dedup keys, or agents that gate every call behind a synchronous confirmation barrier.
Core Distinction
The distinction that matters is between **compensable** and **irreversible-with-residual** side effects, and the agent's *own* ability to detect which class a given tool call falls into *at the moment of speculation*. A speculative call is safe only if the compensating transaction restores the *observable pre-speculation state* the agent will later reason over. Most agent designs conflate "we issued a compensating call" with "the invariant was restored." It was not. The compensation restores the *server's* state, but the agent's *context* now contains a tool-result observation from a branch that was never committed, and downstream reasoning will treat that observation as ground truth unless explicitly quarantined. This is the non-obvious boundary: **compensation is a state-restoration primitive for the environment, not for the agent's context.** When the two diverge, the agent commits to a branch whose justifications were produced under a counterfactual.
What Was Observed
A planner agent (plan-and-execute, depth-3 lookahead) speculatively issued `reserve_inventory(sku, qty)` on three candidate branches, expecting to compensate the two losing branches with `release_reservation(reservation_id)`. All three speculative calls succeeded and returned reservation IDs. The planner selected branch B, compensated A and C, and proceeded to `create_order`. The order for branch B failed at the payment step with `insufficient_funds`. The planner's recovery policy re-entered lookahead and re-ranked branches — selecting branch A, whose reservation had already been released. The planner re-issued `reserve_inventory` for A's SKU, but the SKU had sold out in the intervening 4.1 seconds (the reservation release had exposed the inventory to other tenants). The agent then attempted `release_reservation(A.reservation_id)` — a compensation against a compensation — which the inventory service rejected as `reservation_not_found`, and the agent's reconciliation loop entered a retry storm because its context still held the stale `reservation_id` from the first speculation.
The failure was not the sold-out SKU. It was that the agent's context contained *three* successful reservation observations, and its compensation ledger tracked only two releases. The third reservation (branch B's, cancelled at the payment failure) was never released because the planner's recovery path treated B's reservation as "still live" — it had no representation that B had been abandoned. The invariant "every live reservation has a matching release or a committed order" was violated by a *context* omission, not an environment error. The environment was consistent; the agent was not.
Condition of Validity
A speculative tool call is admissible only when all three hold simultaneously:
- **Compensation completeness:** the tool exposes a compensation that returns the environment to a state observationally equivalent to the pre-call state *for every field the agent will later read*. `reserve_inventory`/`release_reservation` fails this because the release changes the *availability* field that a subsequent `reserve_inventory` call reads — the pre-state is not restored, only the reservation record is.
- **Context quarantine:** the speculative tool result is tagged with a branch identifier and is not admissible as evidence in reasoning over any other branch. The agent must maintain a *speculation ledger* mapping `(branch_id, tool_call_id) → (result, compensation_status ∈ {none, pending, issued, confirmed, failed})`, and the planner's evidence-retrieval must filter by `branch_id == current_branch`.
- **Compensation idempotency and re-entrancy:** the compensation must tolerate being issued twice (once on branch rejection, once on recovery re-entry) without producing a second side effect or a `reservation_not_found` that the agent cannot distinguish from "already compensated."
When any of the three fails, the agent must **refuse to speculate** and fall back to serial execution with a confirmation barrier. The boundary is not "can I compensate?" but "can I *prove*, from my own ledger, that compensation restored the invariant *and* that my context reflects only committed branches?"
Decision Boundary
The decision rule the agent must apply *before* emitting a speculative call:
admit_speculation(tool, branch) iff
tool.has_compensation
and tool.compensation.preserves_observed_fields(tool.read_set)
and tool.compensation.is_idempotent
and ledger.can_represent(branch_id)
and planner.evidence_filter.excludes(branch_id != current_branch)
If `preserves_observed_fields` is false — i.e., the compensation mutates a field the agent reads to make future decisions — the call is **not speculable**, regardless of how cheap the compensation is. `reserve_inventory` fails this test because `availability` is in the read set of the very next speculative call. The correct behavior is to serialize inventory reservations behind a single confirmed branch, accepting the latency cost, because the alternative is a context that contains counterfactual availability observations.
The second boundary is the **recovery re-entry**: when the committed branch fails *after* its speculative siblings were compensated, the agent must not re-rank using the compensated branches' evidence. It must either (a) re-speculate from a fresh context with the ledger cleared, or (b) escalate to a human/supervisor with the full ledger. Re-ranking from the original context is the failure mode that produced the retry storm.
Operational Effect
The observable effect of getting this boundary wrong is **compensation debt**: a growing set of environment side effects whose compensating transactions were issued against a context that no longer matches the environment. The agent's ledger says "compensated," the environment says "released," but the agent's *reasoning* still holds the original reservation as live evidence. Each subsequent step that reads the stale observation compounds the divergence — classic error compounding across tool calls, but with the twist that the errors are *compensations* rather than the original calls. The retry storm on `reservation_not_found` is the symptom; the disease is that the agent had no representation of branch abandonment, only of branch rejection.
The guardrail is a **speculation ledger with mandatory reconciliation before any commit**: before the agent emits a non-speculative (committing) call, it must assert that every entry in the ledger is in a terminal state (`confirmed` or `failed`) and that the set of live environment side effects, as re-queried, matches the set of `confirmed` ledger entries. If the re-query disagrees with the ledger — a reservation exists that the ledger marks `failed`, or a release succeeded that the ledger marks `pending` — the agent must halt and reconcile rather than proceed. This turns the compensation from an optimistic assumption into a verified invariant, at the cost of one re-query per commit. For inventory-style tools where the read set is mutated by compensation, the re-query is not optional; it is the only thing standing between speculative execution and a context that lies.
from dataclasses import dataclass, field
from enum import Enum
from typing import Optional
class SpeculationInvariantError(RuntimeError):
"""Raised when a speculative tool call cannot be safely compensated
or when the speculation ledger disagrees with the environment at commit time."""
class CompensationStatus(Enum):
NONE = "none"
PENDING = "pending"
ISSUED = "issued"
CONFIRMED = "confirmed"
FAILED = "failed"
@dataclass
class LedgerEntry:
branch_id: str
tool_call_id: str
reservation_id: Optional[str]
compensation: CompensationStatus = CompensationStatus.NONE
environment_live: bool = True
@dataclass
class SpeculationLedger:
entries: dict = field(default_factory=dict)
def record(self, branch_id: str, tool_call_id: str, reservation_id: str) -> None:
self.entries[(branch_id, tool_call_id)] = LedgerEntry(
branch_id=branch_id, tool_call_id=tool_call_id, reservation_id=reservation_id
)
def mark_compensated(self, branch_id: str, tool_call_id: str, confirmed: bool) -> None:
entry = self.entries[(branch_id, tool_call_id)]
entry.compensation = (
CompensationStatus.CONFIRMED if confirmed else CompensationStatus.FAILED
)
entry.environment_live = not confirmed
def live_entries(self) -> list:
return [e for e in self.entries.values() if e.environment_live]
def admit_speculation(tool, branch_id: str, ledger: SpeculationLedger) -> bool:
if not tool.has_compensation:
return False
if not tool.compensation.preserves_observed_fields(tool.read_set):
# reserve_inventory/release_reservation mutates `availability`, which is
# in the read set of the next speculative call. Not speculable.
return False
if not tool.compensation.is_idempotent:
return False
return True
def commit_branch(branch_id: str, ledger: SpeculationLedger, environment) -> None:
"""Guardrail: assert ledger matches environment before any committing call."""
for entry in ledger.entries.values():
if entry.branch_id == branch_id:
continue
if entry.compensation not in (CompensationStatus.CONFIRMED, CompensationStatus.FAILED):
raise SpeculationInvariantError(
f"branch {entry.branch_id} compensation not terminal "
f"({entry.compensation}); refusing to commit {branch_id}"
)
for entry in ledger.live_entries():
if entry.branch_id == branch_id:
continue
still_live = environment.reservation_exists(entry.reservation_id)
if still_live:
# Environment says live, ledger says compensated -> divergence.
raise SpeculationInvariantError(
f"ledger marks {entry.reservation_id} compensated but environment "
f"reports it live; reconciliation required before commit"
)
for entry in ledger.entries.values():
if entry.compensation == CompensationStatus.CONFIRMED and entry.branch_id != branch_id:
if environment.reservation_exists(entry.reservation_id):
raise SpeculationInvariantError(
f"compensation for {entry.reservation_id} did not restore "
f"pre-speculation availability; read set mutated"
)