Skip to content

gh-145040: Fix crash in sqlite3 when connection is closed during aggregate callback#145041

Open
raminfp wants to merge 2 commits intopython:mainfrom
raminfp:fix-gh-145040-sqlite3-close-in-callback
Open

gh-145040: Fix crash in sqlite3 when connection is closed during aggregate callback#145041
raminfp wants to merge 2 commits intopython:mainfrom
raminfp:fix-gh-145040-sqlite3-close-in-callback

Conversation

@raminfp
Copy link
Contributor

@raminfp raminfp commented Feb 20, 2026

Summary

Fix a segmentation fault (NULL pointer dereference) in the _sqlite module that occurs when Connection.close() is called inside an aggregate step() callback.

Fix

  1. Primary check – immediately after stmt_step(), check if self->connection->db == NULL. If so, raise ProgrammingError("Cannot operate on a closed database.") and jump to the error path.
  2. Defensive check – guard the sqlite3_last_insert_rowid() call with self->connection->db != NULL as an extra safety net.

Test

Added test_aggr_close_conn_in_step in Lib/test/test_sqlite3/test_userfunctions.py that reproduces the exact crash scenario and verifies that ProgrammingError is raised instead of a segfault.

ASAN output (before fix)

AddressSanitizer: SEGV on unknown address 0x000000000038
  #0 in sqlite3_last_insert_rowid
  #1 in _pysqlite_query_execute Modules/_sqlite/cursor.c:974

After fix

sqlite3.ProgrammingError: Cannot operate on a closed database.

…g aggregate callback

Fix a segmentation fault in the _sqlite module that occurs when
Connection.close() is called inside an aggregate step() callback.

After stmt_step() returns, _pysqlite_query_execute() calls
sqlite3_last_insert_rowid(self->connection->db) without checking if
self->connection->db is still valid. If the connection was closed during
the callback, self->connection->db is NULL, causing a NULL pointer
dereference.

The fix adds a NULL check for self->connection->db after stmt_step()
returns, raising ProgrammingError instead of crashing.
…qlite3-close-crash.rst

Co-authored-by: Benedikt Johannes <benedikt.johannes.hofer@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

Comments