From dd5a66a17f06c8ed6b2572feef7a208ce2eb7415 Mon Sep 17 00:00:00 2001 From: Neil Schemenauer Date: Tue, 1 Dec 2026 22:07:06 -0700 Subject: [PATCH 1/3] gh-162919: Don't block on DB mutex when deallocating a sqlite3 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. --- Lib/test/test_sqlite3/test_dbapi.py | 55 ++++++ ...-12-01-21-30-00.gh-issue-162919.sQs7Fn.rst | 5 + Modules/_sqlite/connection.c | 16 ++ Modules/_sqlite/connection.h | 6 + Modules/_sqlite/cursor.c | 4 + Modules/_sqlite/statement.c | 175 ++++++++++++++++++ Modules/_sqlite/statement.h | 23 ++- 7 files changed, 283 insertions(+), 1 deletion(-) create mode 100644 Misc/NEWS.d/next/Library/2026-12-01-21-30-00.gh-issue-162919.sQs7Fn.rst diff --git a/Lib/test/test_sqlite3/test_dbapi.py b/Lib/test/test_sqlite3/test_dbapi.py index bbb7c1f8b61593..703c38416369b9 100644 --- a/Lib/test/test_sqlite3/test_dbapi.py +++ b/Lib/test/test_sqlite3/test_dbapi.py @@ -27,6 +27,7 @@ import subprocess import sys import threading +import time import unittest import urllib.parse import warnings @@ -1734,6 +1735,60 @@ def run(con, err): t.join() self.assertEqual(len(err), 0, "\n".join(err)) + @threading_helper.reap_threads + def test_dealloc_statement_of_busy_connection(self): + # gh-162919: a cached statement of connection c1 can be deallocated + # by a thread that holds the database lock through c2, while another + # thread uses c1 and waits for that lock. Finalizing the statement + # must not wait for the thread using c1. + def writer(c1, c2, start, locked): + # Fill the statement cache of c1 with statements owned by this + # thread. + for i in range(5): + c1.execute(f"select {start + i}").fetchall() + c2.execute("begin immediate") + locked.set() + deadline = time.monotonic() + 0.05 + while time.monotonic() < deadline: + pass + c2.commit() + + def contender(c1, locked, errors): + locked.wait() + # Let the writer leave Event.set(): the statement is deallocated + # by this thread if the writer is detached (blocked on a lock). + time.sleep(0.01) + try: + # Evicts a statement created by the writer thread, then + # waits for the database lock. + c1.execute("begin immediate") + c1.rollback() + except sqlite.Error as exc: + errors.append(exc) + + self.addCleanup(unlink, TESTFN) + kwargs = dict(timeout=support.SHORT_TIMEOUT, check_same_thread=False, + cached_statements=5) + with (contextlib.closing(sqlite.connect(TESTFN, **kwargs)) as c1, + contextlib.closing(sqlite.connect(TESTFN, **kwargs)) as c2): + c1.execute("create table t(x)") + c1.commit() + for round in range(3): + locked = threading.Event() + errors = [] + threads = [ + threading.Thread(target=writer, + args=(c1, c2, round * 5, locked)), + threading.Thread(target=contender, + args=(c1, locked, errors)), + ] + t0 = time.monotonic() + with threading_helper.start_threads(threads): + pass + self.assertEqual(errors, []) + self.assertLess(time.monotonic() - t0, + support.SHORT_TIMEOUT / 2) + class ConstructorTests(unittest.TestCase): def test_date(self): diff --git a/Misc/NEWS.d/next/Library/2026-12-01-21-30-00.gh-issue-162919.sQs7Fn.rst b/Misc/NEWS.d/next/Library/2026-12-01-21-30-00.gh-issue-162919.sQs7Fn.rst new file mode 100644 index 00000000000000..7e5ebac6f047d1 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-12-01-21-30-00.gh-issue-162919.sQs7Fn.rst @@ -0,0 +1,5 @@ +:mod:`sqlite3`: Fix a stall, lasting until the busy timeout expired, that +could happen on the :term:`free-threaded build` when a connection was handed +over to another thread while the first thread held the database lock through +a different connection. Deallocating a cached statement no longer waits for +a thread that is using its connection. diff --git a/Modules/_sqlite/connection.c b/Modules/_sqlite/connection.c index f8bd3a8df35b66..5cd0fc801e97df 100644 --- a/Modules/_sqlite/connection.c +++ b/Modules/_sqlite/connection.c @@ -295,6 +295,16 @@ pysqlite_connection_init_impl(pysqlite_Connection *self, PyObject *database, goto error; } +#ifdef Py_GIL_DISABLED + pysqlite_pending_stmts *pending_stmts = pysqlite_pending_stmts_new(); + if (pending_stmts == NULL) { + Py_DECREF(statement_cache); + Py_DECREF(blobs); + goto error; + } + self->pending_stmts = pending_stmts; +#endif + // Init connection state members. self->db = db; self->state = state; @@ -462,6 +472,12 @@ connection_close(pysqlite_Connection *self) sqlite3 *db = self->db; self->db = NULL; +#ifdef Py_GIL_DISABLED + pysqlite_pending_stmts *pending_stmts = self->pending_stmts; + self->pending_stmts = NULL; + pysqlite_pending_stmts_close(pending_stmts); +#endif + Py_BEGIN_ALLOW_THREADS /* The v2 close call always returns SQLITE_OK if given a valid database * pointer (which we do), so we can safely ignore the return value */ diff --git a/Modules/_sqlite/connection.h b/Modules/_sqlite/connection.h index a2241bd540669c..478c220c49abd0 100644 --- a/Modules/_sqlite/connection.h +++ b/Modules/_sqlite/connection.h @@ -70,6 +70,12 @@ typedef struct PyObject *statement_cache; +#ifdef Py_GIL_DISABLED + /* Statements that could not be finalized when they were deallocated; + * see statement.c. NULL if the connection is closed. */ + struct pysqlite_pending_stmts *pending_stmts; +#endif + /* Lists of weak references to blobs used within this connection */ PyObject *blobs; diff --git a/Modules/_sqlite/cursor.c b/Modules/_sqlite/cursor.c index ad8c434c1b2fb8..b7e7fb2a4a1ce3 100644 --- a/Modules/_sqlite/cursor.c +++ b/Modules/_sqlite/cursor.c @@ -812,6 +812,10 @@ _pysqlite_query_execute(pysqlite_Cursor* self, int multiple, PyObject* operation self->locked = 1; +#ifdef Py_GIL_DISABLED + pysqlite_pending_stmts_finalize(self->connection->pending_stmts); +#endif + if (multiple) { if (PyIter_Check(second_argument)) { /* iterator */ diff --git a/Modules/_sqlite/statement.c b/Modules/_sqlite/statement.c index f31c699482f601..c575f4cf3bc14b 100644 --- a/Modules/_sqlite/statement.c +++ b/Modules/_sqlite/statement.c @@ -48,6 +48,11 @@ pysqlite_statement_create(pysqlite_Connection *connection, PyObject *sql) return NULL; } +#ifdef Py_GIL_DISABLED + // Bound the number of statements waiting to be finalized. + pysqlite_pending_stmts_finalize(connection->pending_stmts); +#endif + sqlite3 *db = connection->db; int max_length = sqlite3_limit(db, SQLITE_LIMIT_SQL_LENGTH, -1); if (size > max_length) { @@ -98,6 +103,12 @@ pysqlite_statement_create(pysqlite_Connection *connection, PyObject *sql) self->st = stmt; self->is_dml = is_dml; +#ifdef Py_GIL_DISABLED + assert(connection->pending_stmts != NULL); + self->pending = connection->pending_stmts; + _Py_atomic_add_ssize(&self->pending->refcnt, 1); + self->next_pending = NULL; +#endif PyObject_GC_Track(self); return self; @@ -112,6 +123,8 @@ pysqlite_statement_create(pysqlite_Connection *connection, PyObject *sql) return NULL; } +#ifndef Py_GIL_DISABLED + static void stmt_dealloc(PyObject *op) { @@ -134,6 +147,168 @@ stmt_dealloc(PyObject *op) Py_DECREF(tp); } +#else // Py_GIL_DISABLED + +/* + * Finalizing a statement needs the mutex of its database connection. If + * another thread is using the connection, that mutex can be held for a long + * time: for example, while sqlite3_step() waits in the busy handler for a + * file lock. If the thread that deallocates the statement is the one holding + * that file lock (through another connection), blocking on the mutex stalls + * both threads until the busy timeout expires. On the free-threaded build + * this happens in normal use: when a thread that does not own the statement + * drops the last reference (e.g. evicts it from the statement cache), the + * decref is queued and the owning thread deallocates the statement later, at + * an arbitrary point. So stmt_dealloc() must not wait for the mutex. + * + * Instead, the dead statement is put on a list shared with the connection and + * is finalized only if the 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. Delaying sqlite3_finalize() is + * harmless: the statement has normally been reset already and holds no locks. + */ + +pysqlite_pending_stmts * +pysqlite_pending_stmts_new(void) +{ + pysqlite_pending_stmts *pending = PyMem_Calloc(1, sizeof(*pending)); + if (pending == NULL) { + PyErr_NoMemory(); + return NULL; + } + pending->refcnt = 1; + return pending; +} + +static void +pending_stmts_decref(pysqlite_pending_stmts *pending) +{ + if (_Py_atomic_add_ssize(&pending->refcnt, -1) == 1) { + assert(pending->head == NULL); + PyMem_Free(pending); + } +} + +/* Finalize a dead statement and free it. If 'mutex' is not NULL, it is the + * mutex of the statement's database, held by the caller; it is released. */ +static void +stmt_destroy(pysqlite_Statement *self, sqlite3_mutex *mutex) +{ + PyTypeObject *tp = Py_TYPE(self); + int rc; + // Release the database mutex before re-attaching the thread state: a + // thread waiting for that mutex may be attached. + Py_BEGIN_ALLOW_THREADS + rc = sqlite3_finalize(self->st); + sqlite3_mutex_leave(mutex); + Py_END_ALLOW_THREADS + self->st = NULL; + if (rc != SQLITE_OK) { + pysqlite_state *state = PyType_GetModuleState(tp); + PyErr_SetString(state->InternalError, "cannot finalize statement"); + PyErr_FormatUnraisable("Exception ignored in stmt_dealloc()"); + } + pending_stmts_decref(self->pending); + tp->tp_free(self); + Py_DECREF(tp); +} + +static void +stmt_destroy_list(pysqlite_Statement *head) +{ + while (head != NULL) { + pysqlite_Statement *next = head->next_pending; + stmt_destroy(head, NULL); + head = next; + } +} + +/* Finalize the statements waiting on the list. The caller must be using the + * connection, so that waiting for the database mutex is fine. */ +void +pysqlite_pending_stmts_finalize(pysqlite_pending_stmts *pending) +{ + if (_Py_atomic_load_ptr_relaxed(&pending->head) == NULL) { + return; + } + PyMutex_Lock(&pending->mutex); + pysqlite_Statement *head = pending->head; + _Py_atomic_store_ptr_relaxed(&pending->head, NULL); + PyMutex_Unlock(&pending->mutex); + stmt_destroy_list(head); +} + +/* Called when the connection is closed: finalize the waiting statements and + * drop the connection's reference. After that nothing can hold the database + * mutex for long, so statements deallocated later are finalized directly. */ +void +pysqlite_pending_stmts_close(pysqlite_pending_stmts *pending) +{ + PyMutex_Lock(&pending->mutex); + pending->closed = 1; + pysqlite_Statement *head = pending->head; + _Py_atomic_store_ptr_relaxed(&pending->head, NULL); + PyMutex_Unlock(&pending->mutex); + stmt_destroy_list(head); + pending_stmts_decref(pending); +} + +static void +stmt_dealloc(PyObject *op) +{ + pysqlite_Statement *self = _pysqlite_Statement_CAST(op); + PyObject_GC_UnTrack(op); + + pysqlite_pending_stmts *pending = self->pending; + if (self->st == NULL) { + // Empty statement (no SQL): nothing to finalize. + stmt_destroy(self, NULL); + return; + } + PyMutex_Lock(&pending->mutex); + if (pending->closed) { + PyMutex_Unlock(&pending->mutex); + stmt_destroy(self, NULL); + return; + } + // Keep the list alive for the loop below. This must be done before the + // statement is put on the list: once it is there, another thread can + // destroy it and close the connection, dropping the last references. + _Py_atomic_add_ssize(&pending->refcnt, 1); + self->next_pending = pending->head; + _Py_atomic_store_ptr_relaxed(&pending->head, self); + PyMutex_Unlock(&pending->mutex); + + // Finalize the statements on the list (normally just this one) for as + // long as the database mutex is free. Taking the list lock again after + // each one also picks up statements added by threads that found the + // database mutex held by us. + for (;;) { + PyMutex_Lock(&pending->mutex); + pysqlite_Statement *stmt = pending->head; + sqlite3_mutex *mutex = NULL; + if (stmt != NULL) { + // The database stays valid while the statement is on the list. + mutex = sqlite3_db_mutex(sqlite3_db_handle(stmt->st)); + if (sqlite3_mutex_try(mutex) == SQLITE_OK) { + _Py_atomic_store_ptr_relaxed(&pending->head, + stmt->next_pending); + } + else { + stmt = NULL; + } + } + PyMutex_Unlock(&pending->mutex); + if (stmt == NULL) { + break; + } + stmt_destroy(stmt, mutex); + } + pending_stmts_decref(pending); +} + +#endif // Py_GIL_DISABLED + /* * Strip leading whitespace and comments from incoming SQL (null terminated C * string) and return a pointer to the first non-whitespace, non-comment diff --git a/Modules/_sqlite/statement.h b/Modules/_sqlite/statement.h index b18f170ebb0708..dca0f343e87611 100644 --- a/Modules/_sqlite/statement.h +++ b/Modules/_sqlite/statement.h @@ -28,15 +28,36 @@ #include "connection.h" #include "sqlite3.h" -typedef struct +typedef struct pysqlite_Statement { PyObject_HEAD sqlite3_stmt* st; int is_dml; +#ifdef Py_GIL_DISABLED + struct pysqlite_pending_stmts *pending; // owned ref, shared with the connection + struct pysqlite_Statement *next_pending; +#endif } pysqlite_Statement; pysqlite_Statement *pysqlite_statement_create(pysqlite_Connection *connection, PyObject *sql); +#ifdef Py_GIL_DISABLED +/* Deallocated statements that are waiting to be finalized. Shared by a + * connection and all of its statements, since a statement can outlive the + * connection object. */ +typedef struct pysqlite_pending_stmts +{ + Py_ssize_t refcnt; + PyMutex mutex; + int closed; // protected by mutex + pysqlite_Statement *head; // written with mutex held +} pysqlite_pending_stmts; + +pysqlite_pending_stmts *pysqlite_pending_stmts_new(void); +void pysqlite_pending_stmts_close(pysqlite_pending_stmts *pending); +void pysqlite_pending_stmts_finalize(pysqlite_pending_stmts *pending); +#endif + int pysqlite_statement_setup_types(PyObject *module); #endif From 4153139d67cf2695401278880c6167641dc3ea25 Mon Sep 17 00:00:00 2001 From: Neil Schemenauer Date: Wed, 2 Dec 2026 00:13:21 -0700 Subject: [PATCH 2/3] Don't finalize in stmt_dealloc() if SQLite has no connection mutex 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. --- Modules/_sqlite/statement.c | 57 ++++++++++++++++++++++++------------- 1 file changed, 37 insertions(+), 20 deletions(-) diff --git a/Modules/_sqlite/statement.c b/Modules/_sqlite/statement.c index c575f4cf3bc14b..1976aaa5597e68 100644 --- a/Modules/_sqlite/statement.c +++ b/Modules/_sqlite/statement.c @@ -166,6 +166,15 @@ stmt_dealloc(PyObject *op) * left on the list are finalized the next time the connection prepares or * executes a statement, or when it is closed. Delaying sqlite3_finalize() is * harmless: the statement has normally been reset already and holds no locks. + * + * SQLite can also run without a connection mutex ("multi-thread" mode, used + * by the system SQLite on Apple platforms). A connection may then be used by + * several threads, but only by one at a time, and it is up to the application + * to ensure that. The application cannot know when a statement is + * deallocated, so in this mode stmt_dealloc() must not call into SQLite at + * all while the connection is open: it could run at the same time as the + * thread that is using the connection. The statement is always left on the + * list, to be finalized by a thread that is using the connection. */ pysqlite_pending_stmts * @@ -253,6 +262,30 @@ pysqlite_pending_stmts_close(pysqlite_pending_stmts *pending) pending_stmts_decref(pending); } +/* Remove the first statement from the list if the mutex of its database can + * be taken without blocking. Return the statement, with the mutex held and + * stored in *mutex. Return NULL if the list is empty or the mutex is not + * available. */ +static pysqlite_Statement * +pending_stmts_try_pop(pysqlite_pending_stmts *pending, sqlite3_mutex **mutex) +{ + pysqlite_Statement *stmt = NULL; + PyMutex_Lock(&pending->mutex); + pysqlite_Statement *head = pending->head; + if (head != NULL) { + // The database stays valid while the statement is on the list. + // The mutex is NULL in multi-thread mode: leave the statement on + // the list (sqlite3_mutex_try(NULL) would report success). + *mutex = sqlite3_db_mutex(sqlite3_db_handle(head->st)); + if (*mutex != NULL && sqlite3_mutex_try(*mutex) == SQLITE_OK) { + _Py_atomic_store_ptr_relaxed(&pending->head, head->next_pending); + stmt = head; + } + } + PyMutex_Unlock(&pending->mutex); + return stmt; +} + static void stmt_dealloc(PyObject *op) { @@ -280,28 +313,12 @@ stmt_dealloc(PyObject *op) PyMutex_Unlock(&pending->mutex); // Finalize the statements on the list (normally just this one) for as - // long as the database mutex is free. Taking the list lock again after + // long as the database mutex is free. Checking the list again after // each one also picks up statements added by threads that found the // database mutex held by us. - for (;;) { - PyMutex_Lock(&pending->mutex); - pysqlite_Statement *stmt = pending->head; - sqlite3_mutex *mutex = NULL; - if (stmt != NULL) { - // The database stays valid while the statement is on the list. - mutex = sqlite3_db_mutex(sqlite3_db_handle(stmt->st)); - if (sqlite3_mutex_try(mutex) == SQLITE_OK) { - _Py_atomic_store_ptr_relaxed(&pending->head, - stmt->next_pending); - } - else { - stmt = NULL; - } - } - PyMutex_Unlock(&pending->mutex); - if (stmt == NULL) { - break; - } + pysqlite_Statement *stmt; + sqlite3_mutex *mutex; + while ((stmt = pending_stmts_try_pop(pending, &mutex)) != NULL) { stmt_destroy(stmt, mutex); } pending_stmts_decref(pending); From 94e1b9158d4ed02461e184764b261735d4cb229e Mon Sep 17 00:00:00 2001 From: Neil Schemenauer Date: Wed, 2 Dec 2026 17:45:17 -0700 Subject: [PATCH 3/3] gh-162919: Never call into SQLite from deallocators while the connection 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. --- Lib/test/test_sqlite3/test_dbapi.py | 19 ++ ...-12-01-21-30-00.gh-issue-162919.sQs7Fn.rst | 7 +- Modules/_sqlite/connection.c | 22 +- Modules/_sqlite/connection.h | 7 +- Modules/_sqlite/cursor.c | 67 +++- Modules/_sqlite/statement.c | 304 +++++++++++++----- Modules/_sqlite/statement.h | 18 +- 7 files changed, 334 insertions(+), 110 deletions(-) diff --git a/Lib/test/test_sqlite3/test_dbapi.py b/Lib/test/test_sqlite3/test_dbapi.py index 703c38416369b9..03dd0a7c233826 100644 --- a/Lib/test/test_sqlite3/test_dbapi.py +++ b/Lib/test/test_sqlite3/test_dbapi.py @@ -1789,6 +1789,25 @@ def contender(c1, locked, errors): self.assertLess(time.monotonic() - t0, support.SHORT_TIMEOUT / 2) + @unittest.skipIf(support.Py_GIL_DISABLED and sqlite.threadsafety != 3, + "the reset is deferred if SQLite is not in serialized mode") + def test_dealloc_unfinished_cursor_releases_lock(self): + # gh-162919: dropping an unfinished cursor in the thread that uses + # the connection resets its statement right away, which releases the + # read lock, also if the connection can be used by other threads. + self.addCleanup(unlink, TESTFN) + with (contextlib.closing(sqlite.connect(TESTFN, timeout=0.1, + check_same_thread=False)) as c1, + contextlib.closing(sqlite.connect(TESTFN, timeout=0.1)) as c2): + c1.execute("create table t(x)") + c1.executemany("insert into t values(?)", [(i,) for i in range(5)]) + c1.commit() + cur = c1.execute("select x from t") + cur.fetchone() + del cur + c2.execute("insert into t values(5)") + c2.commit() + class ConstructorTests(unittest.TestCase): def test_date(self): diff --git a/Misc/NEWS.d/next/Library/2026-12-01-21-30-00.gh-issue-162919.sQs7Fn.rst b/Misc/NEWS.d/next/Library/2026-12-01-21-30-00.gh-issue-162919.sQs7Fn.rst index 7e5ebac6f047d1..c65e71ce175793 100644 --- a/Misc/NEWS.d/next/Library/2026-12-01-21-30-00.gh-issue-162919.sQs7Fn.rst +++ b/Misc/NEWS.d/next/Library/2026-12-01-21-30-00.gh-issue-162919.sQs7Fn.rst @@ -1,5 +1,8 @@ :mod:`sqlite3`: Fix a stall, lasting until the busy timeout expired, that could happen on the :term:`free-threaded build` when a connection was handed over to another thread while the first thread held the database lock through -a different connection. Deallocating a cached statement no longer waits for -a thread that is using its connection. +a different connection. Fix also a crash on Apple platforms, where SQLite +runs in multi-thread mode. Deallocating a statement or an unfinished cursor +in a thread that may not use the connection at that moment no longer calls +into SQLite: the work is done the next time the connection executes a +statement, or when it is closed. diff --git a/Modules/_sqlite/connection.c b/Modules/_sqlite/connection.c index 5cd0fc801e97df..19369e0780af30 100644 --- a/Modules/_sqlite/connection.c +++ b/Modules/_sqlite/connection.c @@ -303,6 +303,8 @@ pysqlite_connection_init_impl(pysqlite_Connection *self, PyObject *database, goto error; } self->pending_stmts = pending_stmts; + _Py_atomic_store_ulong_relaxed(&self->last_user, + PyThread_get_thread_ident()); #endif // Init connection state members. @@ -475,14 +477,14 @@ connection_close(pysqlite_Connection *self) #ifdef Py_GIL_DISABLED pysqlite_pending_stmts *pending_stmts = self->pending_stmts; self->pending_stmts = NULL; - pysqlite_pending_stmts_close(pending_stmts); -#endif - + pysqlite_pending_stmts_close(pending_stmts, db); +#else Py_BEGIN_ALLOW_THREADS /* The v2 close call always returns SQLITE_OK if given a valid database * pointer (which we do), so we can safely ignore the return value */ (void)sqlite3_close_v2(db); Py_END_ALLOW_THREADS +#endif free_callback_contexts(self); return rc; @@ -772,6 +774,10 @@ pysqlite_connection_commit_impl(pysqlite_Connection *self) return NULL; } +#ifdef Py_GIL_DISABLED + pysqlite_pending_stmts_process(self->pending_stmts); +#endif + if (self->autocommit == AUTOCOMMIT_LEGACY) { if (!sqlite3_get_autocommit(self->db)) { if (connection_exec_stmt(self, "COMMIT") < 0) { @@ -806,6 +812,10 @@ pysqlite_connection_rollback_impl(pysqlite_Connection *self) return NULL; } +#ifdef Py_GIL_DISABLED + pysqlite_pending_stmts_process(self->pending_stmts); +#endif + if (self->autocommit == AUTOCOMMIT_LEGACY) { if (!sqlite3_get_autocommit(self->db)) { if (connection_exec_stmt(self, "ROLLBACK") < 0) { @@ -1795,6 +1805,12 @@ pysqlite_connection_load_extension_impl(pysqlite_Connection *self, int pysqlite_check_thread(pysqlite_Connection* self) { +#ifdef Py_GIL_DISABLED + unsigned long ident = PyThread_get_thread_ident(); + if (_Py_atomic_load_ulong_relaxed(&self->last_user) != ident) { + _Py_atomic_store_ulong_relaxed(&self->last_user, ident); + } +#endif if (self->check_same_thread) { if (PyThread_get_thread_ident() != self->thread_ident) { PyErr_Format(self->ProgrammingError, diff --git a/Modules/_sqlite/connection.h b/Modules/_sqlite/connection.h index 478c220c49abd0..e5025b1ac0d9c5 100644 --- a/Modules/_sqlite/connection.h +++ b/Modules/_sqlite/connection.h @@ -71,9 +71,12 @@ typedef struct PyObject *statement_cache; #ifdef Py_GIL_DISABLED - /* Statements that could not be finalized when they were deallocated; - * see statement.c. NULL if the connection is closed. */ + /* Statements that could not be finalized when they were deallocated. + * NULL if the connection is closed. */ struct pysqlite_pending_stmts *pending_stmts; + + /* The last thread that used the connection. */ + unsigned long last_user; #endif /* Lists of weak references to blobs used within this connection */ diff --git a/Modules/_sqlite/cursor.c b/Modules/_sqlite/cursor.c index b7e7fb2a4a1ce3..e02d904541b9df 100644 --- a/Modules/_sqlite/cursor.c +++ b/Modules/_sqlite/cursor.c @@ -168,15 +168,9 @@ cursor_traverse(PyObject *op, visitproc visit, void *arg) return 0; } -static int -cursor_clear(PyObject *op) +static void +cursor_clear_statement(pysqlite_Cursor *self) { - pysqlite_Cursor *self = _pysqlite_Cursor_CAST(op); - Py_CLEAR(self->connection); - pysqlite_set_ref(op, &self->description, NULL); - Py_CLEAR(self->row_cast_map); - pysqlite_set_ref(op, &self->lastrowid, NULL); - pysqlite_set_ref(op, &self->row_factory, NULL); if (self->statement) { /* Reset the statement if the user has not closed the cursor */ int rc = stmt_reset(self->statement); @@ -186,7 +180,58 @@ cursor_clear(PyObject *op) PyErr_FormatUnraisable("Exception ignored in cursor_clear()"); } } +} + +#ifdef Py_GIL_DISABLED +/* Return 1 if the current thread may use the cursor's connection now. On the + * free-threaded build, a cursor can be deallocated by any thread at any point + * (see statement.c). The connection must be open, and either: + * + * - it is restricted to the current thread (check_same_thread), or + * + * - SQLite serializes access to the connection and the current thread is the + * last one that used it. Concurrent use is allowed in that mode, so this + * is not needed for safety; it only makes it unlikely that we wait for the + * connection mutex while another thread holds it (see statement.c). The + * check is racy: another thread can start using the connection right after + * it. In multi-thread mode that would be a simultaneous use, which is not + * allowed, so there the reset is always left to a thread that is using the + * connection. */ +static int +may_use_connection(pysqlite_Cursor *self) +{ + pysqlite_Connection *con = self->connection; + if (con == NULL || con->db == NULL) { + return 0; + } + unsigned long ident = PyThread_get_thread_ident(); + if (con->check_same_thread) { + return con->thread_ident == ident; + } + return (sqlite3_threadsafe() == 1 && + sqlite3_db_mutex(con->db) != NULL && + _Py_atomic_load_ulong_relaxed(&con->last_user) == ident); +} +#endif +static int +cursor_clear(PyObject *op) +{ + pysqlite_Cursor *self = _pysqlite_Cursor_CAST(op); +#ifdef Py_GIL_DISABLED + if (self->statement && !may_use_connection(self)) { + pysqlite_Statement *stmt = self->statement; + self->statement = NULL; + pysqlite_statement_reset_later(stmt); + } + cursor_clear_statement(self); +#endif + Py_CLEAR(self->connection); + pysqlite_set_ref(op, &self->description, NULL); + Py_CLEAR(self->row_cast_map); + pysqlite_set_ref(op, &self->lastrowid, NULL); + pysqlite_set_ref(op, &self->row_factory, NULL); + cursor_clear_statement(self); return 0; } @@ -813,7 +858,7 @@ _pysqlite_query_execute(pysqlite_Cursor* self, int multiple, PyObject* operation self->locked = 1; #ifdef Py_GIL_DISABLED - pysqlite_pending_stmts_finalize(self->connection->pending_stmts); + pysqlite_pending_stmts_process(self->connection->pending_stmts); #endif if (multiple) { @@ -1088,6 +1133,10 @@ pysqlite_cursor_executescript_impl(pysqlite_Cursor *self, return NULL; } +#ifdef Py_GIL_DISABLED + pysqlite_pending_stmts_process(self->connection->pending_stmts); +#endif + size_t sql_len = strlen(sql_script); int max_length = sqlite3_limit(self->connection->db, SQLITE_LIMIT_SQL_LENGTH, -1); diff --git a/Modules/_sqlite/statement.c b/Modules/_sqlite/statement.c index 1976aaa5597e68..51f7961bbde29d 100644 --- a/Modules/_sqlite/statement.c +++ b/Modules/_sqlite/statement.c @@ -49,8 +49,7 @@ pysqlite_statement_create(pysqlite_Connection *connection, PyObject *sql) } #ifdef Py_GIL_DISABLED - // Bound the number of statements waiting to be finalized. - pysqlite_pending_stmts_finalize(connection->pending_stmts); + pysqlite_pending_stmts_process(connection->pending_stmts); #endif sqlite3 *db = connection->db; @@ -108,6 +107,7 @@ pysqlite_statement_create(pysqlite_Connection *connection, PyObject *sql) self->pending = connection->pending_stmts; _Py_atomic_add_ssize(&self->pending->refcnt, 1); self->next_pending = NULL; + self->on_reset_list = 0; #endif PyObject_GC_Track(self); @@ -150,31 +150,45 @@ stmt_dealloc(PyObject *op) #else // Py_GIL_DISABLED /* - * Finalizing a statement needs the mutex of its database connection. If - * another thread is using the connection, that mutex can be held for a long - * time: for example, while sqlite3_step() waits in the busy handler for a - * file lock. If the thread that deallocates the statement is the one holding - * that file lock (through another connection), blocking on the mutex stalls - * both threads until the busy timeout expires. On the free-threaded build - * this happens in normal use: when a thread that does not own the statement - * drops the last reference (e.g. evicts it from the statement cache), the - * decref is queued and the owning thread deallocates the statement later, at - * an arbitrary point. So stmt_dealloc() must not wait for the mutex. + * On the free-threaded build, a statement can be deallocated by any thread + * at any point: a decref from a thread that does not own the object is + * queued and the owner deallocates it later; decrefs can also be delayed + * until a quiescent state, or done by the GC. The deallocating thread may + * not be allowed to use the connection at that moment: * - * Instead, the dead statement is put on a list shared with the connection and - * is finalized only if the 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. Delaying sqlite3_finalize() is - * harmless: the statement has normally been reset already and holds no locks. + * - In serialized mode, sqlite3_finalize() waits for the connection mutex. + * Another thread can hold it for a long time, e.g. while sqlite3_step() + * waits in the busy handler for a file lock. If the deallocating thread + * holds that file lock (through another connection), both threads stall + * until the busy timeout expires. * - * SQLite can also run without a connection mutex ("multi-thread" mode, used - * by the system SQLite on Apple platforms). A connection may then be used by - * several threads, but only by one at a time, and it is up to the application - * to ensure that. The application cannot know when a statement is - * deallocated, so in this mode stmt_dealloc() must not call into SQLite at - * all while the connection is open: it could run at the same time as the - * thread that is using the connection. The statement is always left on the - * list, to be finalized by a thread that is using the connection. + * - In multi-thread mode (the system SQLite on Apple platforms), a connection + * must 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 statement + * is deallocated. + * + * So while the connection is open, stmt_dealloc() does not call into SQLite. + * It puts the dead statement on a list shared with the connection, and the + * statements on it are finalized the next time the connection prepares or + * executes a statement, or when it is closed: by a thread that is using the + * connection. Delaying sqlite3_finalize() is harmless: the statement has + * been reset already and holds no locks. + * + * The same applies to the reset done when a cursor that still uses a + * statement is deallocated (see cursor_clear()), except that resetting a + * statement can release a lock on the database, so it is done directly when + * that is known to be safe. Otherwise the live statement is put on a second + * list and reset by a thread that is using the connection. + * + * Once the connection is closed, nobody uses it anymore, and statements are + * reset and finalized by whichever thread deallocates them. In multi-thread + * mode these calls must not overlap, so one thread at a time "processes" the + * lists (pending->processing). A deallocator that finds another thread + * processing, or its own thread further up the stack (Python code can run + * inside sqlite3_reset(), e.g. an aggregate's finalize()), puts the statement + * on a list and returns. The processing thread empties the lists before it + * clears the flag. So deallocators never wait for each other, and never + * wait for themselves. */ pysqlite_pending_stmts * @@ -194,22 +208,20 @@ pending_stmts_decref(pysqlite_pending_stmts *pending) { if (_Py_atomic_add_ssize(&pending->refcnt, -1) == 1) { assert(pending->head == NULL); + assert(pending->reset_head == NULL); + assert(!pending->processing); PyMem_Free(pending); } } -/* Finalize a dead statement and free it. If 'mutex' is not NULL, it is the - * mutex of the statement's database, held by the caller; it is released. */ +/* Finalize a dead statement and free it. */ static void -stmt_destroy(pysqlite_Statement *self, sqlite3_mutex *mutex) +stmt_destroy(pysqlite_Statement *self) { PyTypeObject *tp = Py_TYPE(self); int rc; - // Release the database mutex before re-attaching the thread state: a - // thread waiting for that mutex may be attached. Py_BEGIN_ALLOW_THREADS rc = sqlite3_finalize(self->st); - sqlite3_mutex_leave(mutex); Py_END_ALLOW_THREADS self->st = NULL; if (rc != SQLITE_OK) { @@ -227,63 +239,195 @@ stmt_destroy_list(pysqlite_Statement *head) { while (head != NULL) { pysqlite_Statement *next = head->next_pending; - stmt_destroy(head, NULL); + stmt_destroy(head); + head = next; + } +} + +/* Reset live statements and drop the references of the list. A statement + * is taken off the list before it is reset: if a cursor that uses it is + * deallocated after that, the statement is put on the list again. */ +static void +stmt_reset_list(pysqlite_Statement *head) +{ + while (head != NULL) { + pysqlite_pending_stmts *pending = head->pending; + PyMutex_Lock(&pending->mutex); + pysqlite_Statement *next = head->next_pending; + head->next_pending = NULL; + head->on_reset_list = 0; + PyMutex_Unlock(&pending->mutex); + // The result is that of the last sqlite3_step(), which nobody is + // interested in anymore. + Py_BEGIN_ALLOW_THREADS + (void)sqlite3_reset(head->st); + Py_END_ALLOW_THREADS + Py_DECREF(head); head = next; } } -/* Finalize the statements waiting on the list. The caller must be using the - * connection, so that waiting for the database mutex is fine. */ +/* Detach both lists. The caller holds pending->mutex. */ +static void +pending_stmts_take_locked(pysqlite_pending_stmts *pending, + pysqlite_Statement **reset_head, + pysqlite_Statement **head) +{ + *reset_head = pending->reset_head; + _Py_atomic_store_ptr_relaxed(&pending->reset_head, NULL); + *head = pending->head; + _Py_atomic_store_ptr_relaxed(&pending->head, NULL); +} + +/* Reset and finalize the statements waiting on the lists. The caller must be + * using the connection. */ void -pysqlite_pending_stmts_finalize(pysqlite_pending_stmts *pending) +pysqlite_pending_stmts_process(pysqlite_pending_stmts *pending) { - if (_Py_atomic_load_ptr_relaxed(&pending->head) == NULL) { + if (_Py_atomic_load_ptr_relaxed(&pending->reset_head) == NULL && + _Py_atomic_load_ptr_relaxed(&pending->head) == NULL) + { return; } + pysqlite_Statement *reset_head, *head; PyMutex_Lock(&pending->mutex); - pysqlite_Statement *head = pending->head; - _Py_atomic_store_ptr_relaxed(&pending->head, NULL); + pending_stmts_take_locked(pending, &reset_head, &head); PyMutex_Unlock(&pending->mutex); + stmt_reset_list(reset_head); + stmt_destroy_list(head); + // Statements released by the resets above are now on the list. + PyMutex_Lock(&pending->mutex); + pending_stmts_take_locked(pending, &reset_head, &head); + PyMutex_Unlock(&pending->mutex); + stmt_reset_list(reset_head); stmt_destroy_list(head); } -/* Called when the connection is closed: finalize the waiting statements and - * drop the connection's reference. After that nothing can hold the database - * mutex for long, so statements deallocated later are finalized directly. */ -void -pysqlite_pending_stmts_close(pysqlite_pending_stmts *pending) +typedef enum { + // 'stmt' was put on a list; it now owns the caller's reference. + PENDING_PUSHED, + // The caller is the processing thread and holds a reference to 'pending', + // which it drops after pending_stmts_drain(). + PENDING_PROCESS, + // 'stmt' is on the reset list already; the caller only drops its + // reference. + PENDING_ALREADY_QUEUED, +} pending_push_result; + +/* Push 'stmt' on the reset list ('reset' is true) or on the dead list, unless + * the connection is closed and nobody is processing the lists. In that case, + * the caller becomes the processing thread (PENDING_PROCESS). + * + * 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), so 'stmt' can be on the reset list already + * (PENDING_ALREADY_QUEUED). It will be reset. */ +static pending_push_result +pending_stmts_push_or_process(pysqlite_pending_stmts *pending, + pysqlite_Statement *stmt, int reset) { PyMutex_Lock(&pending->mutex); - pending->closed = 1; - pysqlite_Statement *head = pending->head; - _Py_atomic_store_ptr_relaxed(&pending->head, NULL); + if (reset && stmt->on_reset_list) { + PyMutex_Unlock(&pending->mutex); + return PENDING_ALREADY_QUEUED; + } + if (pending->closed && !pending->processing) { + pending->processing = 1; + _Py_atomic_add_ssize(&pending->refcnt, 1); + PyMutex_Unlock(&pending->mutex); + return PENDING_PROCESS; + } + assert(stmt->next_pending == NULL); + if (reset) { + stmt->on_reset_list = 1; + stmt->next_pending = pending->reset_head; + _Py_atomic_store_ptr_relaxed(&pending->reset_head, stmt); + } + else { + stmt->next_pending = pending->head; + _Py_atomic_store_ptr_relaxed(&pending->head, stmt); + } PyMutex_Unlock(&pending->mutex); - stmt_destroy_list(head); - pending_stmts_decref(pending); + return PENDING_PUSHED; } -/* Remove the first statement from the list if the mutex of its database can - * be taken without blocking. Return the statement, with the mutex held and - * stored in *mutex. Return NULL if the list is empty or the mutex is not - * available. */ -static pysqlite_Statement * -pending_stmts_try_pop(pysqlite_pending_stmts *pending, sqlite3_mutex **mutex) +/* Process the lists until they are empty. The caller is the processing + * thread and holds a reference to 'pending'. If 'release' is true, clear the + * processing flag: this is done with the mutex held and the lists empty, so + * a statement pushed by another thread cannot be left behind. */ +static void +pending_stmts_drain(pysqlite_pending_stmts *pending, int release) { - pysqlite_Statement *stmt = NULL; - PyMutex_Lock(&pending->mutex); - pysqlite_Statement *head = pending->head; - if (head != NULL) { - // The database stays valid while the statement is on the list. - // The mutex is NULL in multi-thread mode: leave the statement on - // the list (sqlite3_mutex_try(NULL) would report success). - *mutex = sqlite3_db_mutex(sqlite3_db_handle(head->st)); - if (*mutex != NULL && sqlite3_mutex_try(*mutex) == SQLITE_OK) { - _Py_atomic_store_ptr_relaxed(&pending->head, head->next_pending); - stmt = head; + for (;;) { + pysqlite_Statement *reset_head, *head; + PyMutex_Lock(&pending->mutex); + assert(pending->processing); + pending_stmts_take_locked(pending, &reset_head, &head); + if (reset_head == NULL && head == NULL) { + if (release) { + pending->processing = 0; + } + PyMutex_Unlock(&pending->mutex); + return; } + PyMutex_Unlock(&pending->mutex); + stmt_reset_list(reset_head); + stmt_destroy_list(head); + } +} + +/* Reset a statement that is still in use by a cursor being deallocated, and + * drop the cursor's reference to it ('stmt' is stolen). Used when the + * caller may not be allowed to use the connection: if the connection is + * open, the statement is reset later by a thread that is using it. */ +void +pysqlite_statement_reset_later(pysqlite_Statement *stmt) +{ + pysqlite_pending_stmts *pending = stmt->pending; + if (stmt->st == NULL) { + Py_DECREF(stmt); + return; } + switch (pending_stmts_push_or_process(pending, stmt, 1)) { + case PENDING_PUSHED: + return; + case PENDING_ALREADY_QUEUED: + // Not the last reference: the list holds one. + Py_DECREF(stmt); + return; + case PENDING_PROCESS: + break; + } + stmt_reset_list(stmt); + pending_stmts_drain(pending, 1); + pending_stmts_decref(pending); +} + +/* Close the connection's database: process the waiting statements, call + * sqlite3_close_v2() and drop the connection's reference. + * + * The database stays open (as a "zombie") until its last statement is + * finalized. From now on, statements are reset and finalized by the thread + * processing the lists (see above). */ +void +pysqlite_pending_stmts_close(pysqlite_pending_stmts *pending, sqlite3 *db) +{ + PyMutex_Lock(&pending->mutex); + assert(!pending->closed); + assert(!pending->processing); + pending->closed = 1; + pending->processing = 1; PyMutex_Unlock(&pending->mutex); - return stmt; + + // The connection's reference to 'pending' is the processing reference. + pending_stmts_drain(pending, 0); + Py_BEGIN_ALLOW_THREADS + /* The v2 close call always returns SQLITE_OK if given a valid database + * pointer (which we do), so we can safely ignore the return value */ + (void)sqlite3_close_v2(db); + Py_END_ALLOW_THREADS + pending_stmts_drain(pending, 1); + pending_stmts_decref(pending); } static void @@ -295,32 +439,16 @@ stmt_dealloc(PyObject *op) pysqlite_pending_stmts *pending = self->pending; if (self->st == NULL) { // Empty statement (no SQL): nothing to finalize. - stmt_destroy(self, NULL); + stmt_destroy(self); return; } - PyMutex_Lock(&pending->mutex); - if (pending->closed) { - PyMutex_Unlock(&pending->mutex); - stmt_destroy(self, NULL); + pending_push_result res = pending_stmts_push_or_process(pending, self, 0); + assert(res != PENDING_ALREADY_QUEUED); // only for the reset list + if (res == PENDING_PUSHED) { return; } - // Keep the list alive for the loop below. This must be done before the - // statement is put on the list: once it is there, another thread can - // destroy it and close the connection, dropping the last references. - _Py_atomic_add_ssize(&pending->refcnt, 1); - self->next_pending = pending->head; - _Py_atomic_store_ptr_relaxed(&pending->head, self); - PyMutex_Unlock(&pending->mutex); - - // Finalize the statements on the list (normally just this one) for as - // long as the database mutex is free. Checking the list again after - // each one also picks up statements added by threads that found the - // database mutex held by us. - pysqlite_Statement *stmt; - sqlite3_mutex *mutex; - while ((stmt = pending_stmts_try_pop(pending, &mutex)) != NULL) { - stmt_destroy(stmt, mutex); - } + stmt_destroy(self); + pending_stmts_drain(pending, 1); pending_stmts_decref(pending); } diff --git a/Modules/_sqlite/statement.h b/Modules/_sqlite/statement.h index dca0f343e87611..ce0e54bfbd29f2 100644 --- a/Modules/_sqlite/statement.h +++ b/Modules/_sqlite/statement.h @@ -36,26 +36,32 @@ typedef struct pysqlite_Statement #ifdef Py_GIL_DISABLED struct pysqlite_pending_stmts *pending; // owned ref, shared with the connection struct pysqlite_Statement *next_pending; + int on_reset_list; // protected by pending->mutex #endif } pysqlite_Statement; pysqlite_Statement *pysqlite_statement_create(pysqlite_Connection *connection, PyObject *sql); #ifdef Py_GIL_DISABLED -/* Deallocated statements that are waiting to be finalized. Shared by a - * connection and all of its statements, since a statement can outlive the - * connection object. */ +/* Statements waiting to be reset or finalized by a thread that is using the + * connection; see statement.c. Shared by a connection and all of its + * statements, since a statement can outlive the connection object. */ typedef struct pysqlite_pending_stmts { Py_ssize_t refcnt; PyMutex mutex; int closed; // protected by mutex - pysqlite_Statement *head; // written with mutex held + int processing; // protected by mutex; see statement.c + // Lists linked through next_pending, written with mutex held. + pysqlite_Statement *head; // dead statements, to finalize + pysqlite_Statement *reset_head; // live statements (owned refs), to reset } pysqlite_pending_stmts; pysqlite_pending_stmts *pysqlite_pending_stmts_new(void); -void pysqlite_pending_stmts_close(pysqlite_pending_stmts *pending); -void pysqlite_pending_stmts_finalize(pysqlite_pending_stmts *pending); +void pysqlite_pending_stmts_close(pysqlite_pending_stmts *pending, + sqlite3 *db); +void pysqlite_pending_stmts_process(pysqlite_pending_stmts *pending); +void pysqlite_statement_reset_later(pysqlite_Statement *stmt); #endif int pysqlite_statement_setup_types(PyObject *module);