Skip to content

gh-162919: Don't call into SQLite from deallocators on the free-threaded build - #162979

Open
nascheme wants to merge 3 commits into
python:mainfrom
nascheme:gh-162919-sqlite-stmt-finalize
Open

nascheme wants to merge 3 commits into
python:mainfrom
nascheme:gh-162919-sqlite-stmt-finalize

Conversation

@nascheme

@nascheme nascheme commented Dec 2, 2026 •

Copy link
Copy Markdown
Member

On the free-threaded build, a pooled sqlite3 connection could stall until
the busy timeout expired and then fail with "database is locked".

The sequence, with two connections c1 and c2 to the same database file:

  1. Thread T1 uses c1, filling its statement cache, then hands c1 back.
  2. T1 takes the database write lock through c2.
  3. Thread T2 uses c1 and evicts one of the cached statements. T2 is not
    the owner of the Statement object, so the decref is queued for T1.
  4. T2 calls sqlite3_step() on c1. It holds the mutex of c1 and waits
    in the busy handler for the write lock.
  5. T1 merges the queued decref. stmt_dealloc() calls sqlite3_finalize(),
    which blocks on the mutex of c1.

T1 holds the lock T2 waits for, and T2 holds the mutex T1 waits for. Neither
makes progress until the busy timeout of c1 expires. The application never
uses the connection from two threads at once; it is the interpreter that
touches c1 from a second thread.

Why this design

The root problem is not the statement cache: it is that a deallocator does
work that requires using the connection, and on the free-threaded build we
cannot predict which thread will run a deallocator, or when:

  • A decref from a thread that does not own the object is queued (biased
    reference counting), and the owner deallocates the object later, at its
    next eval breaker check. If the owner has exited, the thread that merges
    the refcount does it.
  • Some decrefs are delayed until a quiescent state (QSBR) and run in
    whichever thread processes them.
  • Objects in reference cycles are freed by the GC, in whichever thread
    triggers a collection. (This one also applies to the default build, but
    rarely matters there.)

Making the last decref deallocate immediately in the thread that dropped
it, e.g. by merging the refcount of statements when they are created, would
only handle the first case, and only for statement-cache eviction. Instead,
this PR accepts that tp_dealloc can run in an "unexpected" thread and
makes the deallocators not use the connection unless that is known to be
safe. The work is handed to a thread that is using the connection.

Two SQLite threading modes have to be handled:

  • Serialized mode (the default for most builds): the connection mutex
    serializes calls, but waiting for it from an arbitrary thread can stall as
    shown above.
  • Multi-thread mode (the system SQLite on Apple platforms): a connection may
    only be used by one thread at a time, and it is up to the application to
    ensure that. The application cannot know when a deallocator runs. Apple
    builds SQLite with SQLITE_ENABLE_MULTITHREADED_CHECKS, which gives the
    connection a mutex whose only purpose is to detect misuse: contention on it
    logs "illegal multi-threaded access to database connection" and the
    process aborts. An earlier version of this PR tried the mutex with
    sqlite3_mutex_try() and crashed the iOS CI job this way.

The change

The new code is only compiled on the free-threaded build (Py_GIL_DISABLED).
The default build is unchanged.

Statements (stmt_dealloc())

While the connection is open, stmt_dealloc() does not call into SQLite.
It puts the dead statement on a list shared by the connection and its
statements. The list is processed the next time the connection prepares or
executes a statement, and when it is closed, i.e. by a thread that is using
the connection.

Delaying sqlite3_finalize() is not observable: by the time a statement is
deallocated it has been reset (cursors reset their statement before dropping
it, and cached statements are idle), so finalizing only frees memory owned by
the connection. It holds no locks on the database file. The cost is that
dead statements stay in memory until the connection is used again.

Cursors (cursor_clear())

When a cursor that was not exhausted or closed is deallocated,
cursor_clear() resets its statement. This has the same problem, but
unlike finalizing, resetting is observable: an unfinished SELECT holds a
read transaction, and resetting it releases the lock on the database file.
Code like this relies on that:

cur = con.execute("select * from t")
cur.fetchone()
del cur
other_con.execute("insert into t values (1)")  # needs the lock released

So the reset is still done right away when that is known to be safe: the
connection is open and restricted to the current thread
(check_same_thread=True, the default, and this is the thread that created
it). Then no other thread can be using the connection. Otherwise the
statement goes on a second list (with a strong reference) and is reset when
the connection is next used, or closed. Holding on to the statement is
safe: a cursor only holds a statement while it is busy, and the execute
path never reuses a busy cached statement.

The behavior change is limited to cursors deallocated in a thread other
than the connection's thread, or on connections with
check_same_thread=False: there, the read lock of an abandoned cursor is
released when the connection is next used instead of immediately.

After close

After close(), nobody uses the connection anymore, so statements are reset
and finalized by whichever thread deallocates them. The database stays
open as a "zombie" until its last statement is finalized, and in
multi-thread mode these calls must not overlap.

One thread at a time processes the lists (a processing flag in the shared
object). A deallocator that finds the lists being processed, by another
thread or by its own thread further up the stack, puts the statement on a
list and returns; the processing thread empties the lists before it clears
the flag. Deallocators never wait for each other. A plain lock would not work
here: Python code can run inside sqlite3_reset() (an aggregate's
finalize() when an unfinished aggregate is reset), and if it drops another
busy cursor of the same connection, that deallocator would wait for the
lock held by its own thread. close() itself processes the lists and calls
sqlite3_close_v2() as the processing thread.

