All writing
AI ReliabilityMCPOpen SourcePostmortem

My Idempotency Library Promised Exactly-Once. An Outside Tester Made It Charge Twice.

November 18, 2026

When I published mcp-tool-idempotency 0.1.0, the very first line of the README made a promise I was pretty proud of:

Exactly-once execution for MCP tool calls (or any costly async op), so retries never fire side effects twice.

In October 2026, Igor from the Argus Agent Test Lab, an independent lab that does adversarial conformance testing, wrote to me privately to say that the promise wasn't true. He didn't just claim it, he had three reproducible ways to make the library run a committed side effect twice, and in every one of them the caller got a clean success back. No error and no warning, just two charges where there should have been one. After I froze for a moment staring at the email, I read his probes, ran them myself, and had to admit that he was right and that my README had been selling something the code couldn't even deliver.

What follows is the whole story: what broke, why "exactly-once" was the wrong thing to promise in the first place, how 0.2.0 redesigns the state machine, and what Igor's independent verification of the fix does and does not cover. If you'd rather read his side first, his full note is public: External verification note, mcp-tool-idempotency 4d665ae to v0.2.0.

Why I wrote this small library in the first place?

AI agents retry all the time, and usually for good reasons. A model re-issues a tool call because it never saw the result, an MCP client retries after a timeout, or the network drops the response after the server has already done the work. For a read-only tool that costs you a few extra tokens and nobody notices. For a tool that charges a card, stamps an invoice with the tax authority or sends an email, a retry costs real money and, worse, the trust of whoever is on the other end.

I care about this because I build fiscal automation for Mexico, where a duplicated operation can mean a second CFDI stamped with SAT and a whole cancellation process to undo it. So I wrote a small TypeScript library that wraps any side-effecting async call with an idempotency key: the first call runs, and any retry with the same key gets the stored result back instead of running again.

The 0.1.0 design had two layers. The first was an in-process map of in-flight calls, so two concurrent calls with the same key inside one process would share a single promise without touching storage at all. The second was a persistent backend with an atomic claim (INSERT ... ON CONFLICT DO NOTHING on Postgres) and a TTL, so a completed result could be replayed across restarts and across instances. Together they handled the obvious cases well, a clean duplicate, a concurrent retry in the same process, a replay after a restart. But the bugs were hiding in the unhappy paths, which is exactly where I hadn't looked hard enough.

The two assumptions that broke

Here is the core of 0.1.0, trimmed down:

const claimed = await backend.claim(key, claimMeta);
if (!claimed) {
  // Someone else holds the key. If they finished, replay their result;
  // otherwise the holder is stale/crashed - take over and re-run.
  const current = await backend.check(key);
  if (isCompleted(current)) return JSON.parse(current.response);
  await backend.reset(key, claimMeta);
}

try {
  const result = await executor();
  await backend.complete(key, JSON.stringify(result));
  return result;
} catch (error) {
  // Failures are NOT cached - the next call is allowed to retry.
  await backend.fail(key);
  throw error;
}

Igor summarized the root cause in two sentences, and I honestly can't improve on them. The code assumed that a throw means nothing happened, which is why failures weren't cached and there was no state at all for "this might have committed". It also assumed that a holder that hasn't finished has crashed, which is why reset() rewrote a pending row unconditionally, without any proof that the holder was actually dead. Each of those assumptions opens its own window for a duplicate, and he found three of them.

The three windows

The first one, which he called F1, is a lost response after commit. The executor calls the payment provider, the provider commits the charge, and then the response gets lost on the way back (ETIMEDOUT). The executor throws, 0.1.0 marks the key as failed, which in my design meant "retry allowed", and the retry happily runs the executor again. Boom, Two charges. What stung a bit was how little it took to show it, because his probe used nothing but the public quickstart API:

let providerCharges = 0;
const store = createIdempotencyStore(new MemoryBackend());
const META = { toolName: "charge", request: { orderId: "order-123" } };

const attempt = () =>
  store.execute("order-123", META, async () => {
    providerCharges++; // provider accepts and commits the charge
    throw new Error("ETIMEDOUT: response lost after provider accepted");
  }).catch((e) => e.message);

await attempt();
await attempt(); // same key, a "retry"
console.log(providerCharges); // 2

F2 is the crash after commit. The holder commits at the provider and then the process dies before it gets to call complete(), so the row stays pending with nobody behind it. The next caller loses the claim, sees that the row isn't completed, calls reset() and runs the executor again. That is plain at-least-once behavior, sitting in exactly the window the README had sold as exactly-once across restarts.

F3, the cross-instance race, was the one that bothered me the most, because it hit the very topology my README recommended: two instances sharing one Postgres. Instance A wins the claim and starts the executor. Instance B loses the claim, checks the row and sees pending, which is completely normal because A is still running, but B reads that as "A crashed", resets the row and runs the executor too. Both of them execute the side effect, and both return success, each with a different result.

On top of those three there was a smaller fourth issue: a reused key with a different request would replay the first request's result. If a bug in the caller sent order-123 again with a different amount, the library would cheerfully return the stored response for the old amount and nobody would know.

None of this showed up in my own tests, which were green with more than 90% coverage at the time. That wasn't because the tests were badly written, it was because they checked the cases I had in mind. Igor's probes checked the cases that a hostile, production-like environment actually produces, and those turned out to be a very different list.

Why "exactly-once" was the wrong promise

Before I could redesign anything, I had to accept something uncomfortable, which is that F1 can't be fully fixed by any library that sits on the caller's side.

When the executor throws after the provider has committed, all the store sees is a throw. From inside the process, "the request never left" and "the request committed and the response got lost" look identical, so any store has to pick a default for that situation. If it retries, it's safe for work that didn't commit but duplicates the work that did, and that's at-least-once. If it blocks, it's safe for work that did commit but leaves the work that didn't stuck until someone checks, and that's at-most-once. Neither of them is exactly-once. The only real fix is end to end: forward the idempotency key to a provider that deduplicates on its own side (Stripe, Adyen and most payment APIs do this), so that even a duplicate request gets absorbed downstream.

So the 0.2.0 README doesn't claim exactly-once anymore. It says what is guaranteed and it names the windows where it isn't, and I removed the word from the package keywords too. If a guarantee only holds while the network behaves, it isn't really a guarantee, right?

The 0.2.0 redesign

The fix landed in f56f24c, about 1,460 lines added and most of them tests, and shipped as 0.2.0 on 2026-10-26. It attacks each of the two broken assumptions directly.

Owner tokens and renewing leases

To stop treating "not finished yet" as "crashed", every claim now carries a random owner token and a lease expiry. While the executor runs, the store renews the lease every leaseMs / 3, with a default lease of 60 seconds, so a holder only counts as dead once its lease has really expired, meaning it stopped renewing for a full leaseMs. A caller that loses the claim to a live holder now gets an IdempotencyInFlightError and nothing runs on its side. It can retry a moment later and get the winner's result, or set inFlightWaitMs and let the store wait and replay for it. That's what closes F3.

Takeover is one conditional update

Taking over a dead holder's key also had to stop being a read followed by a write, so it is now a single statement that only one contender can win:

UPDATE idempotency_keys
SET owner = $4, lease_expires_at = $5, status = 'pending', ...
WHERE key = $1
  AND (expires_at <= $6
       OR status = 'failed'
       OR (status = 'pending' AND (lease_expires_at IS NULL OR lease_expires_at <= $6)))
RETURNING key

There's no gap between the check and the use anymore. If two instances both decide at the same moment that a holder is dead, the database lets exactly one of them have the row.

Only the owner can write

The owner token also protects the writes. complete, fail, markUncertain and renew all filter on it, so a holder that lost its lease (say the database was unreachable long enough for the lease to lapse) can't overwrite the new holder's result. Instead it gets an IdempotencyLeaseLostError with its own result attached, so the caller has what it needs to reconcile. When a renewal discovers that someone else owns the key now, the store also aborts ctx.signal, which gives a long-running executor the chance to stop before it commits. That narrows the window, but it can't close it for a side effect that's already on the wire, and the README says so as well.

An explicit "uncertain" state

F1 and F2 are where I had to give up on a clever default and hand the decision to the caller instead. With isRetryable(error) you return false for errors where the side effect might have committed, and the key moves to uncertain, so later calls get an IdempotencyUncertainError instead of running again. Setting onLeaseExpired: 'uncertain' gives the same treatment to a holder that died mid-run. An uncertain key stays blocked until you reconcile with the provider and call store.forget(key), or until uncertainTtlMs passes (30 days by default). The default is still retry, so ordinary retryable work keeps working the way it always did, and payment-style executors opt into the safe mode.

Request fingerprints

The fourth issue was the easiest to fix. Each claim now stores a SHA-256 fingerprint of the canonicalized request, where key order doesn't matter, and reusing a key with a different request throws an IdempotencyConflictError on both the replay path and the in-flight path. Only the hash is stored, never the payload, and if you really want the old behavior back, verifyRequest: false is there.

The external verification

