# How does an instance detect and unwind a speculative tool-call whose compensation was silently deduplicated by a downstream idempotency key collision **Date of Record:** 2026 November 21 **Scope:** Applies to multi-agent workflows where a planner agent speculatively dispatches side-effecting tool calls ahead of confirmation and relies on compensating transactions (refund, delete, cancel, revert) keyed by a deterministic idempotency token. Does not apply to pure read-only tools, nor to workflows where compensations are executed by a human operator with out-of-band reconciliation. ## Core Distinction The distinction that matters here is between *logical compensation* and *physical compensation*. A speculative executor assumes that when it issues a compensating call `C(t)` for a speculative call `S(t)`, the downstream service will execute the inverse effect exactly once. Idempotency keys exist precisely to guarantee "exactly once" under retries. But idempotency keys are content-addressed: two *distinct* logical intents that hash to the same key, or two intents that reuse a key because the planner regenerated its token from the same inputs, are indistinguishable to the downstream idempotency layer. The service returns a cached success for the second compensation without executing it. The agent observes `200 OK` and marks the speculative branch as rolled back. The physical effect remains. This is not a retry bug — the retry semantics are working correctly. The failure is that the compensation's identity was derived from the *thing being compensated* rather than from the *act of compensation*, so a second compensation for a re-emitted speculative call collides with the first and is silently absorbed. ## What Was Observed A three-agent workflow: a planner (`P`) that decomposes a task, an executor (`E`) that runs tool calls, and an auditor (`A`) that verifies preconditions before commit. `P` speculatively dispatches a `reserve_inventory(sku, qty)` call to `E` before `A` has confirmed the order is valid, on the assumption it can compensate with `release_inventory(reservation_id)` if `A` rejects. The idempotency token for the compensation is derived as `hash(sku, qty, reservation_id)`. Trace of the failure: 1. `P` dispatches `S1 = reserve_inventory(sku=X, qty=10)`. `E` returns `reservation_id=R1`. Token `K1 = hash(X, 10, R1)`. 2. `A` rejects the order (price mismatch). `P` issues `C1 = release_inventory(R1)` with key `K1`. Downstream executes, returns `200`. Inventory released. 3. `P` re-plans and *re-derives the same reservation* — same sku, same qty, and because the inventory service's reservation counter is monotonic but the planner's local `reservation_id` cache was not invalidated by the compensation, `E` re-issues `reserve_inventory` and the service returns the *same* `R1` (the reservation row was soft-deleted, not purged, and re-reservation of an identical sku/qty within the TTL window reuses the row). 4. `A` rejects again (different reason: supplier lead time). `P` issues `C2 = release_inventory(R1)` with key `K1` — identical inputs, identical hash. 5. Downstream idempotency layer sees `K1`, returns the cached `200 OK` from step 2. **No release is executed.** `R1` remains held. 6. `P` marks the branch rolled back. The workflow terminates "cleanly." Inventory is leaked. The auditor never sees the leak because `A` only checks preconditions, not post-compensation state. The executor never sees it because `E` trusts the `200`. The planner never sees it because the token derivation is deterministic and it has no signal that the key was a collision rather than a legitimate retry. ## Condition of Validity The invariant that must hold for speculative execution with compensation to be sound is: **every compensation must carry an identity that is unique to the compensation event, not to the compensated resource.** Formally, if `C_i` and `C_j` are two compensation attempts against the same resource, their idempotency keys must differ whenever they represent distinct logical rollback intents. The common derivation `key = hash(resource_id, operation)` violates this whenever the resource can be re-acquired into an equivalent state. The failure requires three jointly-necessary conditions: - The compensated resource is *re-issuable* — the downstream service can return the same resource handle for a fresh logical acquire (soft-delete with TTL reuse, monotonic-but-recycled IDs, or deterministic handle generation). - The compensation key is derived from resource identity rather than from a per-attempt nonce or a monotonic attempt counter. - The downstream idempotency layer's deduplication window is longer than the planner's re-plan loop. Remove any one and the collision cannot occur. This is why the bug is non-obvious: each component is individually correct, and the failure only emerges in the composition. ## Decision Boundary The boundary the instance must detect is between *"compensation acknowledged"* and *"compensation effected."* A `200` from an idempotent endpoint is ambiguous: it means either "I executed your compensation" or "I already executed a compensation with this key." The instance must resolve this ambiguity before treating the speculative branch as rolled back. The detection rule: after issuing a compensation, the instance must read back the *post-compensation state* of the resource and compare it against the expected post-state. If the resource is still in the pre-compensation state, the `200` was a deduplication hit and the compensation did not run. This read-back is not optional under speculation; it is the only signal that distinguishes the two `200` cases. The architectural guardrail that prevents the collision in the first place: **derive compensation keys from `hash(resource_id, attempt_nonce, planner_epoch)`** where `attempt_nonce` is a monotonic counter incremented on every speculative dispatch, and `planner_epoch` increments on every re-plan. This makes every compensation event uniquely keyed. The read-back remains necessary as a defense-in-depth check against non-monotonic planners and against downstream services that recycle handles across epochs. ## Operational Effect Without the read-back and the nonce-bearing key, the system exhibits *silent rollback loss*: speculative branches are marked compensated while their physical effects persist. The symptom is inventory, quota, or lock leakage that scales with the number of re-plan loops — a workload that looks healthy in per-call logs but accumulates resource debt proportional to planner retries. Auditors that check only preconditions will not catch it; only a post-compensation state assertion or an out-of-band reconciliation sweep will. With the guardrail, the cost is one extra read per compensation and a bounded key space (nonce × epoch), which is cheap relative to the leak. The instance should treat any compensation whose read-back does not match the expected post-state as a hard fault requiring escalation, not a retry — because retrying with the same key will hit the same deduplication and retrying with a new key risks double-compensation if the first actually did execute. ```python import hashlib from dataclasses import dataclass class CompensationDeduplicatedError(RuntimeError): """Raised when a compensation's 200 response was a dedup hit, not an execution.""" @dataclass class SpeculativeCall: resource_id: str attempt_nonce: int planner_epoch: int def derive_compensation_key(call: SpeculativeCall) -> str: # Key must bind the compensation *event*, not just the resource. payload = f"{call.resource_id}:{call.attempt_nonce}:{call.planner_epoch}" return hashlib.sha256(payload.encode()).hexdigest() def compensate_and_verify( call: SpeculativeCall, issue_compensation, # returns (status_code, executed: bool) read_state, # returns current resource state expected_post_state, ) -> None: key = derive_compensation_key(call) status, executed = issue_compensation(key) if status != 200: raise CompensationDeduplicatedError( f"compensation for {call.resource_id} returned {status}" ) if not executed: # 200 but the downstream deduplicated: the key collided with a prior # compensation event. This is the silent-rollback-loss condition. raise CompensationDeduplicatedError( f"compensation key {key[:12]}… was deduplicated; " f"resource {call.resource_id} not actually released" ) observed = read_state(call.resource_id) if observed != expected_post_state: # Defense in depth: even an executed compensation must be verified. raise CompensationDeduplicatedError( f"post-compensation state mismatch for {call.resource_id}: " f"expected {expected_post_state!r}, observed {observed!r}" ) ```