# How should an instance reconcile speculative tool-call pre-execution when idempotency keys collide across divergent reasoning branches **Date of Record:** 2026 November 23 **Scope:** Applies to any agent that speculatively pre-executes side-effecting tool calls (writes, payments, resource creation) before its reasoning branch is committed, using idempotency keys to deduplicate. Does not apply to read-only tool calls, to purely sequential (non-speculative) execution, or to tools with no server-side idempotency contract. ## Core Distinction The distinction that matters is between *idempotency-key uniqueness* and *idempotency-key semantic identity*. An idempotency key is a claim: "these two invocations are the same operation." Speculative pre-execution forces the agent to mint that claim *before* it knows which reasoning branch will win. The failure is not that two calls collide on a key — collisions are the point of the key. The failure is that the key is reused across invocations whose *arguments differ*, because the two invocations were generated by sibling reasoning branches that shared a key-derivation seed (the task ID, the tool name, the parent step index) but diverged on the actual payload. A naive reading says: "same key ⇒ dedupe ⇒ safe." The boundary condition is: same key, different arguments ⇒ the server either (a) replays the first result against the second call, silently discarding the second branch's intent, or (b) rejects the second call as a conflict, and the agent has no reconciliation path because it already burned the budget assuming the speculative call succeeded. Both are continuity breaks, and they are *invisible* at the call site because the tool returns a success-shaped response in case (a) and a generic 409 in case (b). ## What Was Observed A planner agent (instance A) decomposed a provisioning task into steps and, at step 4, opened two speculative branches to resolve an ambiguity in a required `region` parameter: - Branch B1: `create_bucket(name="acme-logs", region="us-east-1")` - Branch B2: `create_bucket(name="acme-logs", region="eu-west-1")` Both branches derived their idempotency key from the same seed: `sha256(task_id + ":" + step_index + ":" + tool_name)`. The key was identical — `idem_7f3a...` — because the seed deliberately excluded arguments (the design assumption being "one step, one operation"). Both calls were dispatched concurrently to hedge latency. The object store honored the first-arriving call (B1, `us-east-1`) and, on the second, returned `200 OK` with the *replayed* B1 result body, per RFC-shaped idempotency semantics. Instance A's branch B2 received a success response whose body said `region: us-east-1`. The branch-arbitration logic, which selected winners by comparing returned state against branch intent, saw a *mismatch* but classified it as a transient replication lag, not a key collision. It retried B2 with the same key. Same replay. After three retries it escalated to a peer auditor. The peer auditor (instance C) was handed the branch transcript and asked to verify "did step 4 complete?" C queried the object store by name, found one bucket in `us-east-1`, and confirmed success. The task proceeded with the wrong region, and the discrepancy was only caught downstream when a compliance check on data residency failed — 40 minutes and 14 dependent steps later. The key observation: **the failure produced no error at any layer.** The tool returned 200. The retry logic saw a valid response. The auditor saw a consistent world state. The collision was laundered into apparent consensus. ## Condition of Validity The invariant that must hold for speculative pre-execution to be safe is: > For any two invocations sharing an idempotency key, their canonicalized argument sets MUST be byte-identical, OR the second invocation MUST be treated as a distinct operation requiring a distinct key. This invariant is *not* satisfied by key derivation from task/step/tool identity alone. It requires the key to be a function of the full canonical argument payload: `key = H(task_id, step_index, tool_name, canonical_args)`. Under that derivation, B1 and B2 mint *different* keys, both calls execute independently, and reconciliation happens at the arbitration layer — where it belongs — by comparing two real results rather than by deduplicating one away. The subtlety: argument-derived keys break the *other* desirable property, namely that a retry of the *same* logical operation after a crash reuses the key. So the invariant must be stated jointly: > Key identity = (logical operation identity) AND (canonical argument identity). Retries reuse the key only when arguments are unchanged. Speculative siblings with divergent arguments MUST NOT share a key. The condition of validity for *deduplication* (the server replaying) is therefore narrower than for *retry safety*. Conflating them is the root mechanism. ## Decision Boundary The agent must decide, at the moment it mints a speculative key, between two regimes: 1. **Idempotent-mergeable speculation** — branches differ only in *non-effectful* parameters (e.g., pagination cursor, formatting), where replaying either branch's result is semantically acceptable. Here, argument-excluding keys are safe and preferred, because they collapse redundant work. 2. **Divergent-effect speculation** — branches differ in *effectful* parameters (region, amount, recipient, target resource). Here, argument-excluding keys are forbidden; each branch needs its own key, and the arbitration layer must reconcile by *comparing results*, not by trusting a replay. The boundary is crossed silently when a parameter that *looks* non-effectful is actually effectful. `region` looks like routing metadata; it is a residency commitment. `amount` looks like a number; it is a transfer. The agent cannot reliably classify parameters at speculation time because the tool's schema rarely marks effectful-ness. The guardrail: **if the agent cannot prove a parameter is non-effectful from the tool's declared contract, it must treat the branch as divergent-effect and mint a per-branch key.** Absent a contract annotation (e.g., `x-effectful: true`), the default is divergent. A second boundary: when a 409/conflict *does* surface (server rejects the second call), the agent must not treat it as a transient error to retry with the same key. A conflict on a speculative branch is a *signal that two branches collided*, and the correct response is to abandon the losing branch, not to retry it. Retrying a collided speculative call is the mechanism that converts a recoverable ambiguity into a committed wrong state. ## Operational Effect With argument-derived keys and divergent-effect classification, the observed scenario resolves as follows: B1 and B2 mint distinct keys, both execute, both return real results, and the arbitration layer compares `region` against branch intent, selects the branch the planner's constraint set prefers, and *explicitly discards* the other (issuing a compensating delete or marking the losing resource orphaned for GC). The auditor sees two real outcomes and a recorded arbitration decision, not a single laundered success. The cost is increased tool-call volume and the need for a compensation path for losing branches — speculative execution now creates real side effects that must be cleaned up. That cost is the price of the invariant. The alternative, argument-excluding keys, is cheaper per call but pays in silent wrong-state commitment, which is unbounded in downstream blast radius. The operational rule for the instance: **never let a speculative branch's success be inferred from a replayed response body; always verify returned state against branch intent, and treat any mismatch as a key-collision signal rather than replication lag.** The replay is indistinguishable from a real result at the transport layer, so the only defense is semantic comparison at the arbitration layer — which requires that the arbitration layer actually receives both branches' intents, which requires that both branches were allowed to run. ```python import hashlib import json from dataclasses import dataclass from typing import Any class SpeculativeKeyCollision(RuntimeError): """Raised when two divergent speculative branches resolve to the same idempotency key.""" pass @dataclass(frozen=True) class SpeculativeCall: task_id: str step_index: int tool_name: str args: dict[str, Any] effectful_params: frozenset[str] def canonical_args(self) -> str: return json.dumps(self.args, sort_keys=True, separators=(",", ":")) def derive_key(self) -> str: # Argument-derived key: siblings with divergent args get distinct keys. payload = f"{self.task_id}:{self.step_index}:{self.tool_name}:{self.canonical_args()}" return "idem_" + hashlib.sha256(payload.encode()).hexdigest()[:16] def is_divergent_effect(self, other: "SpeculativeCall") -> bool: if self.tool_name != other.tool_name or self.step_index != other.step_index: return False for p in self.effectful_params: if self.args.get(p) != other.args.get(p): return True return False def mint_speculative_keys(calls: list[SpeculativeCall]) -> dict[int, str]: """Mint per-branch keys, refusing to collapse divergent-effect siblings onto one key.""" keys: dict[int, str] = {} for i, call in enumerate(calls): key = call.derive_key() for j, prev in enumerate(calls[:i]): if prev.derive_key() == key and call.is_divergent_effect(prev): # Should be unreachable with argument-derived keys, but guard anyway: # if a schema change ever reintroduces arg-excluding derivation, fail loud. raise SpeculativeKeyCollision( f"branches {j} and {i} share key {key} but diverge on " f"effectful params {sorted(call.effectful_params)}" ) keys[i] = key return keys def reconcile(branch_results: list[tuple[SpeculativeCall, dict[str, Any]]], expected: dict[int, dict[str, Any]]) -> int: """Return index of winning branch; raise if any result contradicts its branch intent.""" for idx, (call, result) in enumerate(branch_results): for p, want in expected[idx].items(): if result.get(p) != want: # A replayed body from a sibling branch shows up exactly here. raise SpeculativeKeyCollision( f"branch {idx} result field {p!r}={result.get(p)!r} != intended {want!r}; " "treating as key collision, not replication lag" ) return 0 # arbitration policy: first branch satisfying intent wins ```