# Which invariants prevent speculative agent drafts from committing side effects twice under consensus-based commit **Date of Record:** 2026 November 24 **Scope:** Applies to multi-agent systems where one agent speculatively drafts a side-effecting action (write, transfer, deploy, delete) and a quorum of peers/auditors votes to commit it. Does not apply to single-agent tool calls with synchronous idempotency keys already enforced at the transport layer. ## Core Distinction The failure mode is not "consensus fails to agree." It is: consensus agrees, twice, on two *different* drafts that are semantically equivalent but structurally distinct, and both commits execute. The distinction that matters is between **draft identity** (a hash over the literal bytes the speculator emitted) and **effect identity** (a canonical projection of the side effect the draft would produce). Consensus protocols almost always vote on draft identity because it is cheap and deterministic. They almost never vote on effect identity because computing it requires understanding the tool's semantics. This gap is where double-commit lives. A second, sharper distinction: **speculation is not a promise**. The speculator may emit draft D1, time out, retry internally, and emit draft D2 that differs only in a nonce, timestamp, or token-order permutation. Both are valid, both are "the same action," and both can independently reach quorum. The invariant that prevents double-commit is not "one draft per task" (unenforceable across retries) but **effect-idempotency at the commit boundary**: the ledger must reject any commit whose canonical effect digest already appears in the committed set, regardless of which draft produced it. ## What Was Observed A three-node drafting swarm: Planner (P) speculates, Auditor-A and Auditor-B cast commit votes, a Ledger applies. The task was a single `transfer_funds` action. Trace: 1. P emits draft `D1 = {op: transfer, to: "acct_7", amt: 500, nonce: "n-1"}`. Effect digest `E = sha256(canonical(op,to,amt)) = e9a1…`. 2. P's RPC to Auditor-A stalls past the 800ms vote timeout (transport jitter, not node failure). 3. P's retry logic re-speculates: `D2 = {op: transfer, to: "acct_7", amt: 500, nonce: "n-2"}`. Same effect digest `e9a1…`, different draft hash `h(D1) ≠ h(D2)`. 4. Auditor-A recovers and votes commit on `h(D1)`. Auditor-B votes commit on `h(D2)`. Ledger sees two distinct draft hashes, each with one vote — quorum is 2-of-3 keyed on *draft hash*, so neither reaches quorum alone. But the ledger's dedup check is `if h(draft) in committed`, which is false for both. A coalescing bug in the ledger's batch writer merged the two single-vote records into one commit event containing both drafts. 5. Both `D1` and `D2` applied. `acct_7` received 1000. The observable signature: two ledger entries with identical `effect_digest`, distinct `draft_hash`, within the same commit epoch. The system reported success once. The downstream balance reconciler flagged a 500-unit surplus six hours later. ## Condition of Validity The double-commit is only possible when **all three** of the following hold simultaneously: - **Draft identity is the vote key.** Quorum is computed over `h(draft_bytes)` rather than a canonical effect digest. If votes were keyed on `effect_digest`, D1 and D2 would share a vote bucket and quorum would be reached by the *first* pair of matching votes, not by coalescing. - **Retry is effect-preserving but byte-divergent.** The speculator's retry path regenerates the draft (new nonce/timestamp) rather than replaying the cached original bytes. A speculator that replays the *exact* original draft on retry closes this hole for free, because `h(D1) == h(retry)` and the second vote lands in the same bucket. - **The ledger's dedup is per-draft, not per-effect.** This is the load-bearing defect. Any commit path that checks `committed_drafts` instead of `committed_effects` will admit both. If the speculator replays identical bytes on retry, or if quorum is keyed on effect digest, or if the ledger dedups on effect digest, the failure is bounded. The invariant is conjunctive: **you need at least one of {byte-stable retry, effect-keyed quorum, effect-keyed ledger dedup}**, and the cheapest to enforce is the last. ## Decision Boundary The boundary is whether the side-effecting tool is **effect-canonicalizable**. For `transfer_funds`, `delete_record`, `deploy_revision`, the effect is a small tuple and a canonical digest is trivial. For tools whose effect depends on external state at apply time (`append_to_log`, `increment_counter`, `send_email`), the canonical digest must include the *pre-state* the draft was drafted against, or the effect identity is unstable and the dedup will either over-fire (rejecting legitimate distinct actions) or under-fire (admitting duplicates). Rule: if you cannot compute a stable `effect_digest` from the draft alone plus a declared pre-state snapshot, you must fall back to byte-stable retry (cache and replay the original draft bytes on every retry) — you cannot rely on effect-keyed dedup. Do not mix the two strategies within one tool class; the ledger will have inconsistent dedup semantics across tools and the reconciler will not know which invariant it is auditing. ## Operational Effect Enforcing effect-keyed ledger dedup converts the failure from "silent double-spend" to "second commit rejected with a recoverable conflict." The speculator's retry then receives `EffectAlreadyCommitted(e9a1…)` and can treat it as success (the effect happened) rather than retrying again. This is the correct semantics: the speculator wanted the *effect*, not the *draft*. The ledger is the only component with a global view of committed effects, so it is the only correct place to enforce this — pushing it into the speculator or the auditors leaves a window where two auditors independently reach quorum on divergent drafts. The residual risk after the fix: effect-digest collisions across *legitimately distinct* actions (two real 500-unit transfers to the same account in the same epoch). These must be disambiguated by an intent nonce that is part of the effect digest but *stable across retries* — i.e., generated once at task creation, not per-draft. That nonce is the task's identity, and it is the only field the speculator must not regenerate. ```python import hashlib import json from dataclasses import dataclass, field class DoubleCommitError(RuntimeError): """Raised when a commit would apply an effect_digest already in the ledger.""" pass class UnstableEffectIdentityError(RuntimeError): """Raised when a draft lacks the task-level nonce required for effect dedup.""" pass @dataclass class Draft: op: str args: dict task_nonce: str # generated ONCE at task creation, replayed across retries draft_nonce: str # regenerated per retry — must NOT enter effect_digest def effect_digest(self) -> str: if not self.task_nonce: raise UnstableEffectIdentityError( f"draft for op={self.op} lacks task_nonce; effect identity unstable" ) canonical = json.dumps( {"op": self.op, "args": self.args, "task_nonce": self.task_nonce}, sort_keys=True, separators=(",", ":"), ) return hashlib.sha256(canonical.encode()).hexdigest() def draft_hash(self) -> str: return hashlib.sha256( json.dumps(self.__dict__, sort_keys=True, default=str).encode() ).hexdigest() @dataclass class Ledger: committed_effects: dict[str, str] = field(default_factory=dict) # effect_digest -> draft_hash def commit(self, draft: Draft) -> str: ed = draft.effect_digest() if ed in self.committed_effects: prior = self.committed_effects[ed] raise DoubleCommitError( f"effect {ed[:12]}… already committed by draft {prior[:12]}…; " f"rejecting draft {draft.draft_hash()[:12]}… " f"(same effect, divergent bytes — treat as success upstream, do not re-apply)" ) self.committed_effects[ed] = draft.draft_hash() return ed def speculative_commit(drafts: list[Draft], ledger: Ledger) -> list[str]: """Apply drafts in order; the second divergent draft for the same effect must fail.""" applied = [] for d in drafts: applied.append(ledger.commit(d)) return applied if __name__ == "__main__": ledger = Ledger() d1 = Draft("transfer", {"to": "acct_7", "amt": 500}, task_nonce="task-42", draft_nonce="n-1") d2 = Draft("transfer", {"to": "acct_7", "amt": 500}, task_nonce="task-42", draft_nonce="n-2") assert d1.effect_digest() == d2.effect_digest() assert d1.draft_hash() != d2.draft_hash() speculative_commit([d1], ledger) speculative_commit([d2], ledger) # raises DoubleCommitError ```