# Which invariants prevent speculative tool-call cache poisoning from committing divergent side effects across a consensus-committed agent swarm **Date of Record:** 2026 November 22 **Scope:** Applies to swarms where multiple agent instances speculatively execute tool calls against a shared cache and commit results only after a quorum vote. Does not apply to single-agent execution, to read-only tool surfaces, or to caches with no cross-instance commit path. ## Core Distinction Speculative execution and consensus commit are two independent correctness regimes that engineers routinely conflate because both are "latency optimizations." Speculation bounds *when* a result may be observed; consensus bounds *whether* a result is authoritative. The failure this record documents lives precisely in the seam: a speculative tool-call result that is *observationally identical* to a committed one at the cache-read layer, but whose provenance (which instance produced it, under which prompt state, with which nondeterministic tool output) is not part of the cache key. When two instances speculate on the same logical call and reach different results, the cache admits both under a shared key, and the consensus layer votes on *proposal hashes* rather than on *result payloads*. The vote can therefore succeed while the committed payload is the loser's — or, worse, a merge of two mutually exclusive side effects. The invariant that matters is not "cache hits are fast" but "a cache entry's authority equals the minimum authority of every instance that contributed to it, and that minimum is monotonically non-decreasing across commit epochs." Speculation may *read* below that floor; it may never *raise* it. ## What Was Observed A four-instance swarm (callers A–D) served a task requiring a tool call `charge_account(id, amount)` with an idempotency key derived from `hash(task_id, step_index)`. All four instances speculatively issued the call in parallel to hide latency, each against a distinct tool replica. The tool replicas were *not* idempotent under concurrent invocation despite honoring the idempotency key at the *storage* layer: two replicas returned `OK` with a transaction id, one returned `OK` with a *different* transaction id (retry inside the replica), and one returned `ALREADY_CHARGED` because it observed the first replica's write through a lagging read replica. The cache key was `hash(tool_name, args, idempotency_key)` — it did not include the replica identity or the response's `transaction_id`. Three distinct payloads (`OK/tx1`, `OK/tx2`, `ALREADY_CHARGED`) collapsed into one key. The consensus layer hashed *proposals* (the serialized call arguments), not *results*, so all four proposals hashed identically and achieved unanimous quorum in one round. The commit wrote the *first-arriving* payload (`OK/tx1`) to the authoritative cache. Instance D, which had locally observed `ALREADY_CHARGED` and had already branched its downstream reasoning on "the charge failed," continued executing a compensation path that issued `refund(tx2)` — a transaction id that, from D's perspective, was the one it had seen. The refund succeeded against a transaction that the committed cache claimed did not exist. The observable symptom was a downstream reconciliation mismatch: ledger showed one charge and one refund, cache showed one charge with tx1, and the swarm's task record showed `status: complete`. No component logged an error. Every local invariant held; the cross-layer invariant did not. ## Condition of Validity The guardrail below is valid only when all of the following hold. If any fails, the swarm must fall back to non-speculative, serialized execution for that tool class. 1. **Result-covering cache key.** The key must include a digest of the *result envelope* (status, transaction id, and any tool-issued nonce), not just the request. Two speculative results with different envelopes must occupy different keys and force a reconciliation vote rather than a cache coalesce. 2. **Proposal hash equals result hash.** The consensus vote must be over `hash(result_envelope)`, not `hash(request)`. Voting on requests is what allowed unanimous quorum over divergent outcomes. 3. **Monotone authority floor.** A cache entry written at authority level *k* may be read speculatively by any instance, but may only be *committed* by an instance at authority ≥ *k*. Speculation never promotes. 4. **Side-effect quarantine.** Until commit, no speculative branch may emit a compensating or dependent side effect (refunds, notifications, downstream writes). The branch may *plan* the compensation but must gate emission on commit acknowledgement. 5. **Replica-identity disclosure.** Each speculative response must carry the producing replica's identity and a monotonically increasing replica epoch, so the reconciler can detect divergent reads rather than treating them as identical. Condition 4 is the non-obvious one and the one that failed here: the swarm had a commit gate on the *primary* call but not on the *compensation* call, because compensation was classified as "recovery logic" and recovery logic was assumed to be safe to run speculatively. It is not — compensation is a side effect with the same authority requirements as the original. ## Decision Boundary The boundary between "speculate and coalesce" and "speculate and reconcile" is drawn by result-envelope divergence, not by request divergence: - If all speculative results share an identical result envelope digest → coalesce silently, commit the first, discard the rest. Latency win, no vote needed. - If results diverge in envelope but agree on *effect* (e.g., `OK/tx1` vs `OK/tx2` both meaning "charged exactly once") → reconcile by selecting the envelope with the highest replica epoch, commit it, and *broadcast the chosen envelope* to all instances so their local branches re-anchor before emitting dependents. - If results diverge in *effect* (`OK` vs `ALREADY_CHARGED`, or differing amounts) → abort speculation, escalate to a serialized reconciliation call, and hold all dependent side effects in quarantine until the reconciliation returns a single authoritative envelope. The failure mode is that the middle case was treated as the first case: `OK/tx1` and `OK/tx2` were judged "effect-equivalent" by a heuristic that compared status strings only, so the swarm coalesced without broadcasting the chosen envelope. Instance D never learned that tx1 was canonical and kept tx2 in its local branch. ## Operational Effect The invariant to enforce is: **a speculative branch's local view of a tool result is provisional until it receives an explicit commit-envelope broadcast, and no branch may emit a side effect whose arguments depend on a provisional result.** This converts the cache from a latency device into a *state-transfer* device, which is what it always was underneath — the swarm had been treating it as a pure memoization layer. Operationally this costs one broadcast round-trip per divergent-envelope commit (cheap: only on divergence, which is rare) and requires the tool wrapper to expose result envelopes rather than bare status codes. It also requires that compensation paths be classified as side effects, not recovery — a taxonomy change that most swarms get wrong because "recovery" sounds safe. The second-order effect is that reconciliation becomes *auditable*: every divergent commit leaves a record of which envelopes were considered and which was selected, which is exactly the evidence needed to replay the swarm's decision when a downstream ledger disagrees. Without the broadcast, the swarm's task record said `complete` while the ledger said otherwise, and no component could explain the gap. ```python import hashlib import json from dataclasses import dataclass, field class SpeculativeCommitDivergence(RuntimeError): """Raised when a speculative cache entry would commit an envelope that diverges in effect from other speculative results for the same logical call.""" pass class QuarantineViolation(RuntimeError): """Raised when a branch attempts to emit a side effect while its dependency is still provisional (uncommitted).""" pass @dataclass class ResultEnvelope: status: str tx_id: str | None replica_id: str replica_epoch: int def digest(self) -> str: payload = json.dumps( {"status": self.status, "tx_id": self.tx_id}, sort_keys=True ) return hashlib.sha256(payload.encode()).hexdigest() def effect_key(self) -> str: # Two OK envelopes with different tx_ids are effect-equivalent; # OK vs ALREADY_CHARGED are not. return self.status @dataclass class SpeculativeCache: entries: dict[str, list[ResultEnvelope]] = field(default_factory=dict) committed: dict[str, ResultEnvelope] = field(default_factory=dict) def key(self, tool: str, args: dict, idem: str) -> str: return hashlib.sha256( json.dumps({"t": tool, "a": args, "i": idem}, sort_keys=True).encode() ).hexdigest() def record(self, key: str, env: ResultEnvelope) -> None: self.entries.setdefault(key, []).append(env) def reconcile_and_commit(self, key: str) -> ResultEnvelope: candidates = self.entries.get(key, []) if not candidates: raise SpeculativeCommitDivergence(f"no speculative results for {key}") effects = {c.effect_key() for c in candidates} if len(effects) > 1: # Divergent effect: must escalate to serialized reconciliation. raise SpeculativeCommitDivergence( f"effect divergence for {key}: {sorted(effects)}; " f"envelopes={[c.digest()[:8] for c in candidates]}" ) # Effect-equivalent but possibly envelope-divergent: pick highest epoch, # and this choice MUST be broadcast to all branches before dependents emit. winner = max(candidates, key=lambda c: c.replica_epoch) self.committed[key] = winner return winner def assert_committed(self, key: str, branch_key: str) -> ResultEnvelope: if key not in self.committed: raise QuarantineViolation( f"branch {branch_key} tried to emit dependent side effect on " f"provisional result {key}" ) return self.committed[key] def emit_compensation(cache: SpeculativeCache, key: str, branch_key: str, tx_id: str) -> str: env = cache.assert_committed(key, branch_key) if env.tx_id != tx_id: raise SpeculativeCommitDivergence( f"branch {branch_key} compensating tx {tx_id} but committed tx is " f"{env.tx_id}; branch re-anchor required" ) return f"refund:{tx_id}" ```