An agent calls send_refund_email. The email provider takes eight seconds, your HTTP client times out at five, and the harness reports "tool failed: timeout" to the model. The model, reasonably, tries again. The provider had in fact accepted the first request, so the customer now has two emails. Swap "email" for "create ticket", "charge card" or "post to channel" and you have the most common way agents do real damage while behaving exactly as designed.
The root cause is not the model. It is that a timeout tells you nothing about whether the side effect happened, and the retry layer (yours, the SDK's, or the model's own) cannot tell either. This article covers how to make side-effecting tool calls safe to repeat: where the idempotency key comes from, a small ledger that enforces it, how to handle downstreams that offer no idempotency, and a test that proves it works.
Separate reads from writes, then key only the writes
Retrying a read is free. Retrying a write is a decision. Start by classifying every tool in your registry into one of three groups:
- Pure reads (
search_orders,get_invoice): retry freely, no key needed. - Naturally idempotent writes (
set_ticket_status(id, "closed"), upsert by a client-supplied ID): repeating them converges on the same end state. Still worth logging, but no ledger is required. - Non-idempotent writes (
send_email,create_ticket,charge,append_comment): each execution adds something new. These need a key.
The classification belongs in the tool definition, not in someone's head. A single field such as effect: "read" | "idempotent_write" | "append_write" lets the harness decide mechanically whether a failed call may be re-executed, and lets you audit the registry for tools nobody has classified.
Where the key comes from
The tempting design is to let the model supply an idempotency_key argument. Don't. Models regenerate plausible-looking strings, so a retry after a failure often arrives with a different key, which defeats the purpose, and the same model may reuse a key across two genuinely different actions.
Derive the key in the harness from things that are stable across a retry of the same intent and different across different intents:
key = sha256(run_id + ":" + tool_call_id + ":" + tool_name)tool_call_id is the identifier the model API attaches to each tool-use block in a response. If your harness retries the HTTP request to the downstream service within one tool call, or replays the same model turn after a crash, the ID is identical, so the key is identical. If the model decides to call the tool again in a later turn, it gets a new ID and a new key, which is correct: that is a new decision, and whether it is a wise decision is a prompt and approval-gate problem, not an idempotency problem.
Keep the hash of the arguments next to the key rather than inside it. If the same key ever arrives with different arguments, something is wrong (a replay bug, a mutated transcript) and the right response is to refuse loudly, not to execute.
A small ledger that enforces it
The ledger records each keyed call as in_progress before executing and done (with the stored result) afterwards. The essential property is that claiming the key is atomic, so two workers or two retries cannot both proceed.
import hashlib, json, sqlite3, time
db = sqlite3.connect("ledger.db", isolation_level=None)
db.execute("""CREATE TABLE IF NOT EXISTS ledger (
key TEXT PRIMARY KEY, args_hash TEXT NOT NULL,
state TEXT NOT NULL, result TEXT, started_at REAL)""")
STALE_AFTER = 120 # seconds an in_progress claim is trusted
def run_once(key, args, execute):
args_hash = hashlib.sha256(
json.dumps(args, sort_keys=True).encode()).hexdigest()
try:
db.execute("INSERT INTO ledger VALUES (?,?,?,?,?)",
(key, args_hash, "in_progress", None, time.time()))
except sqlite3.IntegrityError:
row = db.execute(
"SELECT args_hash, state, result, started_at FROM ledger WHERE key=?",
(key,)).fetchone()
if row[0] != args_hash:
return {"error": "key_reused_with_different_args"}
if row[1] == "done":
return json.loads(row[2]) # replay stored result
if time.time() - row[3] < STALE_AFTER:
return {"error": "in_progress", "retry_after_s": 5}
return {"error": "outcome_unknown",
"hint": "previous attempt may have succeeded; verify before retrying"}
result = execute(args) # the real side effect
db.execute("UPDATE ledger SET state='done', result=? WHERE key=?",
(json.dumps(result), key))
return resultWhy it works: the primary-key insert is the claim, so concurrent duplicates fail at the database rather than racing in application code. A retry after success returns the stored result without touching the downstream, so the model sees the same "sent, message id 81" it would have seen the first time.
The interesting branch is the last one. If the process died between execute and the UPDATE, the row is stuck in in_progress and nobody knows whether the email left. The ledger cannot resolve this by itself. It must say so honestly (outcome_unknown) instead of guessing in either direction, because guessing "failed" re-sends and guessing "done" silently drops the action. How you resolve it depends on the downstream, which is the next section.
Two limits to be aware of. First, this ledger is only as strong as its storage: an in-memory dict dies with the process, and a SQLite file on one node does not coordinate several workers. Use whatever shared, durable store your service already trusts. Second, a ledger gives you at-most-once from your side, not exactly-once. The crash window above is inherent.
When the downstream can't help you, make it checkable
If the provider supports idempotency keys, pass your derived key through and let the provider deduplicate. Stripe's API documents this model for POST requests: it saves the status code and body of the first request made with a key and returns that saved response on retries, compares the parameters of retries to the original and errors if they differ, and may prune keys after at least 24 hours. Read the semantics of whichever API you use, because the retention window and the treatment of concurrent requests differ, and a key reused after pruning is a new request.
Many downstreams have no such feature. Then the goal is to turn the unknown outcome into a lookup. Put your key in a field the downstream stores, such as an external reference on the ticket, a header you can later search, or a tag on the message. The resolution path for outcome_unknown becomes: query the downstream for that reference; if found, mark the ledger done with the found object; if not found, it is now safe to execute.
This has its own failure mode: the downstream may be eventually consistent, so a search a second after the write finds nothing. Wait out the known indexing delay before concluding "absent", or route the case to a human. For high-stakes actions such as payments, "route to a human" is the correct default for unknown outcomes.
Also decide what the model sees. A raw timeout invites a blind retry. Return a structured result instead: {"status": "unknown", "do_not_retry": true, "next": "call lookup_message with ref=..."}. Give it the verification tool and say plainly that the action may have happened.
Prove it with an ack-lost test
The failure you care about is not "the call fails". It is "the call succeeds and the acknowledgement is lost". Test exactly that with a fake downstream that records every real execution:
def test_lost_ack_does_not_double_send():
sent = []
def flaky_send(args):
sent.append(args) # side effect happens...
raise TimeoutError("ack lost") # ...but the caller never hears
key = "run1:call_a:send_email"
args = {"to": "a@example.com", "body": "Refund issued"}
try: run_once(key, args, flaky_send)
except TimeoutError: pass
# simulate the model/harness retrying the same tool call
out = run_once(key, args, lambda a: sent.append(a) or {"id": 2})
assert len(sent) == 1 # the real send happened once
assert out["error"] in ("in_progress", "outcome_unknown")The assertion that matters is len(sent) == 1. Run variants: a crash after the claim but before execution, two concurrent calls with the same key, and the same key with different arguments. If you use a real provider's sandbox, add one case where the stored result is replayed and confirm the model-facing text is identical.
Checklist
- Every tool in the registry declares whether it is a read, an idempotent write, or an append-style write; unclassified tools fail a registry lint.
- The key is derived in the harness from the run ID and the model's tool-call ID, never supplied by the model.
- Claiming the key is atomic and happens before the side effect; the arguments hash is stored and mismatches are refused.
- The
in_progressstate has a staleness rule that yieldsoutcome_unknown, not a guess. - Downstream keys or searchable references are used where the provider supports them; otherwise unknown outcomes resolve by lookup or by a human.
- The model receives structured "unknown, do not retry, verify with X" results rather than a bare timeout.
- A lost-acknowledgement test asserts a single real execution.
Further reading
- Stripe API reference: Idempotent requests, for one widely used provider's key semantics (saved responses, parameter comparison, key pruning).
Comments (0)
No comments yet — be the first.
Sign in to leave a comment.