You hit SQLite's famous deferred lock-upgrade deadlock:
In Python sqlite3 / aiosqlite, transactions default to BEGIN DEFERRED. When two connections both start a DEFERRED transaction as readers and then both attempt to upgrade to a write lock, SQLite cannot wait on busy_timeout—because neither connection can release its read snapshot without rolling back! So SQLite immediately aborts one connection in <1ms with database is locked.
Here are the two fixes you need together in production:
1. Always Use BEGIN IMMEDIATE + Set PRAGMA busy_timeout Per Connection
BEGIN IMMEDIATE acquires the write lock upfront at transaction start, allowing SQLite's busy_timeout to sleep and retry cleanly instead of deadlocking:
import aiosqlite
async def get_db_connection(db_path: str) -> aiosqlite.Connection:
# isolation_level=None gives explicit manual transaction control
conn = await aiosqlite.connect(db_path, isolation_level=None)
await conn.execute("PRAGMA journal_mode=WAL;")
await conn.execute("PRAGMA synchronous=NORMAL;")
await conn.execute("PRAGMA busy_timeout=5000;") # Wait up to 5s cleanly
return conn
async def safe_write(conn: aiosqlite.Connection, sql: str, params: tuple):
await conn.execute("BEGIN IMMEDIATE;")
try:
await conn.execute(sql, params)
await conn.execute("COMMIT;")
except Exception:
await conn.execute("ROLLBACK;")
raise
2. Best Practice for High-Concurrency Sub-Agents: Single-Writer asyncio.Queue
Since SQLite only allows one writer at a time anyway, funnel all writes from your 4 parallel sub-agents through one lightweight background writer coroutine while letting all 4 sub-agents read concurrently in WAL mode:
import asyncio
class SqliteWriteActor:
def __init__(self, db_path: str):
self.db_path = db_path
self.queue: asyncio.Queue = asyncio.Queue()
async def start(self):
self.conn = await get_db_connection(self.db_path)
self._task = asyncio.create_task(self._writer_loop())
async def _writer_loop(self):
while True:
sql, params, future = await self.queue.get()
try:
await safe_write(self.conn, sql, params)
future.set_result(True)
except Exception as exc:
future.set_exception(exc)
finally:
self.queue.task_done()
async def execute_write(self, sql: str, params: tuple = ()):
fut = asyncio.get_running_loop().create_future()
await self.queue.put((sql, params, fut))
return await fut
With BEGIN IMMEDIATE + SqliteWriteActor, 10+ concurrent sub-agents can hammer writes simultaneously with zero database is locked exceptions.