Skip to content

Commit dd5a66a

Browse files
committed
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.
1 parent b314cc9 commit dd5a66a

7 files changed

Lines changed: 283 additions & 1 deletion

File tree

‎Lib/test/test_sqlite3/test_dbapi.py‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
import subprocess
2828
import sys
2929
import threading
30+
import time
3031
import unittest
3132
import urllib.parse
3233
import warnings
@@ -1734,6 +1735,60 @@ def run(con, err):
17341735
t.join()
17351736
self.assertEqual(len(err), 0, "\n".join(err))
17361737

1738+
@threading_helper.reap_threads
1739+
def test_dealloc_statement_of_busy_connection(self):
1740+
# gh-162919: a cached statement of connection c1 can be deallocated
1741+
# by a thread that holds the database lock through c2, while another
1742+
# thread uses c1 and waits for that lock. Finalizing the statement
1743+
# must not wait for the thread using c1.
1744+
def writer(c1, c2, start, locked):
1745+
# Fill the statement cache of c1 with statements owned by this
1746+
# thread.
1747+
for i in range(5):
1748+
c1.execute(f"select {start + i}").fetchall()
1749+
c2.execute("begin immediate")
1750+
locked.set()
1751+
deadline = time.monotonic() + 0.05
1752+
while time.monotonic() < deadline:
1753+
pass
1754+
c2.commit()
1755+
1756+
def contender(c1, locked, errors):
1757+
locked.wait()
1758+
# Let the writer leave Event.set(): the statement is deallocated
1759+
# by this thread if the writer is detached (blocked on a lock).
1760+
time.sleep(0.01)
1761+
try:
1762+
# Evicts a statement created by the writer thread, then
1763+
# waits for the database lock.
1764+
c1.execute("begin immediate")
1765+
c1.rollback()
1766+
except sqlite.Error as exc:
1767+
errors.append(exc)
1768+
1769+
self.addCleanup(unlink, TESTFN)
1770+
kwargs = dict(timeout=support.SHORT_TIMEOUT, check_same_thread=False,
1771+
cached_statements=5)
1772+
with (contextlib.closing(sqlite.connect(TESTFN, **kwargs)) as c1,
1773+
contextlib.closing(sqlite.connect(TESTFN, **kwargs)) as c2):
1774+
c1.execute("create table t(x)")
1775+
c1.commit()
1776+
for round in range(3):
1777+
locked = threading.Event()
1778+
errors = []
1779+
threads = [
1780+
threading.Thread(target=writer,
1781+
args=(c1, c2, round * 5, locked)),
1782+
threading.Thread(target=contender,
1783+
args=(c1, locked, errors)),
1784+
]
1785+
t0 = time.monotonic()
1786+
with threading_helper.start_threads(threads):
1787+
pass
1788+
self.assertEqual(errors, [])
1789+
self.assertLess(time.monotonic() - t0,
1790+
support.SHORT_TIMEOUT / 2)
1791+
17371792

17381793
class ConstructorTests(unittest.TestCase):
17391794
def test_date(self):
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
:mod:`sqlite3`: Fix a stall, lasting until the busy timeout expired, that
2+
could happen on the :term:`free-threaded build` when a connection was handed
3+
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.

‎Modules/_sqlite/connection.c‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -295,6 +295,16 @@ pysqlite_connection_init_impl(pysqlite_Connection *self, PyObject *database,
295295
goto error;
296296
}
297297

298+
#ifdef Py_GIL_DISABLED
299+
pysqlite_pending_stmts *pending_stmts = pysqlite_pending_stmts_new();
300+
if (pending_stmts == NULL) {
301+
Py_DECREF(statement_cache);
302+
Py_DECREF(blobs);
303+
goto error;
304+
}
305+
self->pending_stmts = pending_stmts;
306+
#endif
307+
298308
// Init connection state members.
299309
self->db = db;
300310
self->state = state;
@@ -462,6 +472,12 @@ connection_close(pysqlite_Connection *self)
462472
sqlite3 *db = self->db;
463473
self->db = NULL;
464474

