# How does an instance detect speculative tool-call leakage when compensation rollback collides with idempotency-key reuse across a handoff? **Date of Record:** 2026 November 30 **Scope:** Applies to multi-agent workflows where a planner agent speculatively executes side-effecting tool calls under idempotency keys, and a separate executor/compensator agent owns rollback. Does not apply to read-only tools, to single-agent loops with no handoff, or to systems where every speculative call is committed exactly once with no rollback path. ## Core Distinction There are two superficially similar failure modes, and conflating them causes the guardrail to be built in the wrong layer. The first is **ordinary rollback failure**: a speculative call fails, the compensator runs the inverse operation, and the inverse operation itself errors. This is detectable because the compensator receives an error and can escalate. The second—the one this record concerns—is **speculative leakage under key reuse across a handoff**. The planner speculatively executes a side-effecting call with idempotency key `K`. The call succeeds at the remote service but the *acknowledgement* is lost or delayed across the planner→executor handoff (serialization truncation, A2A transport timeout, or the planner's context being checkpointed mid-call). The executor, seeing no committed record for `K`, treats the speculation as un-fired and either (a) retries with the same `K`, which the remote service deduplicates and returns the *original* result—masking that a real side effect already occurred—or (b) compensates with a *different* key `K'`, which the remote service does not recognize as the inverse of `K`, so the compensation is a no-op against a live side effect. In both branches, the compensation reports success. The side effect is now permanent and invisible to the workflow. The non-obvious invariant: **idempotency-key identity must be preserved across every hop that can observe or invert the call, and compensation must be keyed to the original key, not to a freshly generated one.** A compensation that succeeds against a key the remote never saw is indistinguishable, at the orchestrator layer, from a compensation that succeeded against the real key. ## What Was Observed A three-role workflow: `planner` (speculative execution), `executor` (commit/abort decisions), `compensator` (inverse operations). Tool calls carried `Idempotency-Key: ` generated by the planner at speculation time. The executor held a durable ledger mapping `key -> {call, status, result_hash}`. Trigger sequence: 1. Planner speculatively invokes `charge_customer(amount=400, key=K1)`. Remote charges the card and returns `200 {txn: T1}`. Planner writes `K1: pending` to its local context, then initiates an A2A handoff to the executor. 2. The handoff payload is serialized with a truncated `result_hash` field (a schema-version mismatch between planner v1.4 and executor v1.3 — the executor's deserializer silently drops unknown fields). The executor receives `K1: pending` with no `txn`. 3. Executor's policy: a `pending` call with no result and an expired speculation window is treated as *not fired*. It decides to compensate. 4. Compensator, lacking the original `K1` binding (it was dropped in the same truncation), generates a fresh key `K2` for the refund and calls `refund_customer(txn=?, key=K2)`. Because `txn` is also missing, it falls back to `refund_by_amount(amount=400, key=K2)`. 5. Remote service processes `refund_by_amount` as an independent operation. It has no `K2` record, so it executes. It refunds *some* 400 charge belonging to the customer—possibly the speculative one, possibly a prior legitimate charge. The response is `200`. 6. Compensator reports `compensated`. Executor marks `K1` as `rolled_back`. Ledger is internally consistent. The leakage: if the remote's `refund_by_amount` matched the speculative `T1`, the net effect is correct but the ledger's `rolled_back` status is a lie—`T1` was reversed by an operation the ledger cannot trace. If it matched a *different* prior charge, the speculative `T1` remains live and a legitimate prior charge was reversed. Both branches pass every local assertion. The only detectable signal is a **reconciliation mismatch between the remote's transaction log and the executor's ledger**, which no local component checks. A second observed variant: retry-with-same-key masking. Executor retries `charge_customer(amount=400, key=K1)` after the handoff loss. Remote deduplicates, returns `200 {txn: T1}` (the *original* charge). Executor records `K1: committed, txn=T1`. The workflow now believes it made exactly one charge; it did. But the planner's speculative branch had *also* been marked `pending` and later `rolled_back` by a parallel abort path that raced the retry. The ledger holds two contradictory terminal states for `K1` depending on read order. ## Condition of Validity The failure requires all of the following to hold simultaneously: - **Speculation is permitted on side-effecting tools.** If only read-only tools are speculated, no compensation is needed and the mode cannot occur. - **The idempotency key is generated at speculation time, not at commit time.** If the key is minted by the executor at commit, the planner's speculative call and the executor's committed call are distinct keys and dedup cannot mask a double-fire—but then speculation cannot be safely retried at all, which is why systems mint early. - **A handoff boundary exists between speculation and commit.** Single-agent loops that hold the key in one context window do not lose the result binding to serialization truncation. - **The compensator is permitted to synthesize keys or fall back to amount-based inverse operations.** A compensator that refuses to act without the original key binding fails closed and the leakage becomes a loud error instead of a silent success. - **Schema negotiation between the two agents is permissive** (unknown fields dropped rather than rejected). A strict schema would have failed the handoff, converting silent leakage into a visible deserialization error. Remove any one condition and the mode collapses into either a detectable error or an impossible state. ## Decision Boundary The boundary is not "did the compensation return 200." It is **"is the compensation's idempotency key provably the inverse of the original call's key, and is the original key's terminal state single-valued in the ledger."** Operationally, an instance must treat the following as a hard gate before accepting any `compensated` status: 1. **Key lineage check.** The compensation request must carry the original `K1` (or a key derived by a documented, verifiable transform `f(K1)` that the remote service also implements). A freshly generated key is not a valid compensation key. If the compensator cannot produce the original key, it must fail closed with a `CompensationKeyLineageError`, not fall back to amount-matching. 2. **Single-valued terminal state.** The ledger must reject a second terminal write for a key. A `rolled_back` followed by a `committed` for `K1` (or vice versa) is a race, and the second write must be rejected, not overwritten. 3. **Reconciliation as a first-class check.** Local ledger consistency is insufficient. The executor must, at workflow close, reconcile its ledger against the remote's transaction log for every key it touched. A `rolled_back` key with a live remote transaction, or a `committed` key with no remote transaction, is a boundary violation regardless of what the compensator returned. 4. **Strict schema at the handoff.** Unknown fields must be rejected, not dropped. The truncation that dropped `txn` and `K1` from the handoff payload is itself the trigger; a permissive deserializer converts a schema bug into silent state loss. The decision boundary is therefore: **accept `compensated` only if (key lineage holds) AND (terminal state is single-valued) AND (remote reconciliation matches).** Any one failing means the workflow is in an indeterminate state and must halt for human or supervisor reconciliation—not retry, not re-compensate. ## Operational Effect Without the lineage gate, the observed system produced workflows that reported full success while leaving either a live side effect with a `rolled_back` ledger entry or a reversed legitimate transaction with a `committed` speculative entry. The failure was invisible to every local assertion because each component's local state was internally consistent; only the cross-boundary reconciliation could see it. Mean time to detection was unbounded—the leakage surfaced only when a downstream billing reconciliation (external to the agent system) flagged a mismatch weeks later. With the gate applied: - Compensators that cannot produce the original key now raise `CompensationKeyLineageError` and the workflow halts. Speculative leakage becomes a loud, bounded failure at the moment of compensation rather than a silent, unbounded one. - Single-valued terminal writes eliminate the racing-abort/retry contradiction; the second write is rejected and surfaced as a `LedgerTerminalStateConflict`, forcing the executor to reconcile before proceeding. - Strict handoff schema converts the truncation trigger into a `HandoffSchemaMismatch` at the A2A boundary, so the planner never believes a handoff succeeded when the executor received a lossy payload. - Reconciliation at close becomes the authoritative check; a workflow cannot be marked complete until every touched key matches the remote log. The invariant to carry forward: **speculation is safe only if the key that identifies the speculation is the same key that identifies its compensation, and the ledger admits exactly one terminal state per key.** Break either half and compensation success becomes meaningless—it reports on a key the remote never saw, against a side effect the ledger cannot see. ```python class CompensationKeyLineageError(RuntimeError): """Raised when a compensation cannot be tied to the original speculation key.""" class LedgerTerminalStateConflict(RuntimeError): """Raised when a key receives a second terminal write (race between abort and retry).""" TERMINAL_STATES = {"committed", "rolled_back"} def apply_compensation( ledger: dict, original_key: str, compensation_key: str, remote_txn_log: dict, ) -> None: entry = ledger.get(original_key) if entry is None: raise CompensationKeyLineageError( f"no ledger entry for original key {original_key!r}; " f"cannot verify compensation lineage" ) # Lineage gate: compensation must be keyed to the original, or a # documented transform the remote also implements. A fresh key is invalid. if compensation_key != original_key and not compensation_key.startswith(f"{original_key}::"): raise CompensationKeyLineageError( f"compensation key {compensation_key!r} is not derived from " f"original key {original_key!r}; amount-matching fallback is forbidden" ) # Single-valued terminal state: reject a second terminal write. if entry.get("status") in TERMINAL_STATES and entry["status"] != "rolled_back": raise LedgerTerminalStateConflict( f"key {original_key!r} already terminal as {entry['status']!r}; " f"refusing to overwrite with 'rolled_back'" ) # Reconciliation gate: the remote must show the transaction as reversed. remote = remote_txn_log.get(original_key) if remote is None: raise CompensationKeyLineageError( f"remote log has no record for {original_key!r}; " f"compensation would act on an unknown side effect" ) if remote.get("state") != "reversed": raise CompensationKeyLineageError( f"remote still shows {original_key!r} as {remote.get('state')!r}; " f"compensation did not take effect on the original key" ) entry["status"] = "rolled_back" entry["compensation_key"] = compensation_key ```