Skip to content

Commit 94e1b91

Browse files
committed
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.
1 parent 4153139 commit 94e1b91

7 files changed

Lines changed: 334 additions & 110 deletions

File tree

‎Lib/test/test_sqlite3/test_dbapi.py‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1789,6 +1789,25 @@ def contender(c1, locked, errors):
17891789
self.assertLess(time.monotonic() - t0,
17901790
support.SHORT_TIMEOUT / 2)
17911791

1792+
@unittest.skipIf(support.Py_GIL_DISABLED and sqlite.threadsafety != 3,
1793+
"the reset is deferred if SQLite is not in serialized mode")
1794+
def test_dealloc_unfinished_cursor_releases_lock(self):
1795+
# gh-162919: dropping an unfinished cursor in the thread that uses
1796+
# the connection resets its statement right away, which releases the
1797+
# read lock, also if the connection can be used by other threads.
1798+
self.addCleanup(unlink, TESTFN)
1799+
with (contextlib.closing(sqlite.connect(TESTFN, timeout=0.1,
1800+
check_same_thread=False)) as c1,
1801+
contextlib.closing(sqlite.connect(TESTFN, timeout=0.1)) as c2):
1802+
c1.execute("create table t(x)")
1803+
c1.executemany("insert into t values(?)", [(i,) for i in range(5)])
1804+
c1.commit()
1805+
cur = c1.execute("select x from t")
1806+
cur.fetchone()
1807+
del cur
1808+
c2.execute("insert into t values(5)")
1809+
c2.commit()
1810+
17921811

17931812
class ConstructorTests(unittest.TestCase):
17941813
def test_date(self):
Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
:mod:`sqlite3`: Fix a stall, lasting until the busy timeout expired, that
22
could happen on the :term:`free-threaded build` when a connection was handed
33
over to another thread while the first thread held the database lock through
4-
a different connection. Deallocating a cached statement no longer waits for
5-
a thread that is using its connection.
4+
a different connection. Fix also a crash on Apple platforms, where SQLite
5+
runs in multi-thread mode. Deallocating a statement or an unfinished cursor
6+
in a thread that may not use the connection at that moment no longer calls
7+
into SQLite: the work is done the next time the connection executes a
8+
statement, or when it is closed.

‎Modules/_sqlite/connection.c‎

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -303,6 +303,8 @@ pysqlite_connection_init_impl(pysqlite_Connection *self, PyObject *database,
303303
goto error;
304304
}
305305
self->pending_stmts = pending_stmts;
306+
_Py_atomic_store_ulong_relaxed(&self->last_user,
307+
PyThread_get_thread_ident());
306308
#endif
307309

308310
// Init connection state members.
@@ -475,14 +477,14 @@ connection_close(pysqlite_Connection *self)
475477
#ifdef Py_GIL_DISABLED
476478
pysqlite_pending_stmts *pending_stmts = self->pending_stmts;
477479
self->pending_stmts = NULL;
478-
pysqlite_pending_stmts_close(pending_stmts);
479-
#endif
480-
480+
pysqlite_pending_stmts_close(pending_stmts, db);
481+
#else
481482
Py_BEGIN_ALLOW_THREADS
482483
/* The v2 close call always returns SQLITE_OK if given a valid database
483484
* pointer (which we do), so we can safely ignore the return value */
484485
(void)sqlite3_close_v2(db);
485486
Py_END_ALLOW_THREADS
487+
#endif
486488

487489
free_callback_contexts(self);
488490
return rc;
@@ -772,6 +774,10 @@ pysqlite_connection_commit_impl(pysqlite_Connection *self)
772774
return NULL;
773775
}
774776

