DEV Community

Walker Miller
Walker Miller

Posted on Originally published at loopandretry.github.io

Replay every tool call twice: a CI test that catches non-idempotent agent tools

Originally published on Loop & Retry — field notes on building LLM agents that survive production.

Idempotency is a property people assert and almost never test. A tool's docstring says "safe to retry", the wrapper adds a key, everyone nods. Then a timeout hits in production, the retry fires, and the customer gets two emails. The claim was never checked against the only scenario that matters: the same call, executed twice.

This is a practical post. For how to derive keys, see idempotency keys for agents. For what to do at runtime when a call times out, see the timeout that might have worked. For the budget and breaker side, fleet retry patterns. This one is about the test that tells you whether any of that actually holds for your tools, before an incident does.

The idea: count effects, not return values

A tool that returns the same answer twice isn't necessarily idempotent. send_email can return {"ok": true} both times and have sent two messages. What you assert on is the effect log of the backend, not the tool's output.

So the harness has three parts:

  1. A fake backend that records every side effect it receives.
  2. A registry of your tools with sample arguments.
  3. A runner that executes each call under three fault modes and checks the log.

The fake backend

Every effect goes through one object. It records, and it can be told to fail after recording, which is the case that bites.

# fakes.py
from dataclasses import dataclass, field

class AckLost(TimeoutError):
    """The effect happened; the caller never heard back."""

@dataclass
class Backend:
    effects: list = field(default_factory=list)
    drop_next_ack: bool = False
    seen_keys: dict = field(default_factory=dict)   # only used if the API supports keys

    def apply(self, op: str, payload: dict, key: str | None = None):
        # Model a backend that honours idempotency keys, if one is sent.
        if key is not None and key in self.seen_keys:
            return self.seen_keys[key]
        self.effects.append((op, payload))
        result = {"ok": True, "n": len(self.effects)}
        if key is not None:
            self.seen_keys[key] = result
        if self.drop_next_ack:
            self.drop_next_ack = False
            raise AckLost(op)
        return result
Enter fullscreen mode Exit fullscreen mode

Note the order: record, then raise. A backend that fails before recording tests nothing, because retrying that is always safe.

If a real third-party API gives you no key support, delete the key branch and the fake gets stricter: it will accept the duplicate, which is what the real one does.

Tools under test

Each tool takes the backend as a parameter, so the test can swap it. Here are two, one naive and one defended:

# tools.py
import hashlib, json

def send_email_naive(be, to, subject):
    return be.apply("email", {"to": to, "subject": subject})

def intent_key(op, payload):
    blob = json.dumps([op, payload], sort_keys=True)
    return hashlib.sha256(blob.encode()).hexdigest()[:24]

def send_email_keyed(be, to, subject):
    p = {"to": to, "subject": subject}
    return be.apply("email", p, key=intent_key("email", p))
Enter fullscreen mode Exit fullscreen mode

The key is derived from what the call is for, not from a timestamp or a counter. If you derive it from the moment, every replay gets a fresh key and the test, correctly, fails.

The runner: three modes

# test_idempotency.py
import pytest
from fakes import Backend, AckLost
import tools

CASES = [
    # (tool, kwargs, expected effects after the logical call)
    (tools.send_email_naive, {"to": "a@x.io", "subject": "hi"}, 1),
    (tools.send_email_keyed, {"to": "a@x.io", "subject": "hi"}, 1),
]

def call_with_retry(fn, be, kwargs, attempts=3):
    for _ in range(attempts):
        try:
            return fn(be, **kwargs)
        except TimeoutError:
            continue
    raise RuntimeError("gave up")

@pytest.mark.parametrize("fn,kwargs,expected", CASES)
def test_replay_twice(fn, kwargs, expected):
    be = Backend()
    fn(be, **kwargs)
    fn(be, **kwargs)                       # the retry that shouldn't have been needed
    assert len(be.effects) == expected

@pytest.mark.parametrize("fn,kwargs,expected", CASES)
def test_ack_lost_then_retry(fn, kwargs, expected):
    be = Backend(drop_next_ack=True)
    call_with_retry(fn, be, kwargs)        # first attempt lands, ack is lost, retry fires
    assert len(be.effects) == expected

@pytest.mark.parametrize("fn,kwargs,expected", CASES)
def test_replay_after_restart(fn, kwargs, expected):
    be = Backend()
    fn(be, **kwargs)
    # A fresh process re-derives everything from scratch: same args, same key.
    import importlib; importlib.reload(tools)
    getattr(tools, fn.__name__)(be, **kwargs)
    assert len(be.effects) == expected
Enter fullscreen mode Exit fullscreen mode

Run it and the naive tool fails all three, the keyed one passes all three. That's the whole point: the failure is mechanical, not a judgment call in code review.

The three modes each catch something different:

  • replay twice catches tools with no dedup at all.
  • ack lost catches the retry-after-timeout path, and the one where your wrapper retries but your key generator isn't stable across attempts.
  • replay after restart catches keys derived from process state: an in-memory counter, uuid4() per call, time.time(). Anything that doesn't survive the agent being resumed from a checkpoint.

What this found in practice

The harness earns its keep on the tools that look fine. The usual finds:

  • A key that included a run ID. Safe within a run, a duplicate across a resumed run. Fix: key on the business intent (recipient + template + the thing that triggered it), not the execution.
  • Read-modify-write "upserts". append_note(ticket, text) is not idempotent however it's phrased, because the second call appends again. The fix is to make the operation a set, not an append: set_note(ticket, note_id, text) where note_id comes from the intent.
  • Counters. increment(balance, 5) fails the replay test by definition. Either send the target value, or send a delta with a unique operation ID the backend can dedupe.
  • A wrapper that dedups on the response. It cached the result locally, so it passed the replay-twice test inside one process and failed the restart test. A local cache is not a ledger.

When the backend gives you no key to send

Some third-party tools take no idempotency key and offer nothing to read. The test still applies; you just can't pass it by sending a key. You pass it by owning the dedup yourself, with a small ledger written before the call:

import sqlite3

class Ledger:
    def __init__(self, path="ledger.db"):
        self.db = sqlite3.connect(path)
        self.db.execute("""CREATE TABLE IF NOT EXISTS sent
            (k TEXT PRIMARY KEY, state TEXT)""")

    def claim(self, k) -> bool:
        try:
            self.db.execute("INSERT INTO sent VALUES (?, 'pending')", (k,))
            self.db.commit()
            return True
        except sqlite3.IntegrityError:
            return False

    def done(self, k):
        self.db.execute("UPDATE sent SET state='done' WHERE k=?", (k,))
        self.db.commit()

def send_email_ledgered(be, led, to, subject):
    p = {"to": to, "subject": subject}
    k = intent_key("email", p)
    if not led.claim(k):
        return {"ok": True, "deduped": True}
    r = be.apply("email", p)               # no key available downstream
    led.done(k)
    return r
Enter fullscreen mode Exit fullscreen mode

Look at what that trades. A crash between claim and done leaves a pending row, so the next attempt is suppressed: you've chosen at-most-once over at-least-once. For an email that's usually right. For a payment you'd rather reconcile the pending rows by reading the effect, which is the verify-before-write step from the timeout post. Which one you want is a per-tool decision; the test just makes you write it down, because expected in the case table has to be a number.

The ledger version passes all three tests, but look at the ack-lost case: the retry is suppressed and returns deduped: True, so the caller learns the effect may have occurred, not that it did. Decide whether that return value is honest for your tool; the agent should be told the outcome is unconfirmed rather than success.

Wiring it into CI without it rotting

Three habits keep this from becoming a test nobody updates:

  1. Fail on unregistered tools. Iterate over your tool registry and assert every tool name has a row in CASES. A new tool with no case breaks the build. This is the single most useful line in the file.
  2. Mark read-only tools explicitly with expected = 0 effects, so a "read" that quietly writes (logging to a CRM, say) gets caught.
  3. Keep the fake honest. When a production incident shows a backend behaving differently, such as dedup windows that expire, add that behaviour to Backend and a case for it. A fake that is more forgiving than the real service gives you false confidence.
def test_every_tool_has_a_case():
    registered = {t.__name__ for t in tools.REGISTRY}
    covered = {c[0].__name__ for c in CASES}
    assert registered <= covered, registered - covered
Enter fullscreen mode Exit fullscreen mode

What it doesn't cover

It tests your side of the contract. It won't tell you that a vendor's dedup window is 24 hours and your retry queue holds work for 36, or that two different keys for the same intent were issued by two agents. The second one is a coordination problem; fleet retry patterns covers the shared-budget side of it, and what idempotent means has the vocabulary if you need to explain the failure to someone else.

What I'd actually do

Start with the registry assertion and the replay-twice test; that's twenty minutes and it will probably fail something today. Add ack-lost next, since it's the one that mirrors the production incident. Put restart last, and only if your agents resume from checkpoints, which most long-running ones eventually do.

Then, for each tool that fails, don't reach for a clever wrapper first. Ask whether the operation can be rewritten as a set instead of an append, a target instead of a delta. A tool that is idempotent by shape needs no key, no ledger, and no test you'll be tempted to skip.

Top comments (0)