Implementation notes

  • The lists live in a small refcounted struct rather than in the connection
    object, because a statement can outlive its connection object.
  • The lists are intrusive (a next_pending field in Statement): deferring
    never allocates.
  • The processing thread holds its own reference to the shared struct:
    finalizing the statements it processes drops theirs.
  • The flag is cleared under the mutex, when the lists are seen empty, so a
    statement pushed by another thread cannot be left behind.

Not covered

  • The blob deallocator still calls sqlite3_blob_close() from whatever
    thread deallocates the blob. That needs a blob that was not closed to be
    deallocated by another thread while the connection is in use.
  • Cursor.__init__() on an already initialized cursor drops a busy
    statement without resetting it (pre-existing, both builds).

Testing

  • New test ThreadTests.test_dealloc_statement_of_busy_connection, based on
    the script from the issue. Without the fix it fails on the free-threaded
    build with "database is locked" after the busy timeout.
  • test_sqlite3 passes on a free-threaded debug build, including -R 3:3.
  • To reproduce the iOS failure locally, SQLite 3.46.1 was built in
    multi-thread mode with SQLITE_ENABLE_MULTITHREADED_CHECKS, patched to
    abort on contention, and loaded with LD_LIBRARY_PATH. With it, the new
    test aborted with the earlier version of this PR; test_sqlite3 (also
    with -R 3:3) now passes. Stress scripts for statement eviction,
    cursors deallocated by another thread, and finalizing after close each
    aborted before the corresponding fix and pass now.
  • The design was model checked with TLA+ (all SQLite calls, the lists, the
    flag, deallocation in any thread including from Python code run inside
    SQLite, check_same_thread on and off). The check found that an earlier
    version, which serialized the calls after close with a lock, could
    deadlock when an aggregate's finalize() dropped another busy cursor; a
    script doing that hung with that version and passes now.

Note: this PR was developed with the assistance of an LLM

…statement

On the free-threaded build, when a thread that does not own a statement
drops the last reference to it (e.g. evicts it from the statement cache),
the decref is queued and the owning thread deallocates the statement later,
at an arbitrary point.  If the owning thread holds the database lock through
another connection while a different thread uses the statement's connection
and waits for that lock, sqlite3_finalize() blocks on the connection mutex
and both threads stall until the busy timeout expires.

On the free-threaded build, put the dead statement on a list shared with the
connection and finalize it only if the connection mutex can be taken without
blocking.  Statements left on the list are finalized the next time the
connection prepares or executes a statement, or when it is closed.  The
default build is unchanged.
In multi-thread mode (the system SQLite on Apple platforms) there is no
connection mutex: sqlite3_db_mutex() returns NULL and sqlite3_mutex_try(NULL)
reports success.  stmt_dealloc() then finalized the statement while another
thread could be using the connection, which is not allowed in that mode.

Leave the statement on the pending list in that case, so that it is finalized
by a thread that is using the connection.
…onnection is open

On the free-threaded build, a statement or cursor can be deallocated by any
thread at any point (queued decrefs from non-owner threads, delayed decrefs,
the GC), so the deallocating thread may not be allowed to use the connection
at that moment.  The previous commit relied on the connection mutex being
NULL in multi-thread mode, but with SQLITE_ENABLE_MULTITHREADED_CHECKS (as
in the system SQLite on Apple platforms) the connection has a mutex whose
only purpose is to detect misuse: any contention on it is reported as
"illegal multi-threaded access to database connection" and the process
aborts.

- stmt_dealloc() never finalizes while the connection is open: the dead
  statement always goes on the pending list.  This removes the try-lock
  path.  Dead statements are already reset and hold no locks.
- cursor_clear() resets an unfinished cursor's statement directly if the
  connection is open and either restricted to the current thread
  (check_same_thread and this is its thread), or SQLite serializes access
  to it and the current thread is the last one that used it (recorded in
  pysqlite_check_thread()).  Concurrent use is allowed in serialized mode,
  so the second check is not needed for safety: it only makes it unlikely
  that the deallocator waits for the connection mutex.  Otherwise the
  statement goes on a second pending list and is reset by the next thread
  that executes a statement on the connection, commits or rolls back.
  Resetting releases the read lock, so the common cases keep doing it right
  away; a connection pool's reset-on-return releases it otherwise.
- Two cursors can use the same statement (a failed executemany() resets a
  cached statement that another cursor is using, and a third cursor can
  then take it from the cache).  A statement already on the reset list is
  not pushed again: the deallocator only drops its reference.
- After close(), statements are reset and finalized by whichever thread
  deallocates them.  One thread at a time processes the pending lists (a
  processing flag in the shared object): a deallocator that finds them being
  processed, by another thread or by its own thread further up the stack,
  pushes the statement and returns, and the processing thread empties the
  lists before clearing the flag.  close() processes the lists and calls
  sqlite3_close_v2() as the processing thread.  A plain lock would deadlock:
  Python code can run inside sqlite3_reset() (an aggregate's finalize()) and
  drop another busy cursor of the same connection.
@nascheme nascheme changed the title gh-162919: Don't block on DB mutex when deallocating a sqlite3 statement gh-162919: Don't call into SQLite from deallocators on the free-threaded build Dec 3, 2026
@nascheme
nascheme marked this pull request as ready for review December 3, 2026 20:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant