AI Agent Tool Call Idempotency in Python: A SQLite Failure Test
A ticket-creation tool commits a database write. Its response is lost. The agent sees a timeout and calls the tool again. Did the first attempt fail, or did only its response fail? You cannot answer that question by inc
A ticket-creation tool commits a database write. Its response is lost. The agent sees a timeout and calls the tool again. Did the first attempt fail, or did only its response fail?
You cannot answer that question by increasing the model's intelligence or adding exponential backoff. The application needs a durable operation identity and a mutation that respects it.
The short answer: for a tool whose entire effect is a local database write, store a stable operation key alongside the mutation, enforce uniqueness inside a transaction, and return the original result when the same operation is retried. Reject attempts to reuse the key with different arguments.
This tutorial uses Python and SQLite to demonstrate the boundary. It requires no model API, framework or external service.
1. A retry is not a new operation
Consider an agent that creates an incident ticket. There are three separate identifiers:
- The agent run ID identifies a workflow execution.
- The operation key identifies the intended business action.
- The attempt ID identifies one execution attempt for tracing.
The operation key must survive retries and process restarts. Generate it in trusted application code when the action is approved, persist it with the workflow state, and reuse it during recovery. A retry must not invent a new key because the model paraphrased the instruction.
Do not derive identity from the arguments alone: two intentionally separate tickets may have identical subjects. Conversely, if the model changes the subject during a retry, treating the changed payload as a new operation may cause an unintended second write.
Scope the key to an authenticated tenant or principal and action type. In this example the table is dedicated to creating tickets, so the action type is implicit. The trusted caller supplies the tenant and the operation key; neither should be accepted as proof of permission just because the model provided it.
2. A transactional idempotency key in Python
The ticket itself is the durable record. There is no separate cache that can disagree with the database after a crash. The unique constraint prevents two tickets for the same tenant and operation key.
Save the following as demo.py and run it with Python 3.11 or later. The included example was executed on Python 3.13.5.
import sqlite3
import tempfile
from pathlib import Path
class Conflict(Exception):
pass
def create_ticket(db, tenant, key, subject, fail=False):
# Explicit transaction mode, also works on Python 3.11.
con = sqlite3.connect(db, isolation_level=None, timeout=5)
try:
con.execute("BEGIN IMMEDIATE")
row = con.execute(
"SELECT id, subject FROM tickets WHERE tenant=? AND op_key=?",
(tenant, key),
).fetchone()
if row:
if row[1] != subject:
raise Conflict("same operation, different subject")
ticket_id = row[0]
else:
ticket_id = con.execute(
"INSERT INTO tickets(tenant, op_key, subject) VALUES(?,?,?)",
(tenant, key, subject),
).lastrowid
if fail:
raise RuntimeError("injected failure before commit")
con.commit()
return ticket_id
except BaseException:
con.rollback()
raise
finally:
con.close()
with tempfile.TemporaryDirectory() as folder:
db = Path(folder) / "tickets.db"
con = sqlite3.connect(db)
con.execute("""CREATE TABLE tickets(
id INTEGER PRIMARY KEY, tenant TEXT NOT NULL,
op_key TEXT NOT NULL, subject TEXT NOT NULL,
UNIQUE(tenant, op_key))""")
con.close()
first = create_ticket(db, "team-a", "op-1", "Investigate latency")
assert create_ticket(db, "team-a", "op-1", "Investigate latency") == first
try:
create_ticket(db, "team-a", "op-1", "Different task")
except Conflict:
pass
else:
raise AssertionError("expected conflict")
assert create_ticket(db, "team-b", "op-1", "Investigate latency") != first
try:
create_ticket(db, "team-a", "op-2", "Rollback test", fail=True)
except RuntimeError:
pass
else:
raise AssertionError("expected rollback")
con = sqlite3.connect(db)
assert con.execute("SELECT COUNT(*) FROM tickets WHERE op_key='op-2'").fetchone()[0] == 0
con.close()
create_ticket(db, "team-a", "op-2", "Rollback test")
con = sqlite3.connect(db)
assert con.execute("SELECT COUNT(*) FROM tickets").fetchone()[0] == 3
con.close()
print("PASS: replay, changed arguments, tenant isolation, rollback, retry")
The observed output from a local run was:
PASS: replay, changed arguments, tenant isolation, rollback, retry
3. What the failure tests actually prove
| Scenario | Observed result |
|---|---|
| Repeat the committed operation | Same ticket ID |
| Reuse the key with another subject | Conflict exception |
| Reuse the key under another tenant | Distinct ticket ID |
| Inject an exception before commit | No ticket for that key remains |
| Retry the rolled-back operation | Ticket created once; three total rows |
Every invocation opens a fresh database connection. Replaying after a successful return models a caller that did not receive or retain the response; it is not a simulated network failure or process termination.
The pre-commit exception is a deterministic fault-injection check. It demonstrates rollback on that code path, not resistance to arbitrary operating-system crashes.
BEGIN IMMEDIATE obtains a write transaction before the lookup. This avoids the simple check-then-insert race in which two callers independently conclude that an operation is absent. SQLite still serializes writers, and a busy database may raise an error. The unique constraint is an additional database-enforced invariant.
This example was not load-tested with concurrent workers. Measure contention and test concurrent retries before adapting the pattern to a production service. The stored subject is immutable in this demo; in an editable ticketing system retain the original request fingerprint and result separately, transactionally with the effect.
4. Why this does not guarantee exactly-once external effects
A local transaction cannot atomically commit an HTTP request to an unrelated remote service.
Suppose the agent sends an email through an external API and then updates a local ledger. If the remote server accepts the email but the application crashes before saving the result, the local state cannot establish whether delivery occurred.
Use a provider's documented idempotency contract where available, reuse the same key within its supported retention window, and reconcile uncertain outcomes with the provider. If no such mechanism exists, route ambiguous writes to a reconciliation or human-review process rather than retrying blindly. An outbox can make the intent durable, but it does not by itself eliminate duplicate delivery at the recipient.
Keep authorization independent of idempotency. A previously approved operation is not a universal permission to act on a different tenant, resource or payload.
5. A practical production checklist
Record operation keys, attempt identifiers, deduplication outcomes, conflicts and unresolved effects in structured telemetry. Avoid exposing sensitive arguments in logs. Decide how long operation records must survive based on the maximum legitimate retry window and the consequences of late replays.
Use separate policies for read tools, local transactional writes, and remote side effects. A general agent retry decorator cannot know the safety contract of every tool it wraps.
The useful question is not whether an agent can retry. It is whether the application knows what retrying means for each action.
Further reading
- Python sqlite3 transaction behavior
- AWS Builders' Library: Making retries safe with idempotent APIs
- Pydantic AI production guide
Which of your agent's write tools can recover safely after an ambiguous timeout, and which require reconciliation?
AI disclosure: This article and its example were generated with ChatGPT. The example was executed locally on Python 3.13.5. No live provider, concurrency benchmark or human review is claimed in this draft.
Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.