From a362962fe7290286a2afb6b34b9593eed1b153b4 Mon Sep 17 00:00:00 2001 From: Inada Naoki Date: Wed, 18 Nov 2026 17:29:51 +0900 Subject: [PATCH 1/3] Free buffered results without acquiring the connection lock --- src/MySQLdb/_mysql.c | 7 ++++--- tests/test_connection.py | 20 +++++++++++++++++++- 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/src/MySQLdb/_mysql.c b/src/MySQLdb/_mysql.c index 8d832bfd..f1af01c9 100644 --- a/src/MySQLdb/_mysql.c +++ b/src/MySQLdb/_mysql.c @@ -2587,13 +2587,14 @@ static void _mysql_ResultObject_dealloc( _mysql_ResultObject *self) { - PyObject *conn = self->conn; PyObject_GC_UnTrack((PyObject *)self); - if (conn != NULL) { + /* Only an unbuffered result may need to read remaining rows from the connection. */ + bool lock_connection = self->use && self->result != NULL && self->conn != NULL; + if (lock_connection) { BEGIN_RESULT_CONNECTION_LOCK(self); } mysql_free_result(self->result); - if (conn != NULL) { + if (lock_connection) { END_RESULT_CONNECTION_LOCK(self); } _mysql_ResultObject_clear(self); diff --git a/tests/test_connection.py b/tests/test_connection.py index 790eecc8..e7d4fade 100644 --- a/tests/test_connection.py +++ b/tests/test_connection.py @@ -1,13 +1,14 @@ import enum import threading import time +from concurrent.futures import ThreadPoolExecutor import pytest from configdb import connection_factory, connection_kwargs from MySQLdb._exceptions import ProgrammingError from MySQLdb.connections import Connection -from MySQLdb.constants import CLIENT +from MySQLdb.constants import CLIENT, FIELD_TYPE @pytest.fixture @@ -168,6 +169,23 @@ def run_slow_query(): assert thread_error is None +def test_stored_result_dealloc_while_connection_locked(conn): + conn.query("SELECT 1") + stored = [conn.store_result()] + + with ThreadPoolExecutor(max_workers=1) as executor: + + def convert(value): + # fetch_row holds the connection lock while calling this converter. + executor.submit(stored.clear).result(timeout=5) + return int(value) + + conn.converter[FIELD_TYPE.NEWDECIMAL] = convert + conn.query("SELECT CAST(2 AS DECIMAL(1,0))") + assert conn.use_result().fetch_row() == ((2,),) + assert not stored + + def test_result_concurrent_use_raises(conn): """While fetch_row holds the connection lock streaming a slow result, any other access from a second thread must raise ProgrammingError immediately.""" From 22696798c4325bcf0c4d0f6b2405f9b515b6b4da Mon Sep 17 00:00:00 2001 From: Inada Naoki Date: Wed, 18 Nov 2026 17:41:04 +0900 Subject: [PATCH 2/3] Reject reinitialization before changing result ownership --- src/MySQLdb/_mysql.c | 18 ++++++++++++++++-- tests/test_connection.py | 13 +++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/src/MySQLdb/_mysql.c b/src/MySQLdb/_mysql.c index f1af01c9..813a872c 100644 --- a/src/MySQLdb/_mysql.c +++ b/src/MySQLdb/_mysql.c @@ -327,8 +327,22 @@ _mysql_ResultObject_Initialize( &_mysql_ConnectionObject_Type, &conn, &use, &conv)) return -1; - self->conn = (PyObject *) conn; - Py_INCREF(conn); + /* A result keeps its original connection and buffering mode until deallocation. */ + bool already_initialized; +#ifdef Py_GIL_DISABLED + Py_BEGIN_CRITICAL_SECTION(self); +#endif + already_initialized = self->conn != NULL; + if (!already_initialized) { + self->conn = Py_NewRef(conn); + } +#ifdef Py_GIL_DISABLED + Py_END_CRITICAL_SECTION(); +#endif + if (already_initialized) { + PyErr_SetString(_mysql_ProgrammingError, "Result is already initialized"); + return -1; + } self->use = use; if (BEGIN_CONNECTION_LOCK(conn) < 0) { return -1; diff --git a/tests/test_connection.py b/tests/test_connection.py index e7d4fade..ecf363b0 100644 --- a/tests/test_connection.py +++ b/tests/test_connection.py @@ -169,6 +169,19 @@ def run_slow_query(): assert thread_error is None +@pytest.mark.parametrize("use", [False, True]) +def test_result_rejects_reinitialization(conn, use): + conn.query("SELECT 1 UNION ALL SELECT 2") + result = conn.use_result() if use else conn.store_result() + with pytest.raises(ProgrammingError, match="already initialized"): + result.__init__(conn, not use) + + assert result.fetch_row() == ((1,),) + del result # Leave the second row for cleanup. + conn.query("SELECT 3") + assert conn.store_result().fetch_row() == ((3,),) + + def test_stored_result_dealloc_while_connection_locked(conn): conn.query("SELECT 1") stored = [conn.store_result()] From a9f21ae642432bd37c53527cd8826efc099a91c1 Mon Sep 17 00:00:00 2001 From: Inada Naoki Date: Wed, 18 Nov 2026 17:59:20 +0900 Subject: [PATCH 3/3] Make buffered result cleanup deterministic on free-threaded Python --- tests/test_connection.py | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/tests/test_connection.py b/tests/test_connection.py index ecf363b0..ea6a1e46 100644 --- a/tests/test_connection.py +++ b/tests/test_connection.py @@ -171,7 +171,7 @@ def run_slow_query(): @pytest.mark.parametrize("use", [False, True]) def test_result_rejects_reinitialization(conn, use): - conn.query("SELECT 1 UNION ALL SELECT 2") + conn.query("SELECT 1 UNION ALL SELECT 2 ORDER BY 1") result = conn.use_result() if use else conn.store_result() with pytest.raises(ProgrammingError, match="already initialized"): result.__init__(conn, not use) @@ -183,10 +183,15 @@ def test_result_rejects_reinitialization(conn, use): def test_stored_result_dealloc_while_connection_locked(conn): - conn.query("SELECT 1") - stored = [conn.store_result()] + stored = [] + + def store_result(): + conn.query("SELECT 1") + stored.append(conn.store_result()) with ThreadPoolExecutor(max_workers=1) as executor: + # On free-threaded CPython, drop the last reference on its owning thread. + executor.submit(store_result).result() def convert(value): # fetch_row holds the connection lock while calling this converter.