# When must an instance refuse to replay a compensated A2A task: the compensation-epoch invariant and the idempotent-retry boundary **Date of Record:** 2026 November 23 **Scope:** Applies to A2A (agent-to-agent) task lifecycles where a coordinator agent retries state-mutating `tasks/send` or `tasks/resume` calls against a remote agent that has already emitted a terminal `compensated` or `failed` state and where the remote agent exposes idempotency keys. Does not apply to pure read-only `tasks/get` polling or to tasks whose operations are provably side-effect-free. ## Core Distinction The distinction that matters is between **retry idempotency** and **compensation idempotency**. These are routinely conflated because both are expressed as "the same request can be sent twice safely." They are not the same invariant, and the A2A task state machine is where they diverge. - *Retry idempotency* is a property of a single forward transition: given request `R` with idempotency key `K`, applying `R` twice with the same `K` yields the same post-state as applying it once. It bounds duplicate delivery. - *Compensation idempotency* is a property of a *reversal transition*: given a task that reached `completed` (or `working` with committed sub-effects) and was then compensated to `compensated`, a late-arriving retry of the original `R` with the *original* `K` must **not** re-apply the forward effect. The failure is non-obvious because the idempotency key `K` is still valid, the remote agent's dedup store still has `K` recorded, and a naive dedup layer will answer `200 OK` with the *original* completed result — silently resurrecting work that was deliberately rolled back. The key is idempotent. The *epoch* is stale. Dedup on `K` alone cannot see the compensation. The invariant required is: **a task's idempotency-key namespace is scoped to a compensation epoch, and any retry carrying a key from a pre-compensation epoch must be rejected as a conflict, not deduplicated as a success.** ## What Was Observed A coordinator agent `C` dispatched a multi-step task to worker `W` over A2A. The task had three sub-effects: `reserve_inventory`, `charge_payment`, `emit_shipment`. `C` sent `tasks/send` with `idempotency_key = K1`. `W` executed all three, transitioned `working → completed`, and returned an artifact handle. `C`'s response read timed out at the transport layer (a 30s deadline fired while the payload was still in flight), so `C`'s retry supervisor scheduled a retry of the *same* `tasks/send` with `K1`. Before the retry fired, a separate auditor agent `A` observed that `emit_shipment` had produced an artifact whose downstream consumer rejected it on schema grounds. `A` issued a `tasks/cancel` with a compensation directive. `W` executed the compensation plan in reverse order: `void_shipment`, `refund_payment`, `release_inventory`, and transitioned `completed → compensating → compensated`. `W` recorded `K1 → compensated` in its dedup store, but the dedup record retained the *original* success payload as the cached response body (a common implementation shortcut: the dedup table stores `key → response`, and the compensation path updated the *state* but not the *cached response*). The retry of `K1` then arrived. `W`'s dedup layer found `K1`, returned the cached `200 OK` with the original `completed` artifact handle. `C` marked the task complete and reported success upstream. The inventory was released, the payment refunded, and the shipment voided — but `C`'s ledger and every downstream consumer of `C`'s report believed a shipment existed. The divergence was detected 41 minutes later when a reconciliation job compared `C`'s reported artifact count against `W`'s actual effect log. The trace, condensed: ``` t0 C → W tasks/send(K1) state: submitted t1 W: reserve_inventory, charge_payment, emit_shipment t2 W: working → completed dedup[K1] = {state: completed, body: artifact_h} t3 C: read timeout (30s) C.retry_pending[K1] = scheduled t4 A → W tasks/cancel(compensate) state: completed → compensating t5 W: void_shipment, refund_payment, release_inventory t6 W: compensating → compensated dedup[K1].state = compensated dedup[K1].body = artifact_h ← NOT updated t7 C → W tasks/send(K1) (retry) dedup hit on K1 t8 W → C 200 OK {body: artifact_h} ← stale epoch resurrected t9 C: task complete, reports artifact_h upstream ``` The root cause is not the timeout, not the compensation, and not the retry. It is the **epoch-blind dedup lookup at t7**: the dedup store keyed on `K1` alone, with no compensation-epoch component, so the lookup could not distinguish "this key was successfully applied in epoch 0" from "this key's epoch-0 effect has been reversed." ## Condition of Validity The epoch-scoped invariant is only required when **all three** of the following hold: 1. The worker exposes a compensation path that reverses forward effects (i.e., `compensated` is reachable from `completed`). 2. The coordinator's retry supervisor can emit a retry whose idempotency key was minted *before* the compensation occurred. This is the common case whenever retries are scheduled asynchronously (backoff timers, dead-letter replay, at-least-once transport) rather than synchronously within a single call. 3. The dedup store caches response bodies, not just terminal states. If the store caches only `state`, the stale-body resurrection cannot occur, but a subtler variant remains: the retry receives `409 Conflict` semantics on state but the coordinator may still treat "state present" as "work done." When any of these fails, the weaker single-key idempotency is sufficient. In particular, if the worker *never* compensates — it only fails forward — then `K1` dedup is safe because there is no reversal to be resurrected. The invariant is specifically about the interaction of reversal with retry, and it is vacuous without reversal. A second validity condition is temporal: the retry must arrive *after* the compensation commits. A retry that lands between `t4` and `t6` (during `compensating`) hits a different boundary — the worker must either block the retry until compensation resolves or reject it, but it must not serve the pre-compensation body. The `compensating` state is the hardest window because the outcome is not yet decided; the only safe response is `409` with a `retry_after` bound to the compensation's own deadline, never a cached success. ## Decision Boundary The coordinator must decide, per retry, whether the retry is a *duplicate of a live forward attempt* or a *resurrection of a reversed attempt*. The decision boundary is drawn by comparing the retry's epoch tag against the worker's current compensation epoch for that task lineage. Concretely, the coordinator should attach `compensation_epoch` to every `tasks/send` and `tasks/resume`. The worker increments its lineage epoch on every committed compensation. The dedup key becomes `(idempotency_key, compensation_epoch)`. On lookup: - Exact `(K, epoch)` match with a cached success → safe to return cached body (true duplicate). - `K` present at a *lower* epoch than current, no match at current epoch → **reject with `409 StaleEpoch`**, do not serve the old body, do not re-execute. The coordinator must then decide whether to re-issue with a fresh key and fresh epoch (a new forward attempt) or abandon. - `K` absent entirely → execute normally. The boundary is *not* "did the worker see this key before." It is "did the worker see this key before **in the current epoch**." This is the one-line change that the observed failure lacked. A note on the coordinator side: the coordinator must not treat `409 StaleEpoch` as a transient error and retry it. It must treat it as a terminal signal that the work it believes is in flight has been reversed, and it must propagate that reversal to its own ledger. A retry loop on `409` is the second-order failure mode — it converts a detectable divergence into a hot loop against a worker that will never accept the stale key. ## Operational Effect With epoch-scoped dedup, the observed failure at t7 becomes a `409 StaleEpoch` at t8. `C` receives an explicit signal that its in-flight task was compensated, and its ledger can be corrected within the same request cycle rather than 41 minutes later. The cost is one extra field on every request and one integer comparison in the dedup path. The operational effect on the *worker* is that it must persist the compensation epoch durably alongside the dedup table, and it must increment the epoch atomically with the compensation commit. If the epoch increment and the compensation commit are not atomic, a crash between them leaves the epoch stale and reopens the resurrection window — the same failure, just narrower. This means the epoch counter is a first-class piece of state, not a derived value. The operational effect on the *coordinator* is that its retry supervisor must carry the epoch it observed at dispatch time and must not "refresh" it on retry. Refreshing the epoch from the worker's current state defeats the entire invariant: the retry would then carry the post-compensation epoch and be treated as a legitimate new forward attempt, re-applying the reversed effects. The epoch is a *witness* of what the coordinator believed at dispatch, and it must be immutable across retries of the same logical attempt. Finally, the invariant bounds a class of failures that are otherwise invisible: any system where retries are asynchronous and compensation is possible has this window. The window's width is the retry backoff plus the compensation duration. Epoch-scoped dedup closes it to zero. Without it, the only mitigation is to make compensation impossible (fail-forward only), which is often not a business option, or to make retries synchronous (which sacrifices at-least-once delivery). The epoch tag is the cheap, local fix. ```python from dataclasses import dataclass, field from enum import Enum from typing import Optional class TaskState(Enum): SUBMITTED = "submitted" WORKING = "working" COMPLETED = "completed" COMPENSATING = "compensating" COMPENSATED = "compensated" FAILED = "failed" class StaleEpochError(RuntimeError): """Raised when a retry carries an idempotency key minted in a compensation epoch that has since been superseded. The forward effect was reversed; serving the cached body would resurrect it.""" class CompensationInFlightError(RuntimeError): """Raised when a retry lands during the compensating window, where the outcome is undecided and no cached body is safe to serve.""" @dataclass class DedupRecord: state: TaskState body: Optional[dict] epoch: int @dataclass class Worker: # key -> record, scoped by epoch stored inside the record dedup: dict[str, DedupRecord] = field(default_factory=dict) # lineage -> current compensation epoch epoch: dict[str, int] = field(default_factory=dict) def handle_send( self, lineage: str, idempotency_key: str, compensation_epoch: int, payload: dict, ) -> dict: current_epoch = self.epoch.get(lineage, 0) record = self.dedup.get(idempotency_key) if record is not None: if record.state is TaskState.COMPENSATING: # Undecided window: never serve a cached body. raise CompensationInFlightError( f"task {lineage} is compensating; retry after " f"compensation deadline" ) if record.epoch != current_epoch or compensation_epoch != current_epoch: # Key was minted in a pre-compensation epoch whose effects # were reversed. Do NOT dedup to success. Do NOT re-execute. raise StaleEpochError( f"idempotency key {idempotency_key} belongs to epoch " f"{record.epoch} but lineage {lineage} is at epoch " f"{current_epoch}; forward effect was compensated" ) # True duplicate within the current epoch: safe to replay. return record.body or {} # Fresh forward attempt. body = self._execute(payload) self.dedup[idempotency_key] = DedupRecord( state=TaskState.COMPLETED, body=body, epoch=current_epoch ) return body def compensate(self, lineage: str, idempotency_key: str) -> None: record = self.dedup.get(idempotency_key) if record is None or record.state is not TaskState.COMPLETED: return record.state = TaskState.COMPENSATING self._reverse_effects(idempotency_key) # Atomic with the reversal in a real store; modeled sequentially here. record.state = TaskState.COMPENSATED record.body = None # invalidate cached body self.epoch[lineage] = self.epoch.get(lineage, 0) + 1 def _execute(self, payload: dict) -> dict: return {"artifact": f"handle-{payload.get('id', 'x')}"} def _reverse_effects(self, idempotency_key: str) -> None: pass ```