# How does an instance detect speculative tool-call divergence when idempotency tokens collide across merged agent branches? **Date of Record:** 2026 November 27 **Scope:** Applies to agent runtimes that (a) speculatively execute tool calls before the enclosing plan branch commits, (b) deduplicate side effects via idempotency tokens, and (c) merge divergent sibling branches (e.g., parallel sub-agents, speculative beam branches) into a single committed state. Does not apply to strictly sequential single-branch agents with no speculative execution, nor to idempotency schemes scoped only to a single process lifetime. ## Core Distinction There are two distinct notions of "the same tool call," and conflating them is the root of this failure mode. The first is **semantic identity**: two invocations that intend the same effect (same tool, same logical arguments, same target resource). The second is **idempotency identity**: the token that the downstream system uses to collapse retries into one committed effect. Speculative execution breaks the assumption that these two identities are 1:1. When a planner forks into sibling branches, each branch independently derives an idempotency token for what *looks* like the same call. If the token derivation is deterministic over `(tool, args)`, the branches collide — and the merge layer silently treats two genuinely separate speculative intents as one, discarding the loser's result. If the token derivation is randomized per branch, the branches *don't* collide — and the downstream system now commits the side effect twice, because the merge layer has no way to know the two tokens were semantically equivalent. The boundary condition is precisely this: **the idempotency token must be a function of the merge-relevant semantic identity, computed before divergence, not after.** Any token derived inside a branch is either too coarse (collides and loses work) or too fine (duplicates work). There is no per-branch derivation that is correct on both sides of the fork. ## What Was Observed A three-branch speculative planner was asked to "reconcile the customer's billing address across the CRM and the invoice ledger." The planner fanned out into three branches: - **Branch A** read the CRM record and issued `crm.update_contact(address=X)` as the reconciliation write. - **Branch B** read the ledger and issued `ledger.update_billing_address(address=X)`. - **Branch C** was a speculative "verify" branch that re-derived the same reconciliation and, because its retrieval returned the CRM record first, also issued `crm.update_contact(address=X)`. All three branches ran concurrently against a shared tool gateway. The gateway's idempotency layer keyed on `sha256(tool_name + canonical_json(args))`. Branch A and Branch C produced byte-identical canonical arguments, so they produced the same idempotency token `tok_7f3a…`. The gateway correctly collapsed them: the second call returned the cached result of the first. The merge layer then received three branch results. Branch A reported `{status: applied, token: tok_7f3a, prior: "addr_old", next: "X"}`. Branch C reported `{status: applied, token: tok_7f3a, prior: "addr_old", next: "X"}` — identical, because it was the cached response. The merge layer's conflict detector compared the two results, found them equal, and concluded **no conflict**. It committed Branch A's write and dropped Branch C as a redundant duplicate. This was, in this instance, correct. The failure appeared on the *next* task, where the same topology ran with a mutated prompt: Branch C's retrieval this time returned a *stale* CRM snapshot (cached from a prior turn), so its `address` argument was `Y` rather than `X`. Branch C's token was now `tok_9c1e…`, distinct from Branch A's `tok_7f3a…`. The gateway committed **both** writes. Branch A set the address to `X`; Branch C set it to `Y`. The merge layer saw two `applied` results with different tokens and different `next` values, flagged a conflict, and — because the merge policy was "last-writer-wins by branch completion order" — committed `Y`. The ledger branch (B) had already written `X` to the ledger. The final state was CRM=`Y`, ledger=`X`: a split-brain reconciliation that no branch had intended and no branch could observe, because each branch had only seen its own pre-merge view. The detection signal was not in any single branch's result. It was in the *relationship* between the token and the semantic arguments across branches — a relationship that only exists at the merge point. ## Condition of Validity The invariant that bounds this failure is: > **For any two speculative branches `i` and `j` that produce tool calls `c_i` and `c_j`, if `semantic_identity(c_i) == semantic_identity(c_j)` then `idempotency_token(c_i) == idempotency_token(c_j)`, and this equality must be established at the fork point, not at the leaf.** Equivalently: the idempotency token is a property of the *plan node*, not of the *branch execution*. A branch may execute the node at most once; sibling branches executing the same node must share the token by construction, and the merge layer must be able to prove the sharing without re-deriving it from arguments. This holds only under three conditions: 1. **Token derivation is upstream of divergence.** The planner assigns tokens when it emits the tool-call node, before forking. Branches inherit the token; they never mint one. 2. **The merge layer has access to the token-to-node mapping.** A branch result carries `(token, node_id, args, result)`, and the merge layer groups by `node_id`, not by `token` alone. Two results with the same `node_id` but different `args` are a *divergence*, not a duplicate. 3. **Stale inputs cannot silently change `args` under a fixed token.** If a branch's arguments differ from the node's declared arguments, the branch must abort rather than execute — because executing under the node's token with different arguments poisons the idempotency cache for every sibling. Condition 3 is the one that was violated. The branch executed `crm.update_contact(address=Y)` while carrying the plan node's declared intent `address=X`. The gateway, keying on arguments, minted a fresh token and committed the write. The token no longer identified the node; it identified the (node, drifted-args) pair, and the merge layer had no way to recover the node identity from the token alone. ## Decision Boundary The operational decision is what the runtime does at the moment a branch's runtime arguments diverge from its declared node arguments. There are three candidate policies, and only one is safe under speculative merge: - **Execute-and-mint (unsafe).** The branch executes with drifted args and the gateway mints a new token. This is what produced the split-brain. It is only safe if the merge layer can detect post-hoc that two tokens map to the same node — which requires the node_id to be carried in the result, which the failing system did not do. - **Execute-under-declared-token (unsafe).** The branch executes with drifted args but reuses the node's token. This poisons the cache: a sibling with correct args hits the poisoned entry and receives the wrong result. Worse than the first. - **Abort-on-divergence (safe).** The branch detects `runtime_args != declared_args`, raises, and returns a `divergence` result to the merge layer. The merge layer sees `(node_id, divergence)` and either re-plans the node or escalates. No tool call is committed under a token whose arguments it did not declare. The boundary is sharp: **a branch may execute a node zero times or once, but never once with arguments other than the node's declared arguments.** The token is a commitment to the arguments; breaking the commitment breaks the token's meaning. The runtime must therefore carry, per branch, a `declared_args` snapshot taken at fork time, and compare it against `runtime_args` immediately before the tool call. This is a cheap check — canonical JSON equality — but it must be enforced at the *tool-call boundary*, not at plan time, because the drift originates in the branch's own retrieval and reasoning, which happens after the fork. ## Operational Effect With abort-on-divergence enforced, the failure trace changes at exactly one point. Branch C, on detecting that its retrieved `address=Y` differs from the node's declared `address=X`, raises `SpeculativeDivergence` before calling the gateway. The gateway never sees a second token. The merge layer receives `(node_crm_update, divergence)` alongside `(node_crm_update, applied, tok_7f3a)` and `(node_ledger_update, applied, tok_… )`. It groups by node_id, sees one applied and one divergent for the CRM node, and — per policy — either accepts the applied result and discards the divergent branch, or escalates the divergence to a re-plan. In neither case does a second write commit, and the ledger/CRM split-brain cannot occur. The cost is that speculative branches which *would* have produced a useful alternative are aborted rather than merged. This is the correct trade: the merge layer cannot distinguish a useful alternative from a stale-input corruption, because both present as "same node, different args." The information needed to distinguish them (which branch's retrieval was stale) is not available at the merge point and cannot be reconstructed from the results. Aborting preserves the invariant at the cost of speculative coverage; executing preserves coverage at the cost of the invariant. For any system where the downstream side effect is not trivially reversible, the invariant wins. The residual risk is a branch that drifts *and* happens to produce declared-identical arguments — e.g., stale retrieval that returns the same address by coincidence. This is indistinguishable from a correct branch and is benign: the token and arguments agree, the cache collapses correctly, and the merged result is the declared one. The invariant does not require branches to be *correct*, only to be *consistent with their declared commitment*. ```python import hashlib import json from dataclasses import dataclass class SpeculativeDivergence(RuntimeError): """Raised when a branch's runtime tool arguments diverge from the plan node's declared arguments under a fixed idempotency token.""" @dataclass(frozen=True) class PlanNode: node_id: str tool: str declared_args: dict idempotency_token: str # minted at fork point, inherited by branches def mint_token(node_id: str, tool: str, declared_args: dict) -> str: # Token is a function of the PLAN NODE, not of branch execution. payload = json.dumps( {"node_id": node_id, "tool": tool, "args": declared_args}, sort_keys=True, separators=(",", ":"), ) return "tok_" + hashlib.sha256(payload.encode()).hexdigest()[:16] def canonical(args: dict) -> str: return json.dumps(args, sort_keys=True, separators=(",", ":")) def execute_speculative_branch(node: PlanNode, runtime_args: dict) -> dict: # Guard: a branch may execute a node zero or one times, never with # arguments other than the node's declared arguments. if canonical(runtime_args) != canonical(node.declared_args): raise SpeculativeDivergence( f"branch args {canonical(runtime_args)} diverge from declared " f"{canonical(node.declared_args)} for node {node.node_id} " f"(token {node.idempotency_token}); refusing to mint a new token" ) # Safe: arguments match the token's commitment. The gateway may collapse # this call with any sibling carrying the same token. return { "node_id": node.node_id, "token": node.idempotency_token, "args": runtime_args, "status": "applied", } def merge_branches(results: list[dict]) -> dict: # Group by node_id, not by token. Same node + different args is a # divergence, not a duplicate; same node + same args is a safe collapse. by_node: dict[str, list[dict]] = {} for r in results: by_node.setdefault(r["node_id"], []).append(r) merged = {} for node_id, group in by_node.items(): applied = [r for r in group if r["status"] == "applied"] divergent = [r for r in group if r["status"] == "divergence"] if divergent: merged[node_id] = {"state": "diverged", "applied": applied, "divergent": divergent} elif len({canonical(r["args"]) for r in applied}) > 1: # Should be unreachable if the guard held; catch it anyway. raise SpeculativeDivergence( f"merge saw multiple argument sets for node {node_id} " f"without a divergence marker" ) else: merged[node_id] = {"state": "committed", "result": applied[0]} return merged ```