Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 74 additions & 0 deletions Lib/test/test_sqlite3/test_dbapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import subprocess
import sys
import threading
import time
import unittest
import urllib.parse
import warnings
Expand Down Expand Up @@ -1734,6 +1735,79 @@ 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)

@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):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +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. 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.
32 changes: 32 additions & 0 deletions Modules/_sqlite/connection.c
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,18 @@ 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;
_Py_atomic_store_ulong_relaxed(&self->last_user,
PyThread_get_thread_ident());
#endif

// Init connection state members.
self->db = db;
self->state = state;
Expand Down Expand Up @@ -462,11 +474,17 @@ 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, 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;
Expand Down Expand Up @@ -756,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) {
Expand Down Expand Up @@ -790,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) {
Expand Down Expand Up @@ -1779,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,
Expand Down
9 changes: 9 additions & 0 deletions Modules/_sqlite/connection.h
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,15 @@ typedef struct

PyObject *statement_cache;

#ifdef Py_GIL_DISABLED
/* 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 */
PyObject *blobs;

Expand Down
69 changes: 61 additions & 8 deletions Modules/_sqlite/cursor.c
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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;
}

Expand Down Expand Up @@ -812,6 +857,10 @@ _pysqlite_query_execute(pysqlite_Cursor* self, int multiple, PyObject* operation

self->locked = 1;

#ifdef Py_GIL_DISABLED
pysqlite_pending_stmts_process(self->connection->pending_stmts);
#endif

if (multiple) {
if (PyIter_Check(second_argument)) {
/* iterator */
Expand Down Expand Up @@ -1084,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);
Expand Down
Loading
Loading