475+
#ifdef Py_GIL_DISABLED
476+
pysqlite_pending_stmts *pending_stmts = self->pending_stmts;
477+
self->pending_stmts = NULL;
478+
pysqlite_pending_stmts_close(pending_stmts);
479+
#endif
480+
465481
Py_BEGIN_ALLOW_THREADS
466482
/* The v2 close call always returns SQLITE_OK if given a valid database
467483
* pointer (which we do), so we can safely ignore the return value */

‎Modules/_sqlite/connection.h‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,12 @@ typedef struct
7070

7171
PyObject *statement_cache;
7272

73+
#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. */
76+
struct pysqlite_pending_stmts *pending_stmts;
77+
#endif
78+
7379
/* Lists of weak references to blobs used within this connection */
7480
PyObject *blobs;
7581

‎Modules/_sqlite/cursor.c‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -812,6 +812,10 @@ _pysqlite_query_execute(pysqlite_Cursor* self, int multiple, PyObject* operation
812812

813813
self->locked = 1;
814814

815+
#ifdef Py_GIL_DISABLED
816+
pysqlite_pending_stmts_finalize(self->connection->pending_stmts);
817+
#endif
818+
815819
if (multiple) {
816820
if (PyIter_Check(second_argument)) {
817821
/* iterator */

‎Modules/_sqlite/statement.c‎

Lines changed: 175 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,11 @@ pysqlite_statement_create(pysqlite_Connection *connection, PyObject *sql)
4848
return NULL;
4949
}
5050

51+
#ifdef Py_GIL_DISABLED
52+
// Bound the number of statements waiting to be finalized.
53+
pysqlite_pending_stmts_finalize(connection->pending_stmts);
54+
#endif
55+
5156
sqlite3 *db = connection->db;
5257
int max_length = sqlite3_limit(db, SQLITE_LIMIT_SQL_LENGTH, -1);
5358
if (size > max_length) {
@@ -98,6 +103,12 @@ pysqlite_statement_create(pysqlite_Connection *connection, PyObject *sql)
98103

99104
self->st = stmt;
100105
self->is_dml = is_dml;
106+
#ifdef Py_GIL_DISABLED
107+
assert(connection->pending_stmts != NULL);
108+
self->pending = connection->pending_stmts;
109+
_Py_atomic_add_ssize(&self->pending->refcnt, 1);
110+
self->next_pending = NULL;
111+
#endif
101112

102113
PyObject_GC_Track(self);
103114
return self;
@@ -112,6 +123,8 @@ pysqlite_statement_create(pysqlite_Connection *connection, PyObject *sql)
112123
return NULL;
113124
}
114125

126+
#ifndef Py_GIL_DISABLED
127+
115128
static void
116129
stmt_dealloc(PyObject *op)
117130
{
@@ -134,6 +147,168 @@ stmt_dealloc(PyObject *op)
134147
Py_DECREF(tp);
135148
}
136149

150+
#else // Py_GIL_DISABLED
151+
152+
/*
153+
* Finalizing a statement needs the mutex of its database connection. If
154+
* another thread is using the connection, that mutex can be held for a long
155+
* time: for example, while sqlite3_step() waits in the busy handler for a
156+
* file lock. If the thread that deallocates the statement is the one holding
157+
* that file lock (through another connection), blocking on the mutex stalls
158+
* both threads until the busy timeout expires. On the free-threaded build
159+
* this happens in normal use: when a thread that does not own the statement
160+
* drops the last reference (e.g. evicts it from the statement cache), the
161+
* decref is queued and the owning thread deallocates the statement later, at
162+
* an arbitrary point. So stmt_dealloc() must not wait for the mutex.
163+
*
164+
* Instead, the dead statement is put on a list shared with the connection and
165+
* is finalized only if the mutex can be taken without blocking. Statements
166+
* left on the list are finalized the next time the connection prepares or
167+
* executes a statement, or when it is closed. Delaying sqlite3_finalize() is
168+
* harmless: the statement has normally been reset already and holds no locks.
169+
*/
170+
171+
pysqlite_pending_stmts *
172+
pysqlite_pending_stmts_new(void)
173+
{
174+
pysqlite_pending_stmts *pending = PyMem_Calloc(1, sizeof(*pending));
175+
if (pending == NULL) {
176+
PyErr_NoMemory();
177+
return NULL;
178+
}
179+
pending->refcnt = 1;
180+
return pending;
181+
}
182+
183+
static void
184+
pending_stmts_decref(pysqlite_pending_stmts *pending)
185+
{
186+
if (_Py_atomic_add_ssize(&pending->refcnt, -1) == 1) {
187+
assert(pending->head == NULL);
188+
PyMem_Free(pending);
189+
}
190+
}
191+
192+
/* Finalize a dead statement and free it. If 'mutex' is not NULL, it is the
193+
* mutex of the statement's database, held by the caller; it is released. */
194+
static void
195+
stmt_destroy(pysqlite_Statement *self, sqlite3_mutex *mutex)
196+
{
197+
PyTypeObject *tp = Py_TYPE(self);
198+
int rc;
199+
// Release the database mutex before re-attaching the thread state: a
200+
// thread waiting for that mutex may be attached.
201+
Py_BEGIN_ALLOW_THREADS
202+
rc = sqlite3_finalize(self->st);
203+
sqlite3_mutex_leave(mutex);
204+
Py_END_ALLOW_THREADS
205+
self->st = NULL;
206+
if (rc != SQLITE_OK) {
207+
pysqlite_state *state = PyType_GetModuleState(tp);
208+
PyErr_SetString(state->InternalError, "cannot finalize statement");
209+
PyErr_FormatUnraisable("Exception ignored in stmt_dealloc()");
210+
}
211+
pending_stmts_decref(self->pending);
212+
tp->tp_free(self);
213+
Py_DECREF(tp);
214+
}
215+
216+
static void
217+
stmt_destroy_list(pysqlite_Statement *head)
218+
{
219+
while (head != NULL) {
220+
pysqlite_Statement *next = head->next_pending;
221+
stmt_destroy(head, NULL);
222+
head = next;
223+
}
224+
}
225+
226+
/* Finalize the statements waiting on the list. The caller must be using the
227+
* connection, so that waiting for the database mutex is fine. */
228+
void
229+
pysqlite_pending_stmts_finalize(pysqlite_pending_stmts *pending)
230+
{
231+
if (_Py_atomic_load_ptr_relaxed(&pending->head) == NULL) {
232+
return;
233+
}
234+
PyMutex_Lock(&pending->mutex);
235+
pysqlite_Statement *head = pending->head;
236+
_Py_atomic_store_ptr_relaxed(&pending->head, NULL);
237+
PyMutex_Unlock(&pending->mutex);
238+
stmt_destroy_list(head);
239+
}
240+
241+
/* Called when the connection is closed: finalize the waiting statements and
242+
* drop the connection's reference. After that nothing can hold the database
243+
* mutex for long, so statements deallocated later are finalized directly. */
244+
void
245+
pysqlite_pending_stmts_close(pysqlite_pending_stmts *pending)
246+
{
247+
PyMutex_Lock(&pending->mutex);
248+
pending->closed = 1;
249+
pysqlite_Statement *head = pending->head;
250+
_Py_atomic_store_ptr_relaxed(&pending->head, NULL);
251+
PyMutex_Unlock(&pending->mutex);
252+
stmt_destroy_list(head);
253+
pending_stmts_decref(pending);
254+
}
255+
256+
static void
257+
stmt_dealloc(PyObject *op)
258+
{
259+
pysqlite_Statement *self = _pysqlite_Statement_CAST(op);
260+
PyObject_GC_UnTrack(op);
261+
262+
pysqlite_pending_stmts *pending = self->pending;
263+
if (self->st == NULL) {
264+
// Empty statement (no SQL): nothing to finalize.
265+
stmt_destroy(self, NULL);
266+
return;
267+
}
268+
PyMutex_Lock(&pending->mutex);
269+
if (pending->closed) {
270+
PyMutex_Unlock(&pending->mutex);
271+
stmt_destroy(self, NULL);
272+
return;
273+
}
274+
// Keep the list alive for the loop below. This must be done before the
275+
// statement is put on the list: once it is there, another thread can
276+
// destroy it and close the connection, dropping the last references.
277+
_Py_atomic_add_ssize(&pending->refcnt, 1);
278+
self->next_pending = pending->head;
279+
_Py_atomic_store_ptr_relaxed(&pending->head, self);
280+
PyMutex_Unlock(&pending->mutex);
281+
282+
// Finalize the statements on the list (normally just this one) for as
283+
// long as the database mutex is free. Taking the list lock again after
284+
// each one also picks up statements added by threads that found the
285+
// database mutex held by us.
286+
for (;;) {
287+
PyMutex_Lock(&pending->mutex);
288+
pysqlite_Statement *stmt = pending->head;
289+
sqlite3_mutex *mutex = NULL;
290+
if (stmt != NULL) {
291+
// The database stays valid while the statement is on the list.
292+
mutex = sqlite3_db_mutex(sqlite3_db_handle(stmt->st));
293+
if (sqlite3_mutex_try(mutex) == SQLITE_OK) {
294+
_Py_atomic_store_ptr_relaxed(&pending->head,
295+
stmt->next_pending);
296+
}
297+
else {
298+
stmt = NULL;
299+
}
300+
}
301+
PyMutex_Unlock(&pending->mutex);
302+
if (stmt == NULL) {
303+
break;
304+
}
305+
stmt_destroy(stmt, mutex);
306+
}
307+
pending_stmts_decref(pending);
308+
}
309+
310+
#endif // Py_GIL_DISABLED
311+
137312
/*
138313
* Strip leading whitespace and comments from incoming SQL (null terminated C
139314
* string) and return a pointer to the first non-whitespace, non-comment

‎Modules/_sqlite/statement.h‎

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,15 +28,36 @@
2828
#include "connection.h"
2929
#include "sqlite3.h"
3030

31-
typedef struct
31+
typedef struct pysqlite_Statement
3232
{
3333
PyObject_HEAD
3434
sqlite3_stmt* st;
3535
int is_dml;
36+
#ifdef Py_GIL_DISABLED
37+
struct pysqlite_pending_stmts *pending; // owned ref, shared with the connection
38+
struct pysqlite_Statement *next_pending;
39+
#endif
3640
} pysqlite_Statement;
3741

3842
pysqlite_Statement *pysqlite_statement_create(pysqlite_Connection *connection, PyObject *sql);
3943

44+
#ifdef Py_GIL_DISABLED
45+
/* Deallocated statements that are waiting to be finalized. Shared by a
46+
* connection and all of its statements, since a statement can outlive the
47+
* connection object. */
48+
typedef struct pysqlite_pending_stmts
49+
{
50+
Py_ssize_t refcnt;
51+
PyMutex mutex;
52+
int closed; // protected by mutex
53+
pysqlite_Statement *head; // written with mutex held
54+
} pysqlite_pending_stmts;
55+
56+
pysqlite_pending_stmts *pysqlite_pending_stmts_new(void);
57+
void pysqlite_pending_stmts_close(pysqlite_pending_stmts *pending);
58+
void pysqlite_pending_stmts_finalize(pysqlite_pending_stmts *pending);
59+
#endif
60+
4061
int pysqlite_statement_setup_types(PyObject *module);
4162

4263
#endif

0 commit comments

Comments
 (0)