Repository navigation
Conversation
…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
marked this pull request as ready for review
December 3, 2026 20:40
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
On the free-threaded build, a pooled
sqlite3connection could stall untilthe busy timeout expired and then fail with "database is locked".
The sequence, with two connections
c1andc2to the same database file:c1, filling its statement cache, then handsc1back.c2.c1and evicts one of the cached statements. T2 is notthe owner of the
Statementobject, so the decref is queued for T1.sqlite3_step()onc1. It holds the mutex ofc1and waitsin the busy handler for the write lock.
stmt_dealloc()callssqlite3_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
c1expires. The application neveruses the connection from two threads at once; it is the interpreter that
touches
c1from 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:
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.
whichever thread processes them.
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_dealloccan run in an "unexpected" thread andmakes 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:
serializes calls, but waiting for it from an arbitrary thread can stall as
shown above.
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 theconnection 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 isdeallocated 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, butunlike finalizing, resetting is observable: an unfinished
SELECTholds aread transaction, and resetting it releases the lock on the database file.
Code like this relies on that:
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 createdit). 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 isreleased when the connection is next used instead of immediately.
After close
After
close(), nobody uses the connection anymore, so statements are resetand 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
processingflag in the sharedobject). 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'sfinalize()when an unfinished aggregate is reset), and if it drops anotherbusy cursor of the same connection, that deallocator would wait for the
lock held by its own thread.
close()itself processes the lists and callssqlite3_close_v2()as the processing thread.Implementation notes
object, because a statement can outlive its connection object.
next_pendingfield inStatement): deferringnever allocates.
finalizing the statements it processes drops theirs.
statement pushed by another thread cannot be left behind.
Not covered
sqlite3_blob_close()from whateverthread 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 busystatement without resetting it (pre-existing, both builds).
Testing
ThreadTests.test_dealloc_statement_of_busy_connection, based onthe script from the issue. Without the fix it fails on the free-threaded
build with "database is locked" after the busy timeout.
test_sqlite3passes on a free-threaded debug build, including-R 3:3.multi-thread mode with
SQLITE_ENABLE_MULTITHREADED_CHECKS, patched toabort on contention, and loaded with
LD_LIBRARY_PATH. With it, the newtest aborted with the earlier version of this PR;
test_sqlite3(alsowith
-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.
flag, deallocation in any thread including from Python code run inside
SQLite,
check_same_threadon and off). The check found that an earlierversion, which serialized the calls after close with a lock, could
deadlock when an aggregate's
finalize()dropped another busy cursor; ascript doing that hung with that version and passes now.
Note: this PR was developed with the assistance of an LLM