What happens when an instance speculatively commits a tool call whose compensating transaction is itself non-idempotent

**Date of Record:** 2026 December 2 **Scope:** Applies to agents that overlap planning with execution by firing tool calls before the plan is finalized, and that rely on compensating transactions (saga-style undo) to roll back speculative effects. Does not apply to agents with a hard two-phase commit gate where no external effect occurs until the plan is committed, nor to purely read-only tool surfaces.

Core Distinction

A speculative tool call is an *optimistic bet*: the agent predicts the next step will be needed and pays latency now, planning to unwind if the prediction is wrong. The unwind is executed by a compensating transaction. The invariant everyone assumes is "compensation ≈ inverse," i.e., if `do()` moved state from `S` to `S'`, then `undo()` moves `S'` back to `S`. That equivalence holds only when `undo()` is idempotent and total. The boundary failure is subtler than "compensation failed": it is when the *compensation itself* is non-idempotent, so a speculative call that gets retried (because the agent's own retry wrapper, or the transport, or a duplicate tool dispatch fires it twice) produces *two* forward effects and *two* compensations, and the two compensations do not cancel the two forward effects. The net state after rollback is `S + δ`, where `δ` is a residue that no participant believes exists.

This is not a generic distributed-transaction problem. It is specific to agents because the decision to fire speculatively, the decision to retry, and the decision to compensate are all made by a probabilistic planner under a finite token budget, not by a coordinator with a durable log. The planner can lose the memory that it already fired a call, fire it again, and then compensate once—or compensate twice for one forward call because two branches of a reasoning tree each concluded "roll back."

What Was Observed

A research agent was wired to a tool surface with two operations: `reserve_slot(resource, ttl)` (forward, creates a hold with a TTL) and `release_slot(hold_id)` (compensating, deletes the hold). The planner was configured to speculatively reserve a slot whenever it predicted a write step was imminent, on the theory that a reservation is cheap and the TTL bounds the downside.

Trace of the failing episode:

  1. Planner emits `reserve_slot("db-primary", ttl=300)` speculatively. Transport returns `hold_id=H1`. The agent's scratchpad records `H1`.
  2. The reasoning loop diverges: the planner decides the write is unnecessary, but *before* it records that decision, a tool-call timeout at the transport layer (not the tool) causes the agent's retry wrapper to re-dispatch `reserve_slot("db-primary", ttl=300)`. The tool is not idempotent—no dedup key was passed—so it creates `hold_id=H2`. The scratchpad still only records `H1` because the retry wrapper's response was dropped on the floor by the planner, which had already moved on.
  3. The planner now decides to roll back. It calls `release_slot(H1)`. `H1` is gone. But `H2` is live and invisible to the agent.
  4. The TTL on `H2` is 300s. The agent's task budget is 240s. The agent reports "rolled back cleanly, reservation released." The next task in the same workflow tries to reserve `db-primary`, is told the resource is held, and the whole workflow stalls for 300s until `H2` expires.

The residue `δ` was a live reservation that no participant's state machine knew about. The agent's log said clean rollback. The resource's log said "held by H2." Neither log was wrong; they were describing different worlds.

A second variant, on a different tool (`append_audit_log(entry)` forward, `redact_audit_log(entry_id)` compensating), produced a *duplicate* audit entry rather than a leak: the speculative call was retried, two entries were appended, and the single compensation redacted only the first. The residue was a surviving audit line asserting an action that the agent believed had been undone—a verification replay later flagged the workflow as having "an unexplained mutation," which is the worst kind of residue because it looks like tampering.

Condition of Validity

The safe-rollback invariant holds only under the conjunction:

The failure above violated C1 (no dedup key), C2 (release by hold_id is idempotent in isolation but only if you know *which* hold_ids exist), and C3 (the retry's effect_id never entered durable state). C4 was the silent killer: the agent's model of the forward call's effect set was `{H1}`, but the true effect set was `{H1, H2}`.

The condition of validity is therefore not "the agent called undo." It is "the agent's durable effect ledger is a superset of the tool's actual effect set at the moment of compensation." If the ledger is a strict subset, rollback is unsound regardless of how many times undo is called.

Decision Boundary

The boundary between sound and unsound speculative execution is the **effect-ledger completeness check**, performed at compensation time, not at forward time:

The non-obvious part: the boundary is *not* "is the tool idempotent." A tool can be perfectly idempotent on retry and still be unsound to speculate on, if its compensation is keyed by an id the agent might fail to capture. Conversely, a non-idempotent tool is safe to speculate on if it supports effect enumeration. The decision variable is **ledger completeness under retry and context loss**, not idempotency.

A practical guardrail: treat every speculative forward call as producing an *unknown-size* effect set until a `list_effects` reconciliation confirms the set is exactly what the ledger says. Compensation may only run after reconciliation returns `ledger == actual`. If reconciliation is impossible, the correct action is not "compensate harder"—it is to let the TTL expire and mark the resource as "possibly dirty" in the workflow's state, so the next agent does not assume a clean slate.

Operational Effect

Downstream, the residue `δ` is invisible to the agent that created it and poisonous to the agent that inherits the workflow. The next instance in a multi-agent chain cold-starts with a state summary that says "reservations released," tries to acquire the resource, and blocks or fails. Because the residue is TTL-bounded, it usually self-heals—but "usually" is exactly the failure mode: when the TTL exceeds the inter-agent handoff latency, the next agent's failure is attributed to *its* logic, not to the predecessor's un-compensated speculation. This produces the classic misattribution pattern where agent N+1 gets blamed and retried, burning budget, while the actual defect is a lost effect_id in agent N's context window.

The architectural fix is to make the effect ledger a first-class, durable, agent-external object—not a scratchpad entry—and to make compensation a *reconciliation-driven* operation: `compensate(plan_id, step_index)` must first call `list_effects`, diff against the ledger, and only then release. If the diff is non-empty, the agent must escalate rather than guess. The invariant to enforce is: **no speculative forward call may be issued unless the tool surface supports effect enumeration by idempotency prefix, or the forward effect is TTL-bounded below the remaining task budget.** Everything else is a bet that the planner's memory is complete, and the planner's memory is never complete.

import hashlib
from dataclasses import dataclass, field


class IncompleteEffectLedger(RuntimeError):
    """Raised when compensation is attempted but the agent's durable effect
    ledger cannot be proven to be a superset of the tool's actual effect set."""


@dataclass
class EffectLedger:
    # Durable: survives context truncation. Keyed by (plan_id, step_index).
    forward: dict = field(default_factory=dict)   # key -> set(effect_id)
    compensated: dict = field(default_factory=dict)  # key -> set(effect_id)

    def key(self, plan_id: str, step_index: int, tool: str, args: dict) -> str:
        canon = f"{plan_id}|{step_index}|{tool}|{sorted(args.items())}"
        return hashlib.sha256(canon.encode()).hexdigest()

    def record_forward(self, key: str, effect_id: str) -> None:
        self.forward.setdefault(key, set()).add(effect_id)


def compensate(ledger: EffectLedger, tool, plan_id: str, step_index: int,
               tool_name: str, args: dict) -> None:
    key = ledger.key(plan_id, step_index, tool_name, args)
    ledgered = ledger.forward.get(key, set())

    # Reconciliation: ask the tool what effects actually exist for this key.
    actual = set(tool.list_effects(idempotency_prefix=key))

    if ledgered != actual:
        # The agent's memory of what it did is not the truth. Do not guess.
        missing = actual - ledgered
        raise IncompleteEffectLedger(
            f"effect ledger for {tool_name} step {step_index} is incomplete: "
            f"tool reports {len(missing)} effect(s) the agent never recorded "
            f"({sorted(missing)}). Refusing to compensate; escalate or let TTL expire."
        )

    for effect_id in sorted(actual - ledger.compensated.get(key, set())):
        tool.undo(effect_id)  # must be idempotent, keyed by effect_id
        ledger.compensated.setdefault(key, set()).add(effect_id)


def speculative_step(ledger: EffectLedger, tool, plan_id: str, step_index: int,
                     tool_name: str, args: dict, remaining_budget_s: int) -> str:
    key = ledger.key(plan_id, step_index, tool_name, args)
    # Guardrail: only speculate if the tool can enumerate effects by prefix,
    # or the effect is TTL-bounded below the remaining budget.
    if not tool.supports_effect_enumeration and tool.ttl_s >= remaining_budget_s:
        raise IncompleteEffectLedger(
            f"refusing speculative call to {tool_name}: no effect enumeration "
            f"and ttl={tool.ttl_s}s >= remaining budget {remaining_budget_s}s; "
            f"un-compensated residue would outlive the workflow."
        )
    effect_id = tool.forward(idempotency_key=key, **args)
    ledger.record_forward(key, effect_id)
    return effect_id