---
title: "Retry Is Not Recovery: Idempotency for AI Agents"
description: "Idempotency is the first thing engineers reach for when an agent retries a failed tool call. A new benchmark shows it fixes one failure phase out of three."
author: "MDflow"
date: 2026-12-05
reading_time: "18 min"
canonical_url: https://mdflow.cz/blog/idempotency-for-ai-agents
md_url: https://mdflow.cz/blog/idempotency-for-ai-agents.md
---

# Retry Is Not Recovery: Idempotency for AI Agents

*Published December 5, 2026 · 18 min read*


A coding agent picks up an issue, applies a patch, runs the tests, and they pass. It tags a release. Then the downstream integration fails. Can it put everything back the way it was? **Idempotency** and the rest of the fault-tolerance toolkit exist to make the answer yes — and a benchmark published in October suggests the toolkit is being applied to agents far more loosely than anyone would apply it to a payments service.

Git knows what changed in the repository. It does not know about the calls that went out to external systems, the runtime configuration that got edited, or the notifications that already landed in somebody's inbox. And re-running an operation is not the same thing as undoing it. That gap — between being able to do the job and being able to reverse it — turns out to be measurable, and larger than the folklore assumes.

> **TL;DR** — Agent benchmarks measure whether an agent can complete a task, not whether it can put things back when the task half-fails. UndoBench measures both separately and finds a large gap between them, and its headline practical result is that recovery is phase-dependent: idempotency keys resolve the post-commit case, do nothing extra before the mutation starts, and do not help when a multi-step workflow is half applied. The companion EvoUndo framework shows why prompting an agent to fix its own undo fails — it lacks the prior state and the vocabulary to reverse the change. The fix starts with capturing the prior state before the write lands, in a layer you control. [MDflow](https://mdflow.cz) does that for the document layer: on Pro, a saved change leaves the previous version behind through every write path, including an agent's own write over MCP or the API.

## What idempotency means for an AI agent

Idempotency means that applying an operation twice leaves the system in the same state as applying it once. It is the oldest trick in distributed systems, and agents need it for a specific reason: **a timeout tells you the response did not arrive, not that the operation did not happen.**

Here is the scenario the UndoBench authors use, and it is worth walking through slowly because every part of it is ordinary:

```text
agent  ──create_ticket(...)──▶  server
                                 creates ticket 781   ✅
       ◀── [acknowledgment lost in transit] ──
agent: request timed out
agent  ──create_ticket(...)──▶  server
                                 creates a second ticket   ✅

intent: one ticket.   result: two tickets.
```

Nothing malfunctioned. The server did its job twice because it was asked twice, and the agent asked twice because it had no way to tell a lost acknowledgment from a failed operation. Human engineers have patterns for this — idempotency keys, write-ahead logging, compensating transactions, better known as sagas. The UndoBench paper's framing of the problem is that modern agent runtimes mostly do not use them: tool execution is treated as an uninspected request-response primitive, and when a call raises, the error string goes back into the prompt and the agent retries or reflects on it.

## Task competence is not recovery capability

The reason this stays invisible is that benchmarks do not look for it. UndoBench's stated motivation is that widely used agent benchmarks — SWE-bench, ToolBench, API-Bank, AgentBench, WebArena — evaluate almost entirely under nominal, unperturbed conditions, which conflates planning competence with fault recovery.

So the benchmark separates them. It spans 36 base workflows and 36 fault scenarios across 8 enterprise domains, and runs each workflow as a **paired counterfactual** under identical seeds: once cleanly, once with a fault injected. Its frozen lost-acknowledgment study covers 12 held-out test workflows across two open-weight models, two frameworks and three recovery paradigms — 5,760 executions, 2,880 paired trials. Two numbers come out of it:

| Measure | Result |
| --- | --- |
| Nominal competence — completed the task cleanly | **83.54%** |
| Conditional recovery success rate (CRSR) — recovered, among trials that succeeded nominally | **46.72%** |
| Naive retry producing duplicate external effects | **53.33%** of trials |

Read those carefully, because the denominators differ: CRSR is conditioned on the paired trial having succeeded under nominal conditions, which is the whole point of pairing. The claim is not that an agent's score halves. It is that **competence and recoverability are different capabilities, and measuring the first tells you very little about the second.** The authors report that extending the study to commercial API models reproduced the same separation.

## Recovery is phase-dependent

This is the finding with the most direct engineering consequence, and the one that complicates the usual advice. UndoBench evaluates recovery at three execution boundaries, and reports that the mechanism that works differs at each:

| When the failure hits | What the problem actually is | What the paper reports |
| --- | --- | --- |
| **Before the mutation** | Nothing has happened remotely yet | Redispatching the call is safe; the more elaborate mechanisms add overhead without a reliability gain |
| **During the mutation** | A composite workflow is partly applied | Naive retry, per-call idempotency and zero-privilege journaling all collapse on the evaluated composite workflows; a per-call key cannot restore an invariant that spans several calls |
| **After commit, before the acknowledgment** | You do not know whether it committed | Server-side deduplication and verifying state before retrying both substantially improve safety |

Two things follow. First, an idempotency key is not a recovery strategy, it is a recovery strategy for one boundary — and it happens to be the boundary that is easiest to reason about. Second, the middle row is the hard one, and it is hard for a structural reason: reconciling an intermediate state requires both knowing what the state was and having a repair action you are permitted to take.

That second constraint is sharper than it looks. UndoBench's taxonomy of recovery baselines includes checkpoint/restore and sagas, and the paper reports **excluding both from its benchmark-wide evaluation as inapplicable** — you cannot snapshot a remote cloud or payment API, and under zero privilege there are no pre-registered inverse actions to compensate with. The two patterns that could genuinely undo something are the two you do not get to use when the agent holds no privilege over the remote system. Which is also why `git revert` is not the answer for a coding agent: it restores the repository and leaves the deploy, the database write and the notification exactly where they are.

## You cannot undo what you never recorded

The companion paper, EvoUndo, takes the same question into territory that is getting less attention than it deserves: agents that modify **themselves**. Their own prompts, tools, middleware, resources and execution harnesses, at runtime.

Start with the smallest possible example, the one the talk uses. An agent changes a timeout from 30 to 60. To undo that, something has to know the original value was 30. If nobody wrote it down before the change, the information is simply gone — no amount of reasoning recovers it. So EvoUndo captures a **witness** of the prior state before applying the change, which serves twice over: it is what you restore from, and it is what an independent verifier later checks the restored state against.

The measurements are blunt. Across 600 one-shot self-evolution tasks, the authors identify 197 changes that improved capability but failed recoverability verification. The talk gives the denominator a different way — of 600 tasks, 478 produced capability improvements, so roughly two in five of the improvements that worked were not safely reversible. The one-sentence version: **an agent can become more capable while becoming less restorable.**

Then the result that should end a popular reflex. Under the original recovery representation, conventional repair strategies recovered **0 of those 197** failures; the talk describes testing four verifier-guided repair strategies, none of which fixed them. Asking the agent to fix its own undo does not work, and the paper isolates two separate reasons with a two-by-two intervention:

- **State grounding.** Give the agent the exact address of what changed and recovery goes from 0 to 38 of 48 cases, in the stratum where the existing recovery language was already sufficient.
- **Expressivity.** Extend the recovery language itself and recovery goes from 0 to 142 of 143 cases in the stratum defined by the oracle.

One is an information problem and the other is a vocabulary problem, and neither is a reasoning problem. The paper's own conclusion is that reliable self-evolution requires co-designing verification, state grounding, witness semantics and recovery-language expressivity, rather than relying on iterative prompting. It also reports one honest wrinkle: on its primary backbone, adding exact-address diagnostics *on top of* the richer language dropped recovery to 133 of 143, and a replication on a second model did not reproduce that interaction — so that part looks model-dependent.

The structural idea underneath EvoUndo is the part worth stealing even if you never run the benchmark. **Recoverability becomes an acceptance criterion.** Capture the witness, apply the change in a test environment, run the recovery plan, have an independent verifier confirm the original state actually came back — and accept the change only if it improves capability *and* passes the restoration check. Recoverability stops being something you plan after deployment and becomes a gate the change has to pass.

And when a failure cannot be handled that way, the talk's taxonomy is four responses chosen by what happened, not by what the agent prefers: nothing changed, so retry; the prior state is known, so restore it; the external action already took effect, so run a compensating action; cannot restore or cannot verify that restoring is safe, so stop and escalate.

## Which applications benefit most

1. **Agents that touch money, tickets or inventory.** Anything where a duplicate is a real-world artefact somebody has to reconcile by hand. This is the case idempotency keys were invented for, and the one where the post-commit boundary dominates.
2. **Coding agents with deploy or migration rights.** The repository is the part you can revert. The migration, the release tag and the notification are not, and they are the part that stays broken.
3. **Multi-step workflow agents.** Any agent whose task spans several tool calls lives in the middle row of that table, where per-call mechanisms stop helping and intermediate-state reconciliation starts.
4. **Self-improving agents and harness tuners.** Anything that edits its own prompts, tools or configuration — where EvoUndo's result applies directly and the witness is the only thing standing between you and an irreversible improvement.
5. **Long-running autonomous agents.** The longer the run, the more effects accumulate before anyone looks, and the more the question shifts from "did it work" to "what is now true that was not before".

## How MDflow fits

Recovery needs two things that are not models: a record of what the state was before the write, and a record of what actually happened. For the document layer — specs, runbooks, decisions, agent-written notes — that is exactly what [MDflow](https://mdflow.cz) keeps.

**What lines up today.**

- **Every write leaves a witness.** Version history captures the previous version on every saved change, and capture covers *every* write path — the editor, the HTTP API and the MCP server alike. So when an agent rewrites a document through `mdflow_update_document_body`, the prior text is retained without the agent having to think about it. There is a line-by-line markdown diff, and restore is non-destructive: the current text is preserved as a new entry, so rolling back is itself reversible. It is a Pro feature — free accounts accrue no history — bounded to 30 days or the last 300 versions, and rapid successive saves within a minute collapse into one capture, which is worth knowing precisely because a timeout-and-retry is exactly that case.
- **An effect history with the actor on it.** The Document Log at `/log` records created, edited, shared and deleted events across documents, with the actor on every row — `you` for browser actions, `automated · <token name>` for anything arriving over the API or MCP. An edited row opens a diff of exactly what that edit changed. Deleted documents keep their who, what and when even though the document is gone. Retained for 30 days; free accounts see the last 24 hours. That is the personal workspace; Team accounts keep their own separate audit feed.
- **The write that is idempotent by construction.** `PUT /api/v1/documents/{id}/body` replaces the whole body rather than appending or patching, so replaying the identical request leaves the identical state. That is the one shape of write where a lost acknowledgment genuinely costs nothing — and it is a design property, not a feature we added for this.
- **A refusal in front of the worst write.** An empty body is rejected unless the caller passes `confirmEmpty: true`, in the editor, the HTTP API and MCP alike, so a client with a cleared or unloaded buffer cannot silently wipe a document. A deterministic check in front of a probabilistic writer.
- **Retry safety is declared per tool, before the call.** Of the write tools on the [MCP server](/docs/mcp), 12 carry `idempotentHint: true` — renaming, moving, replacing a body, updating a folder description, revoking a share, all of which replace rather than append. Six carry `false`: creating a folder, workspace or document, and deleting one. An agent does not have to guess which of our writes survive a repeat, and the annotation is machine-readable before it calls anything. It is the smallest useful version of what UndoBench is arguing for, and it is a hint rather than a guarantee — the MCP specification is explicit that tool annotations are not guaranteed to describe behaviour faithfully.

**And the honest limits**, because this post is about not fooling yourself:

- **Create is not idempotent.** Duplicate document titles inside a folder are disambiguated automatically with a numeric suffix, so a retried create after a lost acknowledgment gives you two documents rather than one. That is the ticket-781 scenario in miniature, inside our own API. There is no `Idempotency-Key` header today.
- **The body write has no precondition.** The editor's saves are conflict-aware — a save only overwrites the server copy the edit was based on, and you get a keep-mine or load-server choice instead of a silent overwrite. The token surface does not have that: an API or MCP write is last-write-wins.
- **The witness is not readable by the thing that wrote the document.** In a personal workspace, version history is private to the document owner; it is exposed through neither the HTTP API nor MCP on any plan, and it records no author. An agent's write leaves a witness behind that the agent itself cannot read, diff or restore from — which is precisely the state-grounding bottleneck EvoUndo isolates, sitting in our own product.
- **There is no trash.** A deleted document is gone, though the log keeps the record that it existed and who removed it.

**Where we are headed.** Interests, not dated commitments — and one of them is a genuine tension rather than a plan. Write paths that can refuse on a stale precondition are straightforwardly something we want, so a stale agent write is rejected instead of silently winning. Agent-readable history is the harder one: keeping version history off the token surface is a deliberate choice, because the record of what an agent changed should not be editable by the agent being audited. Reconciling those two — grounding an agent's own undo without handing it the audit trail — is the open question, and read-only access to a previous version is the obvious shape of an answer. The nearest thing we have already written down is [referencing a document at a specific version](/blog/agents-need-receipts-not-more-tools), so a note can point at the text as it stood on a given day rather than at whatever it says now.

> **Connect Claude to MDflow:** open the [MDflow connector](https://claude.ai/directory/mdflow) in Claude's Connectors Directory, click **Connect to Claude**, and sign in — no URL or token to paste. One connection covers claude.ai, the Claude desktop and mobile apps, and Claude Code signed in with a Claude subscription. Team workspaces use a `mdt_` Team access token instead, with the bearer-header clients listed in the [MCP docs](/docs/mcp).

## The bottom line

The reliability question for agents has quietly moved. It is no longer only "can it do the task" but "when it half-does the task, what is now true that nobody intended". UndoBench measures those as two separate things rather than collapsing them into one pass rate, and the measurement says they come apart.

Three things to take from it. Stop treating a timeout as a failure signal — it is a statement about the response, not the operation. Stop treating idempotency as *the* answer, because it is the answer at one of three boundaries and the hardest boundary is the middle one. And capture the prior state before the write lands, because an undo needs a starting point and nothing reconstructs one that was never recorded.

Then put the records somewhere both your reviewers and your agents can read. [Start free](/login), [connect an AI agent](/docs/mcp), or [read the API docs](/docs/api).

## Frequently asked questions

### What is idempotency in the context of AI agents?

Idempotency means applying the same operation twice leaves the system in the same state as applying it once. For AI agents it matters because an agent that gets no answer from a tool call has no way to tell a failed operation from a successful one whose confirmation was lost, so it cannot know whether repeating the call is safe. If the operation is idempotent the repeat costs nothing. If it is not, the repeat creates a second ticket, a second payment, or a second deploy. One implementation is an idempotency key derived from the call itself, which the server uses to recognise and discard the duplicate; UndoBench evaluates exactly that as one of its recovery baselines, and finds it helps at one execution boundary out of three.

### Why is an idempotency key not enough for an AI agent?

Because it addresses one failure phase. The UndoBench paper evaluates recovery at three execution boundaries and finds the right mechanism differs at each. Before the mutation starts, simply redispatching the call is safe and the more elaborate mechanisms add overhead without a reliability gain. After the remote system commits but before the acknowledgment arrives, server-side deduplication and verifying state before retrying both resolve the ambiguity directly. In between, when a multi-step workflow is half applied, the paper reports that naive retry, per-call idempotency and zero-privilege journaling all collapse on the composite workflows it evaluates, because a per-call key cannot restore an invariant that spans several calls.

### What is a lost acknowledgment?

A lost acknowledgment is when an operation succeeds on a remote server but the connection drops before the client receives the confirmation. It is a classic distributed-systems hazard, and it is why a timeout is not a failure signal: it tells you the response did not arrive, not that the operation did not happen. An agent that treats the timeout as a failure and retries has a good chance of duplicating a side effect it already caused. In UndoBench's frozen lost-acknowledgment study, naive retry produced duplicate external effects in 53.33% of trials.

### Can you just prompt an agent to fix its own undo?

The EvoUndo paper tested that and reports it does not work. Across 600 one-shot self-evolution tasks the authors identified 197 changes that improved the agent's capability but failed recoverability verification, and conventional repair strategies recovered 0 of those 197 under the original recovery representation. The paper separates two reasons. One is state grounding: the agent does not know the exact prior value it is supposed to restore. The other is expressivity: the recovery language cannot express the operation that would reverse the change. Neither is fixed by asking the model to try harder.

### What should an agent do when it cannot undo something?

Stop and escalate. The talk that presented this work lays out four responses chosen by what actually happened: if nothing changed, retry safely; if the prior state was captured, restore it; if an external action already took effect, run a compensating action that offsets it; and if the system cannot be restored, or cannot verify that restoring it is safe, hand the situation to a human rather than guessing. The failure mode worth designing against is an agent that reports success because its undo command returned without error, with nobody checking whether the state actually came back.

## Further reading

- [Your Coding Agent Can't Undo Its Own Mistakes](https://www.youtube.com/watch?v=BT1Mo-fD-g0) — Tanmay Sah and Dolly Sah at AI Engineer, published 8 November 2026. The talk this post is built on, covering both papers and the EvoUndo acceptance loop.
- [UndoBench: Separating Task Competence from Recovery Capability in Tool-Using AI Agents](https://arxiv.org/abs/2610.05622) — Dolly Sah, Tanmay Sah, Harshul Jain and Tanya Sah, 4 October 2026. The benchmark, the CRSR metric, the recovery-baseline taxonomy and the phase-dependent results.
- [EvoUndo: Recoverability-Constrained Self-Evolution for LLM Agent Harnesses](https://arxiv.org/abs/2608.28363) — the same authors, 28 August 2026. Witness semantics, the grounding-by-expressivity intervention, and recoverability as a constraint on self-modification.
- [Sagas](https://www.cs.cornell.edu/andru/cs711/2002fa/reading/sagas.pdf) — Hector Garcia-Molina and Kenneth Salem, 1987. The original compensating-transactions paper, and one of the patterns UndoBench had to exclude as inapplicable under zero privilege.
- [Multi-Agent Orchestration Is a Distributed System](/blog/multi-agent-orchestration-distributed-system) — the companion argument from first principles: partial failure, lost replies and unsafe retries between sub-agents.
- [Event-Sourced Agents: Why the Log Is the Agent](/blog/event-sourced-agents) — what you get when the log, rather than the state, is the source of truth.
- [Agent Archaeology](/blog/agent-archaeology) — the related question of reconstructing what an agent did after the fact.
- [Version Control for Documents — Without Git](/blog/version-control-for-documents) — the witness problem for the document layer, and what a usable history needs.
- [Connect an AI agent to MDflow](/docs/mcp) — the MCP server, the HTTP API and personal access tokens.

