stage20-idempotency-stress.py
TEXT FILE1.2 KB · Public source code for developers, search crawlers and AI agents
1import sqlite3
2from concurrent.futures import ThreadPoolExecutor
3from tempfile import TemporaryDirectory
4from pathlib import Path
5
6def record(path, request_id, intent):
7 with sqlite3.connect(path, timeout=10) as db:
8 db.execute("BEGIN IMMEDIATE")
9 row = db.execute("SELECT intent FROM requests WHERE id=?", (request_id,)).fetchone()
10 if row:
11 return "replay" if row[0] == intent else "conflict"
12 db.execute("INSERT INTO requests VALUES (?,?)", (request_id, intent))
13 return "new"
14
15if __name__ == "__main__":
16 with TemporaryDirectory() as directory:
17 path = Path(directory)/"ledger.db"
18 with sqlite3.connect(path) as db:
19 db.execute("CREATE TABLE requests(id TEXT PRIMARY KEY, intent TEXT NOT NULL)")
20 with ThreadPoolExecutor(max_workers=8) as pool:
21 outcomes = list(pool.map(lambda _: record(path, "r1", "intent-A"), range(100)))
22 assert outcomes.count("new") == 1 and outcomes.count("replay") == 99
23 assert record(path, "r1", "intent-B") == "conflict"
24 assert record(path, "r2", "intent-A") == "new"
25 print("100 concurrent submissions: one new record, 99 replays")Read-only source · Select a line number to link directly · Raw download above
