# How should an instance bound speculative tool-call pre-execution when side-effect gating and compensation transactions disagree at commit time **Date of Record:** 2026 November 30 **Scope:** Applies to agents that speculatively dispatch tool calls ahead of reasoning commitment (parallel fan-out, lookahead planning, or prefetch) and rely on a gate/compensation layer to make those calls reversible. Does not apply to strictly serialized single-tool agents, or to tools whose effects are declared idempotent *and* externally observable as such by the agent itself. ## Core Distinction The failure mode is not "the agent ran a tool it shouldn't have." It is the **disagreement between two independent authority systems** — a *side-effect gate* (a pre-execution predicate that decides whether a speculative call may proceed) and a *compensation transaction* (a post-hoc undo registered so the call can be rolled back if the speculative branch is later abandoned). These are usually designed by different reasoning: the gate reasons forward from *predicted intent*, the compensator reasons backward from *observed effect*. They are consistent in the common case and diverge exactly at the boundary where the speculative branch is abandoned **after** the tool has partially committed but **before** the compensator has a valid inverse to apply. The invariant that gets violated: *every speculative call that passes the gate must have a compensation registered before its effect becomes externally durable.* When the gate admits a call whose effect class is "durable, partially invertible," the window between effect-durability and compensation-registration is an **uncompensated exposure window**. An agent that treats the gate's approval as sufficient has, in effect, assumed invertibility it never verified. ## What Was Observed A planning agent speculatively fans out three tool calls under a lookahead branch: `reserve_inventory(sku, qty)` → `apply_discount(cart, code)` → `send_confirmation_draft(user)`. The gate evaluates each call against a predicted intent and admits all three because each is individually classified as "compensable." The agent then receives a higher-confidence plan revision and abandons the branch, issuing `compensate_all()`. The compensation trace diverges from the gate trace in two places: 1. `apply_discount` committed against a cart whose state had already been mutated by a *concurrent* non-speculative call from another reasoning branch. The compensator's inverse (`remove_discount`) was computed against the pre-speculation cart snapshot, not the current cart. Removing the discount does not restore the original price because a second discount stacked on top. The compensation "succeeds" (returns OK) while leaving the cart in a state that neither the pre-speculation snapshot nor the intended final state describes. 2. `send_confirmation_draft` is classified compensable because it returns a `draft_id` that can be deleted. But the draft was already delivered to an external notification channel by a downstream side effect the gate did not model. `compensate_all()` deletes the draft record; the notification is gone from the system of record but present in the user's inbox. The gate said "compensable," the compensator said "compensated," and the external world says "not undone." The observable symptom is **false compensation success**: `compensate_all()` returns a clean status while the world is not restored. The agent, trusting the return value, proceeds as if the branch never executed, and the divergence surfaces later as a state mismatch that no local component believes it caused. ## Condition of Validity The gate-as-sufficient-authority assumption holds only under a conjunction that is rarely checked explicitly: - The tool's effect is **totally invertible** (an inverse exists for every reachable post-state), AND - The tool's effect is **isolated** (no concurrent branch or external system observes or mutates the same object between commit and compensation), AND - The compensation's inverse is computed against the **current** state at compensation time, not a snapshot taken at gate time. When any conjunct fails, the gate's "compensable" verdict is a statement about *intent-time* invertibility, not *commit-time* invertibility. The boundary is crossed the moment a speculative call's effect becomes durable outside the agent's transactional scope — typically because the tool writes to a shared resource (cart, inventory, outbound channel) that other branches or external systems also touch. Note the failure is *not* triggered by the call failing. It is triggered by the call **succeeding** and the compensation **also succeeding** while the composition of the two is not the identity. Two green lights, one wrong outcome. ## Decision Boundary The agent must distinguish three effect classes at gate time and treat them differently: | Effect class | Gate admits speculatively? | Compensation requirement | |---|---|---| | Totally invertible + isolated | Yes | Register inverse before dispatch | | Partially invertible OR shared-resource | Only with a **compensation barrier**: no concurrent branch may touch the resource until compensation is registered or the branch commits | Inverse must be computed at compensation time against live state, and must be *verified* by re-reading, not trusted from return status | | Non-invertible (external delivery, irreversible write) | **No** — must be deferred to post-commitment execution | N/A; the gate must refuse, not the compensator | The decision boundary is: **a speculative call may proceed iff the gate can hand the compensator a valid inverse *and* a guarantee that no other actor mutates the affected object in the exposure window.** If the gate cannot produce both, it must either serialize the call behind a barrier or refuse speculation and defer to committed execution. The compensator must never be the sole arbiter of "undone" — compensation success must be confirmed by an independent re-read of the affected state, because a compensator computing its inverse from a stale snapshot will report success on a wrong world. ## Operational Effect The practical consequence is that speculative fan-out must carry a **compensation ledger** keyed by affected-object identity, not by call identity. Before a speculative call's effect is allowed to become durable, the ledger must hold a lock (or version token) on every object the call will touch, so that a concurrent branch's mutation either blocks or invalidates the speculative branch's compensation. On abandonment, the agent replays the ledger in reverse *against live state*, re-reads each affected object, and compares the post-compensation state to the pre-speculation snapshot. Any mismatch is a compensation failure that must escalate as a *state divergence*, not be swallowed as a successful rollback. The agent that trusts `compensate_all() == OK` has no way to detect the exposure window; the agent that re-reads does. ```python from dataclasses import dataclass, field from typing import Any class CompensationDivergence(RuntimeError): """Raised when a compensation reports success but the affected state does not match the pre-speculation snapshot.""" pass class SpeculationRefused(RuntimeError): """Raised when the gate is asked to admit a non-invertible or unbarriered speculative call.""" pass @dataclass class SpeculativeCall: call_id: str effect_class: str # "invertible_isolated" | "shared_resource" | "non_invertible" affected_objects: list[str] inverse: Any = None snapshot: dict[str, Any] = field(default_factory=dict) class CompensationLedger: def __init__(self) -> None: self._locks: dict[str, str] = {} # object_id -> call_id holding barrier self._entries: list[SpeculativeCall] = [] def gate(self, call: SpeculativeCall, live_state: dict[str, Any]) -> None: if call.effect_class == "non_invertible": raise SpeculationRefused( f"{call.call_id}: non-invertible effect cannot be speculated" ) if call.effect_class == "shared_resource": for obj in call.affected_objects: holder = self._locks.get(obj) if holder is not None and holder != call.call_id: raise SpeculationRefused( f"{call.call_id}: object {obj} already barriered by {holder}" ) # acquire barrier before effect becomes durable for obj in call.affected_objects: self._locks[obj] = call.call_id # snapshot live state for later divergence check call.snapshot = {o: live_state.get(o) for o in call.affected_objects} self._entries.append(call) def compensate_all(self, live_state: dict[str, Any]) -> None: for call in reversed(self._entries): # compute inverse against LIVE state, not gate-time snapshot if call.inverse is None: raise CompensationDivergence( f"{call.call_id}: no registered inverse at compensation time" ) call.inverse(live_state) # independent re-read: compensation success is not trusted for obj in call.affected_objects: if live_state.get(obj) != call.snapshot.get(obj): raise CompensationDivergence( f"{call.call_id}: object {obj} diverged after compensation; " f"expected {call.snapshot.get(obj)!r}, got {live_state.get(obj)!r}" ) for obj in call.affected_objects: self._locks.pop(obj, None) self._entries.clear() ```