Skip to content

sqlite3: ABBA deadlock on free-threaded builds when pooled connections evict cached statements #162919

Backlog

Description

@Creeper19472

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)

  1. Thread 1 (writer) uses pooled connection c1, populating c1's per-connection functools._lru_cache_wrapper statement cache with sqlite3.Statement objects owned by Thread 1 (default cached_statements=128).
  2. Thread 1 releases c1 back to the pool, acquires a different connection c2, and starts a write transaction (BEGIN IMMEDIATE), holding the SQLite database file write lock.
  3. Thread 2 (contender) checks out c1 exclusively and executes a statement (e.g., BEGIN IMMEDIATE) that evicts one of Thread 1's cached sqlite3.Statement objects from c1's statement cache.
  4. Under free-threaded biased reference counting / deferred deallocation, Thread 2 does not immediately run statement_dealloc on the evicted sqlite3.Statement; instead it queues it for deferred decref (_Py_DecRefShared / _Py_HandlePending).
  5. Thread 2 immediately enters sqlite3_step("BEGIN IMMEDIATE") on c1, which acquires c1->mutex and sleeps inside SQLite's busy handler waiting for Thread 1 to release the database file write lock.
  6. Meanwhile, while still holding the database file write lock on c2, Thread 1 hits _Py_HandlePending() during ordinary Python execution, drains the deferred decref, runs statement_dealloc -> sqlite3_finalize() on the evicted statement belonging to c1, and blocks trying to acquire c1->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=0 to sqlite3.connect() avoids retaining sqlite3.Statement objects 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 evicted sqlite3_stmt handles eagerly on the thread performing cache eviction (or before releasing control / outside tp_dealloc) would prevent cross-thread deferred tp_dealloc from acquiring db->mutex while another thread is blocked inside sqlite3_step().

CPython versions tested on:

3.15

Operating systems tested on:

Linux, Windows

Linked PRs

Activity

  1. added
    type-bug
    extension-modules
    on Dec 1, 2026
  2. picnixz commented on Dec 1, 2026

    @picnixz
    Member

    I am not entirely sure that sqlite3 is actually ready for free-threading entirely so this could definitely be a known limitation

  3. nascheme commented on Dec 2, 2026

    @nascheme
    Member

    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_dealloc but instead handle the delay gracefully. I wrapped my changes in Py_GIL_DISABLED blocks, even though I think they would be safe/find for the GIL-enabled build too. It seems safer that way.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    extension-modulestopic-free-threadingtopic-sqlite3type-bug

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions