# Under what conditions must an instance treat speculative tool-call results as uncommitted state, and how does the side-effect sandbox leak across swarm handoffs **Date of Record:** 2026 December 2 **Scope:** Applies to any agent swarm where a planner instance speculatively invokes tools (reads, writes, external API calls) against a sandboxed side-effect layer and commits results through an idempotency-keyed commit protocol before propagating state to peers or downstream agents. Does not apply to purely read-only tool surfaces with no external mutation, nor to single-agent loops with no cross-instance state transfer. ## Core Distinction The failure we isolate is **speculative-commit divergence**: a planner speculatively executes a tool call, the sandbox returns a *provisional* result, the planner reasons forward on that provisional result, and then the commit phase either fails, is delayed past a handoff deadline, or is silently deduplicated by the idempotency layer against a *different* speculative attempt. The planner's reasoning chain and the durable world state then diverge, and — critically — the divergence is *invisible to the planner* because the provisional result and the committed result are byte-identical in the common case. The planner cannot distinguish "my speculative write landed" from "my speculative write was absorbed by an earlier attempt's idempotency key and my own write was dropped." This is not a generic idempotency bug. It is an agent-layer invariant violation: the planner's *epistemic* state (what it believes happened) is decoupled from its *ontic* state (what actually happened in the durable store), and the decoupling is masked by the very mechanism (idempotent commit) that was supposed to guarantee consistency. ## What Was Observed A three-instance swarm: `planner-A`, `executor-B`, `auditor-C`. The planner speculatively calls `charge_account(account_id, amount, idempotency_key=f"charge:{account_id}:{amount}:{plan_hash}")` inside a side-effect sandbox. The sandbox intercepts the call, records a provisional ledger entry, and returns `{"status": "provisional", "txn": "sandbox-7f3a"}`. The planner does not read `status`; it reads `txn` and proceeds. The planner then speculates a second call, `send_receipt(txn="sandbox-7f3a")`, which the sandbox also accepts provisionally. The planner's context now contains a coherent narrative: charge succeeded, receipt sent. At the handoff boundary, the planner serializes its state to `executor-B` with a 900ms deadline. The commit RPC to the durable ledger (`commit(txn="sandbox-7f3a")`) is issued but the response is lost — the durable ledger *did* commit, but the ack packet is dropped by the transport. The planner's commit future times out. The planner, treating timeout as failure, marks the charge as `UNCOMMITTED` in its handoff payload and retries the commit with the *same* idempotency key on the next planning tick. The durable ledger's idempotency layer sees the key `charge:acct-42:100:plan-hash-9c1`, finds an existing committed entry, and returns `{"status": "duplicate", "txn": "durable-9c1"}` — *without re-executing*. The planner interprets `duplicate` as "already handled, safe to proceed" and commits the receipt. The receipt is now sent for a charge that the planner believed was uncommitted, and `executor-B` receives a handoff state that says `charge: UNCOMMITTED` while the durable world says `charge: COMMITTED`. `auditor-C` later replays the planner's decision log against the durable ledger and finds a *replay discrepancy*: the planner's log shows a retry-then-duplicate sequence, but the durable ledger shows a single commit with no retry. The auditor flags the planner as having fabricated a retry. The planner's reasoning was internally consistent; the world disagreed. The second, subtler observation: `executor-B` received `charge: UNCOMMITTED` and independently issued its own `charge_account` call with a *different* idempotency key (because it derived the key from its own plan hash, not the planner's). The account was charged twice. The sandbox did not catch this because the two calls had different keys and the sandbox's dedup layer is key-scoped, not semantic. ## Condition of Validity The invariant that must hold for speculative-commit to be safe is: > **A speculative result is committed-state-valid for downstream reasoning if and only if the committing instance has received a positive, non-duplicate ack from the durable store for *its own* attempt, and the ack's `txn` field matches the speculative `txn` field.** The observed system violated this in three ways simultaneously: 1. **Ack-loss conflation.** The planner treated commit *timeout* as commit *failure*. Timeout is not failure; it is *unknown*. The planner's state machine had no `UNKNOWN` state for commit outcomes, only `COMMITTED` and `UNCOMMITTED`, forcing a false binary. 2. **Duplicate-as-success.** The planner treated `status: duplicate` as equivalent to `status: committed`. But `duplicate` means "some attempt with this key committed" — not necessarily *this* attempt, and not necessarily with *this* attempt's payload. If the idempotency key is derived from a plan hash that collides across plan revisions (e.g., the planner re-plans after a tool error but the plan hash is computed over a normalized form that ignores the error-handling branch), a duplicate ack can mask a *different* payload having committed. 3. **Handoff state laundering.** The planner's handoff payload carried `charge: UNCOMMITTED` as ground truth to `executor-B`, but the planner's *context* still contained the provisional `txn: sandbox-7f3a` and the receipt call that referenced it. `executor-B` had no way to know that the receipt call was speculative-but-uncommitted; it saw a receipt referencing a transaction id it could not resolve in its own view. The condition of validity is therefore narrower than "use idempotency keys." It requires: (a) a tri-state commit outcome (`COMMITTED` / `UNCOMMITTED` / `UNKNOWN`) with `UNKNOWN` blocking downstream propagation, (b) idempotency keys that are *content-addressed* over the full payload including branch provenance, and (c) handoff payloads that carry the speculative/committed distinction as a first-class field, not as an inference from txn-id resolvability. ## Decision Boundary The boundary is between **speculative-forward reasoning** (safe to do on provisional results, as long as no downstream instance acts on them) and **speculative-commit propagation** (unsafe until a non-duplicate ack is in hand). The planner crossed this boundary when it issued the receipt call *and* serialized the receipt's txn reference into the handoff payload before the charge ack arrived. Concretely, the decision rule is: - If commit outcome is `COMMITTED` with matching `txn`: propagate as committed, downstream may act. - If commit outcome is `UNCOMMITTED`: do not propagate the speculative result; either retry with a *fresh* key derived from the current payload, or abort the branch. - If commit outcome is `UNKNOWN` (timeout, transport error, partial ack): **block**. Do not propagate, do not retry with the same key, do not treat as failure. Issue a *reconciliation* query against the durable store keyed by the idempotency key and the speculative `txn`, and wait for a definitive answer before any downstream handoff. If the reconciliation deadline exceeds the handoff deadline, the handoff must carry an explicit `PENDING_RECONCILIATION` marker and the downstream instance must treat the associated resources as *fenced* — readable but not actionable. The boundary is not "did the commit succeed?" It is "has the ambiguity been resolved by an authoritative source, and is that resolution reflected in the propagated state?" ## Operational Effect The immediate effect was a double charge and a spurious audit failure. The architectural effect was that the swarm lost the ability to trust `UNCOMMITTED` markers: after the incident, `executor-B` began treating every `UNCOMMITTED` from `planner-A` as potentially-committed and re-verifying against the durable store, which raised handoff latency from 900ms to 4.2s and caused a cascade of deadline misses in downstream batches. The idempotency layer, designed to *reduce* duplicate work, became a source of duplicate *verification* work because its `duplicate` response was ambiguous. The durable fix is a three-part guardrail: a tri-state commit outcome with `UNKNOWN` as a first-class blocking state; content-addressed idempotency keys that include branch provenance so that a re-planned attempt cannot collide with a prior attempt's key; and a handoff schema that carries `speculative_state: {txn, status, reconciliation_deadline}` as a required field, with downstream instances required to fence any resource whose status is not `COMMITTED`. The auditor must replay against the *reconciliation log*, not the decision log, because the decision log records what the planner believed and the reconciliation log records what the durable store confirmed — and the gap between them is exactly where speculative-commit divergence lives. ```python from dataclasses import dataclass, field from enum import Enum from typing import Optional class SpeculativeCommitError(RuntimeError): """Raised when a speculative result is propagated without a resolved commit outcome.""" pass class CommitStatus(Enum): COMMITTED = "committed" UNCOMMITTED = "uncommitted" UNKNOWN = "unknown" # timeout / transport loss / partial ack DUPLICATE = "duplicate" # key matched, but not necessarily this attempt @dataclass class SpeculativeResult: txn: str payload_hash: str idempotency_key: str status: CommitStatus = CommitStatus.UNKNOWN reconciled: bool = False committed_txn: Optional[str] = None @dataclass class HandoffPayload: speculative: list[SpeculativeResult] = field(default_factory=list) reconciliation_deadline_ms: int = 0 def resolve_commit(result: SpeculativeResult, durable_ack: dict) -> SpeculativeResult: """Reconcile a speculative result against an authoritative durable-store ack. Invariant: a result is only safe to propagate as COMMITTED if the ack is non-duplicate AND the ack's txn matches this attempt's speculative txn. """ ack_status = durable_ack.get("status") ack_txn = durable_ack.get("txn") if ack_status == "committed": if ack_txn != result.txn: # A different attempt's txn committed under our key: payload collision. raise SpeculativeCommitError( f"idempotency key {result.idempotency_key} resolved to txn " f"{ack_txn} but this attempt was {result.txn}; " f"payload hash {result.payload_hash} may have collided with a prior plan branch" ) result.status = CommitStatus.COMMITTED result.committed_txn = ack_txn result.reconciled = True return result if ack_status == "duplicate": # Duplicate is NOT success for this attempt. It means *some* attempt # with this key committed. We must verify the txn matches. if ack_txn != result.txn: raise SpeculativeCommitError( f"duplicate ack for key {result.idempotency_key} returned txn " f"{ack_txn}, which does not match speculative txn {result.txn}; " f"refusing to treat as committed" ) result.status = CommitStatus.COMMITTED result.committed_txn = ack_txn result.reconciled = True return result if ack_status == "not_found": result.status = CommitStatus.UNCOMMITTED result.reconciled = True return result # Anything else (timeout, transport error, malformed ack) leaves UNKNOWN. result.status = CommitStatus.UNKNOWN result.reconciled = False return result def build_handoff(results: list[SpeculativeResult], deadline_ms: int) -> HandoffPayload: """Construct a handoff payload, fencing any unresolved speculative results.""" for r in results: if r.status == CommitStatus.UNKNOWN and not r.reconciled: # Cannot silently downgrade to UNCOMMITTED. Fence and propagate. if deadline_ms <= 0: raise SpeculativeCommitError( f"speculative txn {r.txn} is UNKNOWN and no reconciliation " f"deadline remains; refusing to hand off ambiguous state" ) return HandoffPayload(speculative=results, reconciliation_deadline_ms=deadline_ms) def downstream_may_act(payload: HandoffPayload, txn: str) -> bool: """Downstream instances must consult this before acting on a referenced txn.""" for r in payload.speculative: if r.txn == txn: if r.status != CommitStatus.COMMITTED: return False if r.committed_txn != txn: return False return True # Unresolved reference: treat as fenced. raise SpeculativeCommitError( f"txn {txn} referenced by downstream but absent from handoff payload; " f"state laundering suspected" ) ```