Repository navigation
Description
Bug report
On free-threaded Python (GIL disabled), reusing sqlite3.Connection objects across threads (check_same_thread=False, strictly one thread using each connection at a time — the standard connection-pool pattern such as SQLAlchemy's default QueuePool for file-backed SQLite) can trigger an ABBA deadlock between SQLite's per-connection mutex (db->mutex) and SQLite's database file write lock, stalling both threads for the entire busy_timeout duration and raising sqlite3.OperationalError: database is locked.
Notably, this occurs without concurrent access to the same Connection and without any registered Python callbacks (unlike gh-118172, gh-160699, and gh-161065).
Root cause (ABBA lock inversion)
- Thread 1 (
writer) uses pooled connectionc1, populatingc1's per-connectionfunctools._lru_cache_wrapperstatement cache withsqlite3.Statementobjects owned by Thread 1 (defaultcached_statements=128). - Thread 1 releases
c1back to the pool, acquires a different connectionc2, and starts a write transaction (BEGIN IMMEDIATE), holding the SQLite database file write lock. - Thread 2 (
contender) checks outc1exclusively and executes a statement (e.g.,BEGIN IMMEDIATE) that evicts one of Thread 1's cachedsqlite3.Statementobjects fromc1's statement cache. - Under free-threaded biased reference counting / deferred deallocation, Thread 2 does not immediately run
statement_deallocon the evictedsqlite3.Statement; instead it queues it for deferred decref (_Py_DecRefShared/_Py_HandlePending). - Thread 2 immediately enters
sqlite3_step("BEGIN IMMEDIATE")onc1, which acquiresc1->mutexand sleeps inside SQLite's busy handler waiting for Thread 1 to release the database file write lock. - Meanwhile, while still holding the database file write lock on
c2, Thread 1 hits_Py_HandlePending()during ordinary Python execution, drains the deferred decref, runsstatement_dealloc->sqlite3_finalize()on the evicted statement belonging toc1, and blocks trying to acquirec1->mutex.
Both threads remain deadlocked until c1's busy_timeout expires (e.g., 10–30 s in production configurations). When sqlite3_step() finally returns SQLITE_BUSY and releases c1->mutex, Thread 1 immediately unblocks and commits c2 within ~1 ms.
Native thread stacks captured during the hang (gdb, Windows x64, Python 3.15.2t)
Thread "writer" (holding DB write lock on c2, blocked on c1->mutex):
#0 ntdll!ZwWaitForAlertByThreadId ()
...
#3 ntdll!RtlEnterCriticalSection ()
#4 sqlite3_finalize () from sqlite3.dll
#5 ?? () from _sqlite3.cp315t-win_amd64.pyd
#6 python315t!_Py_DecRefShared ()
#7 python315t!_Py_HandlePending ()
...
#12 python315t!_PyEval_EvalFrameDefault ()
Thread "contender" (holding c1->mutex, waiting for DB write lock on c1):
#0 ntdll!ZwDelayExecution ()
#2 KernelBase!SleepEx ()
...
#7 sqlite3_step () from sqlite3.dll
#8 ?? () from _sqlite3.cp315t-win_amd64.pyd
Minimal reproducible example (stdlib only)
import sqlite3
import sys
import tempfile
import threading
import time
from pathlib import Path
def run_repro(cached_statements: int, max_rounds: int = 30) -> None:
with tempfile.TemporaryDirectory() as td:
db = str(Path(td) / "repro.db")
c1 = sqlite3.connect(
db,
timeout=1.0,
autocommit=sqlite3.LEGACY_TRANSACTION_CONTROL,
check_same_thread=False,
cached_statements=cached_statements,
)
c1.execute("PRAGMA journal_mode=WAL")
c1.execute("PRAGMA busy_timeout=1000")
c1.execute("CREATE TABLE t (x INT)")
c1.commit()
c2 = sqlite3.connect(
db,
timeout=1.0,
autocommit=sqlite3.LEGACY_TRANSACTION_CONTROL,
check_same_thread=False,
cached_statements=cached_statements,
)
c2.execute("PRAGMA busy_timeout=1000")
try:
for round_idx in range(max_rounds):
t1_ready = threading.Event()
error: list[BaseException] = []
t1_elapsed: list[float] = []
def writer() -> None:
# Strictly exclusive use of c1 before handoff to contender
base = round_idx * 5
for k in range(base, base + 5):
c1.execute(f"SELECT {k}").fetchall()
c2.execute("BEGIN IMMEDIATE")
t1_ready.set()
t0 = time.monotonic()
deadline = t0 + 0.05
while time.monotonic() < deadline:
_ = [i for i in range(100)]
t1_elapsed.append(time.monotonic() - t0)
c2.commit()
def contender() -> None:
t1_ready.wait()
time.sleep(0.01)
try:
# Strictly exclusive use of c1; evicts a writer-owned
# cached Statement right before sqlite3_step holds c1->mutex
c1.execute("BEGIN IMMEDIATE")
c1.rollback()
except BaseException as exc:
error.append(exc)
th1 = threading.Thread(target=writer)
th2 = threading.Thread(target=contender)
th1.start()
th2.start()
th1.join()
th2.join()
if error:
print(
f"cached_statements={cached_statements}: DEADLOCKED on round {round_idx} "
f"(writer held lock {t1_elapsed[0]:.3f}s): "
f"{type(error[0]).__name__}: {error[0]}"
)
return
print(f"cached_statements={cached_statements}: all {max_rounds} rounds passed")
finally:
c1.close()
c2.close()
print("Python:", sys.version, "GIL enabled:", sys._is_gil_enabled())
run_repro(cached_statements=5)
run_repro(cached_statements=0)Observed output
On Python 3.15.2 free-threaded (GIL enabled: False):
Python: 3.15.2 free-threading build (tags/v3.15.2:5e58eaa, Oct 25 2026, 17:19:11) [MSC v.1951 64 bit (AMD64)] GIL enabled: False
cached_statements=5: DEADLOCKED on round 0 (writer held lock 1.099s): OperationalError: database is locked
cached_statements=0: all 30 rounds passed
With PYTHON_GIL=1, both cached_statements=5 and cached_statements=0 pass all 30 rounds with ~0.05 s writer duration.
We also observed the exact same failure mode on Linux (Ubuntu 26.04, Python 3.15.2 free-threaded) in CI tests using SQLAlchemy QueuePool against file-backed SQLite.
Workaround / Possible directions
- Workaround: Passing
cached_statements=0tosqlite3.connect()avoids retainingsqlite3.Statementobjects across threads on the connection, so each statement is finalized synchronously on the executing thread when its cursor finishes/closes. - Possible fix in
_sqlite3: Finalizing evictedsqlite3_stmthandles eagerly on the thread performing cache eviction (or before releasing control / outsidetp_dealloc) would prevent cross-thread deferredtp_deallocfrom acquiringdb->mutexwhile another thread is blocked insidesqlite3_step().
CPython versions tested on:
3.15
Operating systems tested on:
Linux, Windows
Linked PRs
Metadata
Metadata
Assignees
Labels
Projects
- StatusShow more project fieldsNo status
Activity
picnixz commentedon Dec 1, 2026
I am not entirely sure that sqlite3 is actually ready for free-threading entirely so this could definitely be a known limitation
fix(sqlite): implement a workaround by setting `cached_statements=0` …
nascheme commentedon Dec 2, 2026
It seems this is (in theory) supported and so I took a shot at fixing it. I believe the best strategy is not to try to ensure eager calling of
tp_deallocbut instead handle the delay gracefully. I wrapped my changes inPy_GIL_DISABLEDblocks, even though I think they would be safe/find for the GIL-enabled build too. It seems safer that way.