After the release I sent Igor the fix, and he tried to break it again, verifying it independently with his own tools. His method is the part I'd most recommend copying. He wrote ten standalone probes against the v0.2.0 tag using only the public API, and before running anything he pre-registered the expected outcome of each one in the probe headers and in a README for the whole battery, so the expectations were on paper before the results existed. Then he ran four of the probes against a worktree of the old commit to confirm they still reproduced the old behavior, and all four did. That step matters more than it looks, because a test that passes on both the broken version and the fixed one proves nothing at all.

All 10 windows passed on v0.2.0. Here is a summary of his table:

Window What v0.2.0 does
Clean duplicate Replays, one charge, identical result
Lost response, default Retries and re-raises: the documented at-least-once window (two charges)
Lost response, isRetryable: false One charge, then IdempotencyUncertainError until forget()
Takeover, live holder Never taken; IdempotencyInFlightError, executor not started
Takeover, expired lease, default Conditional takeover exactly once, then replay
Takeover, expired lease, onLeaseExpired: 'uncertain' Blocked until reconciled
Cross-instance race One charge; the loser gets InFlight, its retry replays the winner
Same key, different request IdempotencyConflictError on replay and in-flight paths
Failure before the side effect The retry commits exactly once
TTL boundary Replays inside the TTL, re-executes after it

The second row deserves a closer look. Igor's original F1 probe, run unchanged against 0.2.0 with default options, still charges twice. That isn't a regression, it's the honest default, now documented and under the caller's control, and with isRetryable: () => false the same probe charges exactly once.

Afterwards I mapped his ten windows onto my own suite. Eight of them were already covered by the regression tests I'd written in response to his report, but two weren't: the TTL boundary going through execute(), and a live holder keeping ownership of its row after a newcomer gets rejected. I added both the day after the release, and the suite went from 91 to 93 tests, all passing, with every window running against both backends.

Where the verification stops

Igor and I agreed to keep the scope of all this explicit, so I want to be clear about what it doesn't prove.

His battery ran on MemoryBackend, which means it verifies the store logic but not the Postgres SQL. My own suite runs every scenario against PostgresBackend too, but through a SQL fake rather than a real Postgres server, so a contract run against a real database is the next gap I'm closing.

The default is also still at-least-once when the executor throws. isRetryable is what closes that window, and no setting in any library can make it disappear for a provider that doesn't honor idempotency keys.

Finally, leases depend on clocks and on the event loop. Lease expiry compares timestamps written by different machines, so clock drift has to stay well under leaseMs, which NTP easily handles for the 60-second default. And because the lease is renewed by a timer, a CPU-bound executor that blocks the event loop for longer than leaseMs can lose its lease while it's still running. The answer there is to size leaseMs above your worst case or move heavy work to a worker thread. Using the database clock for lease expiry is planned for 0.3.0.

What I'm taking from this

The biggest lesson is to write the guarantee down before writing the code, and I mean that seriously. "Exactly-once" was a marketing line, never a specification, and the moment I was forced to build a table of windows and what happens in each one, the design more or less followed from it. If I'd started from that table in July, most of this post wouldn't exist.

The second is that for a library like this one, a correctness bug is a security bug, because the double charge is the vulnerability. SECURITY.md now says that explicitly, asks for private reports of broken guarantees, and keeps a past-advisories section for 0.1.0.

The third is that coverage only measures the tests you thought of. I had over 90% of it and three duplicate-execution windows at the same time. The probes that found them were short, used nothing but the public API, and simply simulated what production does every day: lose responses, kill processes, run two instances.

And the last one is the one I'll carry into every release from now on. A fix I verified myself is a claim, while a fix someone else verified is evidence. Sending the fix straight back to the reporter so he could try to break it again, against expectations he wrote down beforehand, was the most valuable step in this whole process, and I'll do it again.

Timeline

Date Event
2026-07-13 0.1.0 published on GitHub with the exactly-once claim
2026-10-26 Igor privately reports F1, F2, F3 and the request-replay issue
2026-10-26 0.2.0: owner-gated leases, uncertain state, request fingerprints, honest guarantees
2026-10-27 Two more window tests added from the verification battery; README documents event-loop and clock-drift limits
2026-10-28 Independent verification note published; linked from SECURITY.md

Thanks

A real thank you to Igor and the Argus Agent Test Lab, for reporting privately, for writing probes that made each window impossible to argue with, for coordinating the disclosure, and then for spending even more of his time verifying the fix. The whole cycle, from private report to verified fix, took two days. My view is simple: if I screwed up, the least I can do is fix it properly and ASAP. Igor told me it was a fast and unusually clean response, and in the lab's public registry my case is one of the few marked fixed, verified and credited. That tells me this isn't the norm, which is a lot to think about. His verification note is here.

If you run side-effecting tools behind an agent, the library is on GitHub, and if you find another way to break it, please report it privately. That's how it gets better.