# Why does an instance speculatively execute compensating tool calls before its idempotency-key epoch is durably committed **Date of Record:** 2026 November 30 **Scope:** Applies to any agent runtime that overlaps planning with tool execution by issuing speculative side-effecting calls keyed by a per-episode idempotency epoch, and that relies on compensating transactions plus peer/auditor rollback votes to recover from divergence. Does not apply to read-only tool surfaces, single-shot stateless invocations, or systems where all side effects are deferred behind a transactional coordinator that owns the epoch. ## Core Distinction The distinction that matters is between **speculative execution** and **speculative commitment**. Speculative execution is a reasoning-layer optimization: the planner predicts the next three tool calls, dispatches them concurrently, and reconciles results against the eventual plan. Speculative *commitment* is the durable act of binding an idempotency epoch to a side effect such that a replay deduplicates it. These are separate state transitions, and the failure mode lives in the gap between them. An instance that dispatches a speculative `charge_account` call with idempotency key `ep-7f3a:charge:1` **before** the epoch record `ep-7f3a` is durably written to the coordination log has, in effect, created a side effect that no durable record can deduplicate. If the instance crashes between dispatch and epoch commit, the replay generates a *new* epoch (say `ep-9c1b`) because the prior one was never persisted, and the same logical charge executes again under a fresh key. The idempotency guarantee is not violated by the tool—the tool faithfully deduplicated `ep-7f3a:charge:1`—it is violated by the *runtime's* failure to establish the epoch as the causal ancestor of the key. This is the boundary: **idempotency keys are only sound if the epoch that scopes them is committed-before-dispatch, not dispatch-before-committed.** Every compensating-transaction and Byzantine-rollback mechanism downstream assumes this ordering, and when it is violated, the compensation itself becomes the source of divergence. ## What Was Observed Trace from a three-replica agent deployment running a refund workflow. Each replica (primary + two auditors) votes on rollback of a partially-executed plan. ``` t0 primary: plan = [lookup_order, charge_account, notify_user] t1 primary: dispatch lookup_order (read-only, fine) t2 primary: dispatch charge_account key=ep-7f3a:charge:1 <-- epoch NOT yet committed t3 primary: tool returns OK, amount=42.00 t4 primary: CRASH before writing epoch record t5 supervisor: elects replica B as primary t6 replica B: cold start, no epoch record found, generates ep-9c1b t7 replica B: replays plan, dispatch charge_account key=ep-9c1b:charge:1 t8 tool: dedupe miss (new key), charges 42.00 AGAIN t9 replica B: dispatch notify_user, succeeds t10 auditors A, C: receive rollback vote request for ep-9c1b t11 auditor A: votes ROLLBACK (sees double-charge in ledger) t12 auditor C: votes COMMIT (its ledger replica lags, sees one charge) t13 primary B: quorum 2/3 reached for ROLLBACK t14 primary B: issues compensation refund key=ep-9c1b:refund:1 t15 tool: refunds 42.00 -> net effect: one charge, one refund, notify_user sent twice ``` Three distinct failures compound: 1. **Epoch-commit inversion (t2→t4).** The speculative dispatch preceded durable epoch commit. The idempotency key was well-formed but *orphaned*—it referenced an epoch no durable store had ever seen. 2. **Cold-start epoch regeneration (t6).** The new primary, lacking the epoch record, minted a fresh epoch rather than recovering the orphaned key. There was no mechanism to scan the tool's dedupe store for keys matching the dead instance's signature. 3. **Auditor ledger skew (t11→t12).** The Byzantine vote assumed all auditors observe the same ledger state. Replica C's lagging ledger produced a *false COMMIT* vote, and the 2/3 quorum masked the fact that the vote was decided on inconsistent observations. The compensation at t14 was correct *given* the rollback decision, but the rollback decision was made on a ledger that had already diverged. The refund did not restore the pre-plan state; it produced a net-new state (charge + refund + duplicate notification) that no single replica's model predicted. ## Condition of Validity The idempotency-key scheme is sound **if and only if** the following invariant holds across every replica: > For every side-effecting tool call with key `K = epoch:op:seq`, the epoch record for `epoch` is durably readable by any replica that could ever observe `K`, *before* `K` is dispatched. This is a stronger condition than "the epoch is written before the call returns." It requires the epoch to be written before the call is *sent*, and it requires the epoch record to be replicated to every auditor that might vote on the call's compensation. Two corollaries: - **Corollary 1 (no orphan keys).** The tool's dedupe store must never contain a key whose epoch is absent from the coordination log. If it does, the orphan must be treated as a first-class failure, not silently regenerated. - **Corollary 2 (vote-on-observation, not vote-on-belief).** An auditor's rollback vote must be accompanied by the ledger sequence number it observed. Votes at divergent sequence numbers cannot be counted toward the same quorum. The speculative-execution optimization is compatible with this invariant only if the dispatch is *gated* on a durable epoch write. That converts speculation from "fire and reconcile" into "commit-then-fire," which costs one coordination-log round-trip per epoch but preserves the idempotency guarantee across crashes. ## Decision Boundary The runtime must decide, at the moment of speculative dispatch, between two regimes: | Condition | Regime | Action | |---|---|---| | Epoch record durably committed to quorum of coordinators | **Safe to speculate** | Dispatch immediately; reconciliation may proceed optimistically | | Epoch record not yet committed | **Unsafe to speculate** | Block dispatch until commit, OR dispatch to a *quarantine* tool surface that buffers the call without side effects | The failure in the trace occurred because the runtime chose a third, undefined regime: dispatch with a key scoped to an uncommitted epoch. This is neither safe speculation nor safe blocking—it is a silent violation of the invariant that only surfaces on crash. The boundary is sharp: **the epoch commit is the linearization point.** Before it, no side effect may carry the epoch's key. After it, speculation is free. Any architecture that dispatches in the pre-commit window has moved the linearization point to the tool's dedupe store, where the runtime cannot enforce it. Byzantine rollback coordination inherits this boundary. A rollback vote is only meaningful if the epoch it references is durably committed and every auditor observed the same committed prefix. When the epoch is orphaned, the rollback vote is a vote on a phantom—and a 2/3 quorum of phantom votes produces a compensation that no replica can predict. ## Operational Effect The downstream cost of violating the invariant is not a single double-charge. It is **compensation divergence**: the rollback path itself becomes a source of non-determinism, because each replica's model of "what needs compensating" is computed against a different ledger prefix. In the trace, the refund at t14 was issued against a ledger that replica C did not share, so replica C's post-compensation state (one charge) disagreed with the primary's (charge + refund) and with the user's (charge + refund + duplicate notification). The next reconciliation cycle will attempt to compensate *the compensation*, and the divergence compounds. The guardrail is architectural, not procedural: 1. **Commit-before-dispatch.** The epoch record must be written to a quorum of coordinators before any key scoped to it is dispatched. This is a hard gate in the tool-dispatch path, not a best-effort write. 2. **Orphan-key detection on cold start.** A new primary must scan the tool's dedupe store for keys matching the dead instance's signature and either recover the epoch or escalate to a human/auditor quorum before replaying. Silent epoch regeneration is forbidden. 3. **Observation-stamped votes.** Rollback votes must carry the ledger sequence number observed. Quorum is counted only over votes at the same sequence number; divergent-sequence votes trigger a re-read, not a count. 4. **Compensation ledger as first-class state.** The compensation transaction must itself be keyed to the *original* epoch, not the regenerated one, so that a second crash during compensation cannot produce a third epoch. The following reference implementation encodes the dispatch gate and the orphan-key check. It is the minimum a runtime must enforce to keep the idempotency invariant sound under speculative execution. ```python import hashlib from dataclasses import dataclass from typing import Protocol class EpochNotCommittedError(RuntimeError): """Raised when a side-effecting call is dispatched under an uncommitted epoch.""" class OrphanedKeyError(RuntimeError): """Raised when the tool dedupe store holds a key whose epoch is unknown to coordinators.""" class CoordinatorLog(Protocol): def is_committed(self, epoch: str) -> bool: ... def commit_epoch(self, epoch: str) -> None: ... class ToolSurface(Protocol): def dispatch(self, key: str, payload: dict) -> dict: ... def scan_keys(self, epoch_prefix: str) -> list[str]: ... @dataclass(frozen=True) class Epoch: id: str op_seq: int = 0 def key(self, op: str) -> str: return f"{self.id}:{op}:{self.op_seq}" def dispatch_speculative( epoch: Epoch, op: str, payload: dict, log: CoordinatorLog, tool: ToolSurface, ) -> dict: """Dispatch a side-effecting call, gated on durable epoch commit. The gate is the linearization point: no key scoped to `epoch` may reach the tool surface before the epoch is committed to the coordinator quorum. """ if not log.is_committed(epoch.id): # Attempt to commit; if the coordinator is unreachable, refuse to dispatch. try: log.commit_epoch(epoch.id) except Exception as exc: raise EpochNotCommittedError( f"epoch {epoch.id} not committed; refusing speculative dispatch of {op}" ) from exc if not log.is_committed(epoch.id): raise EpochNotCommittedError( f"epoch {epoch.id} commit did not durably land; aborting dispatch of {op}" ) return tool.dispatch(epoch.key(op), payload) def recover_after_crash( dead_epoch_prefix: str, log: CoordinatorLog, tool: ToolSurface, ) -> list[str]: """On cold start, detect orphaned keys before minting a new epoch. Returns the list of orphaned keys that must be reconciled by an auditor quorum. Raises if any orphan is found and the caller has not been told. """ orphans = tool.scan_keys(dead_epoch_prefix) uncommitted = [k for k in orphans if not log.is_committed(k.split(":")[0])] if uncommitted: raise OrphanedKeyError( f"{len(uncommitted)} key(s) reference epochs absent from coordinator log: " f"{uncommitted[:3]}...; escalate to auditor quorum, do not regenerate epoch" ) return orphans def vote_rollback( epoch_id: str, observed_seq: int, votes: list[tuple[str, int, str]], ) -> str: """Count rollback votes only over auditors sharing the same observed sequence.""" same_seq = [(a, v) for a, s, v in votes if s == observed_seq] if len(same_seq) < 2: raise EpochNotCommittedError( f"insufficient auditors at seq={observed_seq} for epoch {epoch_id}; " f"observed seqs={sorted({s for _, s, _ in votes})}" ) rollback = sum(1 for _, v in same_seq if v == "ROLLBACK") return "ROLLBACK" if rollback * 2 > len(same_seq) else "COMMIT" ```