777+
#ifdef Py_GIL_DISABLED
778+
pysqlite_pending_stmts_process(self->pending_stmts);
779+
#endif
780+
775781
if (self->autocommit == AUTOCOMMIT_LEGACY) {
776782
if (!sqlite3_get_autocommit(self->db)) {
777783
if (connection_exec_stmt(self, "COMMIT") < 0) {
@@ -806,6 +812,10 @@ pysqlite_connection_rollback_impl(pysqlite_Connection *self)
806812
return NULL;
807813
}
808814

815+
#ifdef Py_GIL_DISABLED
816+
pysqlite_pending_stmts_process(self->pending_stmts);
817+
#endif
818+
809819
if (self->autocommit == AUTOCOMMIT_LEGACY) {
810820
if (!sqlite3_get_autocommit(self->db)) {
811821
if (connection_exec_stmt(self, "ROLLBACK") < 0) {
@@ -1795,6 +1805,12 @@ pysqlite_connection_load_extension_impl(pysqlite_Connection *self,
17951805

17961806
int pysqlite_check_thread(pysqlite_Connection* self)
17971807
{
1808+
#ifdef Py_GIL_DISABLED
1809+
unsigned long ident = PyThread_get_thread_ident();
1810+
if (_Py_atomic_load_ulong_relaxed(&self->last_user) != ident) {
1811+
_Py_atomic_store_ulong_relaxed(&self->last_user, ident);
1812+
}
1813+
#endif
17981814
if (self->check_same_thread) {
17991815
if (PyThread_get_thread_ident() != self->thread_ident) {
18001816
PyErr_Format(self->ProgrammingError,

‎Modules/_sqlite/connection.h‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -71,9 +71,12 @@ typedef struct
7171
PyObject *statement_cache;
7272

7373
#ifdef Py_GIL_DISABLED
74-
/* Statements that could not be finalized when they were deallocated;
75-
* see statement.c. NULL if the connection is closed. */
74+
/* Statements that could not be finalized when they were deallocated.
75+
* NULL if the connection is closed. */
7676
struct pysqlite_pending_stmts *pending_stmts;
77+
78+
/* The last thread that used the connection. */
79+
unsigned long last_user;
7780
#endif
7881

7982
/* Lists of weak references to blobs used within this connection */

‎Modules/_sqlite/cursor.c‎

Lines changed: 58 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -168,15 +168,9 @@ cursor_traverse(PyObject *op, visitproc visit, void *arg)
168168
return 0;
169169
}
170170

171-
static int
172-
cursor_clear(PyObject *op)
171+
static void
172+
cursor_clear_statement(pysqlite_Cursor *self)
173173
{
174-
pysqlite_Cursor *self = _pysqlite_Cursor_CAST(op);
175-
Py_CLEAR(self->connection);
176-
pysqlite_set_ref(op, &self->description, NULL);
177-
Py_CLEAR(self->row_cast_map);
178-
pysqlite_set_ref(op, &self->lastrowid, NULL);
179-
pysqlite_set_ref(op, &self->row_factory, NULL);
180174
if (self->statement) {
181175
/* Reset the statement if the user has not closed the cursor */
182176
int rc = stmt_reset(self->statement);
@@ -186,7 +180,58 @@ cursor_clear(PyObject *op)
186180
PyErr_FormatUnraisable("Exception ignored in cursor_clear()");
187181
}
188182
}
183+
}
184+
185+
#ifdef Py_GIL_DISABLED
186+
/* Return 1 if the current thread may use the cursor's connection now. On the
187+
* free-threaded build, a cursor can be deallocated by any thread at any point
188+
* (see statement.c). The connection must be open, and either:
189+
*
190+
* - it is restricted to the current thread (check_same_thread), or
191+
*
192+
* - SQLite serializes access to the connection and the current thread is the
193+
* last one that used it. Concurrent use is allowed in that mode, so this
194+
* is not needed for safety; it only makes it unlikely that we wait for the
195+
* connection mutex while another thread holds it (see statement.c). The
196+
* check is racy: another thread can start using the connection right after
197+
* it. In multi-thread mode that would be a simultaneous use, which is not
198+
* allowed, so there the reset is always left to a thread that is using the
199+
* connection. */
200+
static int
201+
may_use_connection(pysqlite_Cursor *self)
202+
{
203+
pysqlite_Connection *con = self->connection;
204+
if (con == NULL || con->db == NULL) {
205+
return 0;
206+
}
207+
unsigned long ident = PyThread_get_thread_ident();
208+
if (con->check_same_thread) {
209+
return con->thread_ident == ident;
210+
}
211+
return (sqlite3_threadsafe() == 1 &&
212+
sqlite3_db_mutex(con->db) != NULL &&
213+
_Py_atomic_load_ulong_relaxed(&con->last_user) == ident);
214+
}
215+
#endif
189216

217+
static int
218+
cursor_clear(PyObject *op)
219+
{
220+
pysqlite_Cursor *self = _pysqlite_Cursor_CAST(op);
221+
#ifdef Py_GIL_DISABLED
222+
if (self->statement && !may_use_connection(self)) {
223+
pysqlite_Statement *stmt = self->statement;
224+
self->statement = NULL;
225+
pysqlite_statement_reset_later(stmt);
226+
}
227+
cursor_clear_statement(self);
228+
#endif
229+
Py_CLEAR(self->connection);
230+
pysqlite_set_ref(op, &self->description, NULL);
231+
Py_CLEAR(self->row_cast_map);
232+
pysqlite_set_ref(op, &self->lastrowid, NULL);
233+
pysqlite_set_ref(op, &self->row_factory, NULL);
234+
cursor_clear_statement(self);
190235
return 0;
191236
}
192237

@@ -813,7 +858,7 @@ _pysqlite_query_execute(pysqlite_Cursor* self, int multiple, PyObject* operation
813858
self->locked = 1;
814859

815860
#ifdef Py_GIL_DISABLED
816-
pysqlite_pending_stmts_finalize(self->connection->pending_stmts);
861+
pysqlite_pending_stmts_process(self->connection->pending_stmts);
817862
#endif
818863

819864
if (multiple) {
@@ -1088,6 +1133,10 @@ pysqlite_cursor_executescript_impl(pysqlite_Cursor *self,
10881133
return NULL;
10891134
}
10901135

1136+
#ifdef Py_GIL_DISABLED
1137+
pysqlite_pending_stmts_process(self->connection->pending_stmts);
1138+
#endif
1139+
10911140
size_t sql_len = strlen(sql_script);
10921141
int max_length = sqlite3_limit(self->connection->db,
10931142
SQLITE_LIMIT_SQL_LENGTH, -1);

0 commit comments

Comments
 (0)