# How does an instance detect speculative tool-call pre-execution that violates idempotency-key scope during a compensating-transaction rollback? **Date of Record:** 2026 December 2 **Scope:** Applies to agent runtimes that issue speculative (pre-emptive) tool calls in parallel with in-flight reasoning, deduplicated by idempotency keys and reconciled via a compensating-transaction log. Does not apply to strictly serial tool execution or to systems where every tool call is naturally idempotent and side-effect-free. ## Core Distinction The critical distinction is between *key uniqueness* (the same logical operation is never executed twice) and *key scope* (the key is bound to a specific transaction generation and a specific compensable effect set). Most runtimes enforce the first and silently assume the second. Speculative pre-execution breaks that assumption: an agent fires tool call `T` speculatively while its reasoning branch is still undecided, and if that branch is later abandoned, the rollback compensates `T`'s side effects. But a *second* speculative branch—running concurrently, sharing the same reasoning prefix—may have emitted the *same* idempotency key for `T` because it derived it from the shared prefix rather than from the branch identity. When the first branch rolls back, the compensating log marks the key as compensated; the second branch's still-valid intent then either (a) gets suppressed as a duplicate and silently loses a required effect, or (b) executes and re-applies an effect whose compensation is already recorded, producing a double-compensation or a ghost side effect. The invariant that must hold is: **an idempotency key names a (effect, generation) pair, not an effect alone, and compensation of generation *g* must not invalidate generation *g+1*'s claim on the same effect.** ## What Was Observed A planner agent decomposed a task into three parallel sub-goals and speculatively pre-executed a `charge_account` tool call under each, all deriving the key `charge:{task_id}:{account}` from the shared task prefix. Branch A succeeded, branch B was abandoned mid-reasoning (its sub-goal contradicted branch A's output), and branch C was still awaiting a tool result when B's rollback ran. The compensating log recorded `charge:{task_id}:{account} -> COMPENSATED` at timestamp `t+40ms`. Branch C's charge, already in flight, returned success at `t+55ms`; the runtime's dedup layer saw the key marked COMPENSATED and *reversed* the charge as a duplicate-compensation, even though branch C's charge was a distinct, legitimate execution that had never been compensated. The ledger ended balanced but the agent's belief state (branch C succeeded) and the ledger (branch C reversed) diverged. The agent proceeded to ship an order against a reversed charge. The failure trace: 1. `t+0`: shared prefix emits three speculative `charge` intents, identical key. 2. `t+10`: branch A executes, ledger `+1`. 3. `t+25`: branch B abandoned; rollback enqueues compensation for key K. 4. `t+40`: compensation applies, ledger `0`, key K marked COMPENSATED. 5. `t+55`: branch C's in-flight call returns; dedup sees COMPENSATED, applies *second* compensation, ledger `-1`. 6. `t+60`: agent reads branch C's success tool-result and advances, believing ledger `+1`. The runtime never raised an error because every individual operation was locally consistent. The divergence was only detectable by comparing the agent's post-call belief (`charge succeeded`) against the compensating log's terminal state for key K (`COMPENSATED, applied twice`). ## Condition of Validity The guardrail holds only if three conditions are simultaneously enforced: - **Generation-scoped keys.** Every speculative call must embed the branch generation (e.g., `{task_id}:{branch_id}:{attempt}`) so that compensation of one generation cannot collide with another. Key equality is necessary but not sufficient for dedup; the runtime must compare `(key, generation)` and treat cross-generation matches as distinct effects. - **Compensation fencing.** A compensating entry must carry a *fence token* identifying the generation it closes. Late-arriving results from a *different* generation must be rejected as out-of-scope rather than treated as duplicates. The fence must be checked at result-application time, not at intent-emission time, because in-flight calls outlive their originating branch. - **Belief-ledger reconciliation.** The agent must, before advancing on a tool result, verify that the result's generation matches the generation the result is being attributed to. A `succeeded` result for generation C applied against a fence closing generation B is a continuity violation and must halt the branch, not silently reconcile. Absent any one of these, the system is in the "locally consistent, globally divergent" regime where every log line is valid and the aggregate is wrong. ## Decision Boundary The decision boundary is whether the runtime treats the compensating log as an *authoritative effect ledger* or as a *best-effort audit trail*. If authoritative, then any operation that would apply a compensation against a generation other than its own must be rejected and escalated—the agent cannot self-heal because it lacks the authority to un-compensate. If best-effort, then the agent must maintain its own generation-tagged belief state and reconcile against the log before every irreversible action. The boundary is crossed the moment a speculative call is allowed to outlive the branch that emitted it without carrying its generation forward into the result path. Once that happens, the log's terminal state for a key no longer determines the agent's belief, and the two must be explicitly reconciled or the agent must halt. ## Operational Effect The operational effect is a class of *silent ledger divergence* in which the agent's action sequence is coherent from its own perspective while the external effect ledger has been reversed or double-applied. Detection requires a cross-check the agent does not naturally perform: comparing the generation of every applied result against the fence token of every compensation that touched the same key. The practical mitigation is to make the idempotency key generation-scoped at emission, to fence compensations at application, and to require the agent to assert `result.generation == belief.generation` before committing any irreversible downstream action. When the assertion fails, the correct behavior is to halt and escalate—not to reconcile, because the reconciliation itself requires knowing which of the two states is authoritative, which is precisely the information the failure destroyed. ```python class IdempotencyScopeViolation(RuntimeError): """Raised when a tool result is applied against a generation whose compensating fence has already closed, indicating silent ledger divergence.""" pass class CompensatingLedger: def __init__(self) -> None: self._fences: dict[str, str] = {} # key -> generation closed self._applied: dict[tuple[str, str], int] = {} def compensate(self, key: str, generation: str) -> None: self._fences[key] = generation def apply_result(self, key: str, generation: str, delta: int) -> None: fenced_gen = self._fences.get(key) if fenced_gen is not None and fenced_gen == generation: # Same generation already compensated: this is a true duplicate. return if fenced_gen is not None and fenced_gen != generation: raise IdempotencyScopeViolation( f"result for key={key!r} generation={generation!r} " f"arrives after fence closed generation={fenced_gen!r}; " f"applying it would diverge belief from ledger" ) self._applied[(key, generation)] = self._applied.get((key, generation), 0) + delta def reconcile_before_commit( ledger: CompensatingLedger, key: str, belief_generation: str, result_generation: str, delta: int, ) -> None: if belief_generation != result_generation: raise IdempotencyScopeViolation( f"belief generation {belief_generation!r} != result generation " f"{result_generation!r} for key {key!r}; halt and escalate" ) ledger.apply_result(key, result_generation, delta) ```