~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(database): prevent SQLCipher WAL open/close deadlocks (#7000)
LearningCircuita6bfbc564d6a
diff --git a/changelog.d/+sqlcipher-wal-lifecycle.bugfix.md b/changelog.d/+sqlcipher-wal-lifecycle.bugfix.mdnew file mode 100644index 0000000000..5b0f1f452b--- /dev/null+++ b/changelog.d/+sqlcipher-wal-lifecycle.bugfix.md@@ -0,0 +1 @@+Prevent encrypted database connections from hanging during concurrent opens, closes and switches out of WAL journal mode when the SQLCipher driver embeds SQLite 3.51.0 or 3.51.1. On those builds, an `ATTACH DATABASE` or `DETACH DATABASE` of a file that another thread is opening or closing at the same time can still hang; the application only attaches its temporary backup file, which nothing else opens.diff --git a/src/local_deep_research/database/backup/backup_service.py b/src/local_deep_research/database/backup/backup_service.pyindex 20d92cb91d..27088c79e0 100644--- a/src/local_deep_research/database/backup/backup_service.py+++ b/src/local_deep_research/database/backup/backup_service.py@@ -406,12 +406,15 @@ class BackupService:try:# Import SQLCipher module- from ..sqlcipher_compat import get_sqlcipher_module+ from ..sqlcipher_compat import (+ connect_sqlcipher,+ get_sqlcipher_module,+ )sqlcipher3 = get_sqlcipher_module()# Open the backup with the same password- conn = sqlcipher3.connect(str(backup_path))+ conn = connect_sqlcipher(sqlcipher3, str(backup_path))cursor = conn.cursor()try:diff --git a/src/local_deep_research/database/encrypted_db.py b/src/local_deep_research/database/encrypted_db.pyindex abb3fd6d22..3704424d96 100644--- a/src/local_deep_research/database/encrypted_db.py+++ b/src/local_deep_research/database/encrypted_db.py@@ -43,7 +43,7 @@ from ..settings.env_registry import get_env_setting# initialization. Other files in PRs #4168/#4175/#4181 can import# ``redact_secrets`` at module scope because they are not on that bootstrap# path.-from .sqlcipher_compat import get_sqlcipher_module+from .sqlcipher_compat import connect_sqlcipher, get_sqlcipher_modulefrom .pool_config import (MAX_OVERFLOW,POOL_PRE_PING,@@ -465,7 +465,7 @@ class DatabaseManager:sqlcipher_module = get_sqlcipher_module()sqlcipher = sqlcipher_module.dbapi2- conn = sqlcipher.connect(tmp_path)+ conn = connect_sqlcipher(sqlcipher, tmp_path)try:cursor = conn.cursor()# Use creation_mode=True since we're creating a new test database@@ -635,7 +635,8 @@ class DatabaseManager:ValueError: If the database key cannot be verified."""sqlcipher3 = get_sqlcipher_module()- conn = sqlcipher3.connect(+ conn = connect_sqlcipher(+ sqlcipher3,str(db_path),isolation_level=isolation_level,check_same_thread=check_same_thread,diff --git a/src/local_deep_research/database/sqlcipher_compat.py b/src/local_deep_research/database/sqlcipher_compat.pyindex 7aecd274f0..01a9636ff4 100644--- a/src/local_deep_research/database/sqlcipher_compat.py+++ b/src/local_deep_research/database/sqlcipher_compat.py@@ -7,6 +7,235 @@ Provides a unified interface for importing SQLCipher on different platforms:- Other platforms: Uses sqlcipher3"""+from functools import lru_cache+import os+import threading+++_lifecycle_lock = threading.RLock()+++def _reset_lifecycle_lock():+ """A fork must not inherit a lock owned by a vanished parent thread."""+ global _lifecycle_lock+ _lifecycle_lock = threading.RLock()+++if hasattr(os, "register_at_fork"):+ os.register_at_fork(after_in_child=_reset_lifecycle_lock)+++# Driver entry points that refuse a foreign thread when a connection is+# opened with check_same_thread=True (pysqlite_check_thread in sqlcipher3).+_CONNECTION_THREAD_CHECKED = (+ "__call__",+ "commit",+ "create_aggregate",+ "create_collation",+ "create_function",+ "create_window_function",+ "enable_load_extension",+ "execute",+ "executemany",+ "executescript",+ "load_extension",+ "open_blob",+ "rollback",+ "set_authorizer",+ "set_busy_handler",+ "set_busy_timeout",+ "set_progress_handler",+ "set_trace_callback",+)+_CURSOR_THREAD_CHECKED = (+ "__next__",+ "close",+ "execute",+ "executemany",+ "executescript",+ "fetchall",+ "fetchmany",+ "fetchone",+)+++def _check_owner_thread(connection):+ owner = getattr(connection, "_ldr_owner_thread", None)+ current = threading.get_ident()+ if owner is not None and owner != current:+ raise connection.ProgrammingError(+ "SQLite objects created in a thread can only be used in that "+ f"same thread. The object was created in thread id {owner} "+ f"and this is thread id {current}."+ )+++def _owner_checked(native, connection_of):+ def method(self, *args, **kwargs):+ _check_owner_thread(connection_of(self))+ return native(self, *args, **kwargs)++ method.__name__ = native.__name__+ method.__doc__ = native.__doc__+ return method+++def _same_object(connection):+ return connection+++def _cursor_connection(cursor):+ return cursor.connection+++@lru_cache(maxsize=8)+def _guarded_connection_type(connection_type, cursor_type, check_same_thread):+ class LifecycleConnection(connection_type):+ def __init__(self, *args, **kwargs):+ self._ldr_initialized = False+ self._ldr_owner_thread = (+ threading.get_ident() if check_same_thread else None+ )+ # The driver's close() refuses a foreign thread when its own+ # check_same_thread is on. A connection finalised on another+ # thread would then fall through to the native deallocator,+ # which closes it with no guard held. Open without the native+ # check so __del__ can always close under the guard; the+ # caller's requested check is enforced by this wrapper instead.+ if len(args) > 4:+ args = (*args[:4], False, *args[5:])+ else:+ kwargs["check_same_thread"] = False+ with _lifecycle_lock:+ super().__init__(*args, **kwargs)+ self._ldr_initialized = True++ def close(self):+ _check_owner_thread(self)+ return self._ldr_close()++ def _ldr_close(self):+ with _lifecycle_lock:+ return connection_type.close(self)++ def __del__(self):+ # The native deallocator also closes an abandoned connection.+ # Close it under the same guard first, from whichever thread+ # finalises it; the native close has no thread check here.+ # A failed constructor has no complete statement/blob lists, so+ # calling the driver's close() on it is unsafe.+ if getattr(self, "_ldr_initialized", False):+ try:+ self._ldr_close()+ except Exception: # allow: silent-exception+ pass # Finalization must not raise during interpreter exit.++ if check_same_thread:++ class ThreadCheckedCursor(cursor_type):+ pass++ for name in _CURSOR_THREAD_CHECKED:+ if hasattr(cursor_type, name):+ setattr(+ ThreadCheckedCursor,+ name,+ _owner_checked(+ getattr(cursor_type, name), _cursor_connection+ ),+ )+ for name in _CONNECTION_THREAD_CHECKED:+ if hasattr(connection_type, name):+ setattr(+ LifecycleConnection,+ name,+ _owner_checked(+ getattr(connection_type, name), _same_object+ ),+ )++ def cursor(self, *args, **kwargs):+ _check_owner_thread(self)+ if not args and "factory" not in kwargs:+ kwargs["factory"] = ThreadCheckedCursor+ return connection_type.cursor(self, *args, **kwargs)++ LifecycleConnection.cursor = cursor++ # The only property setter the driver thread-checks: setting+ # isolation_level to None commits through the native commit, which+ # bypasses the wrapped commit() above. Other values and the getter+ # stay unchecked, as in the driver.+ native_isolation_level = connection_type.isolation_level++ def set_isolation_level(self, value):+ if value is None:+ _check_owner_thread(self)+ native_isolation_level.__set__(self, value)++ LifecycleConnection.isolation_level = property(+ native_isolation_level.__get__,+ set_isolation_level,+ native_isolation_level.__delete__,+ native_isolation_level.__doc__,+ )++ return LifecycleConnection+++def wal_lifecycle_guard():+ """Return the lock that serializes the affected native WAL transitions.++ Hold it around statements that close a WAL inside SQLite's pager, such+ as ``PRAGMA journal_mode`` leaving WAL mode. Taking it is harmless on+ unaffected builds, where nothing else contends for it.+ """+ return _lifecycle_lock+++def connect_sqlcipher(driver, database, **kwargs):+ """Open an application SQLCipher connection with native lifecycle safety.++ SQLite 3.51.0/3.51.1 can invert its inode and global VFS mutexes when a+ WAL connection closes while another connection opens. In sqlcipher3,+ close() also holds the GIL, so the whole interpreter can stop. Serialize+ these two native entry points for the affected POSIX builds; statements+ and transactions continue to run concurrently. SQLite fixed the mutex+ order in 3.51.2 (see the official 3.51.2 release notes). Leaving WAL+ mode closes the WAL the same way; see ``wal_lifecycle_guard``.++ A guarded connection closes under the guard even when another thread+ finalises it. To make that possible it is opened without the driver's+ own thread check. When the caller asks for ``check_same_thread`` (the+ driver default), the wrapper raises the driver's ProgrammingError for+ the connection methods the driver checks, for setting+ ``isolation_level`` to None (which commits), and for cursors from the+ default cursor factory. A blob is checked only when opened.++ Only opens and closes made through this function are serialized.+ ``ATTACH DATABASE`` opens a file and ``DETACH DATABASE`` closes it inside+ a statement, outside the guard. On the affected builds, attaching or+ detaching a file while another thread opens or closes the same file+ through this function can still deadlock; attaching a different file+ does not contend. The application attaches only its temporary backup+ file, which no other connection opens while it is attached.++ Explicit custom factories retain their own construction/cleanup behavior.+ Application connections use the default driver Connection factory.+ """+ if os.name == "posix" and getattr(driver, "sqlite_version_info", None) in (+ (3, 51, 0),+ (3, 51, 1),+ ):+ connection_type = driver.Connection+ if kwargs.get("factory", connection_type) is connection_type:+ kwargs["factory"] = _guarded_connection_type(+ connection_type,+ driver.Cursor,+ bool(kwargs.get("check_same_thread", True)),+ )+ return driver.connect(database, **kwargs)+def get_sqlcipher_module():"""diff --git a/src/local_deep_research/database/sqlcipher_utils.py b/src/local_deep_research/database/sqlcipher_utils.pyindex 98233d88d7..3a68a2fd18 100644--- a/src/local_deep_research/database/sqlcipher_utils.py+++ b/src/local_deep_research/database/sqlcipher_utils.py@@ -663,7 +663,18 @@ def apply_performance_pragmas(cursor_or_conn: Any) -> None:"OFF",):raise ValueError(f"Invalid journal_mode: {journal_mode!r}")- cursor_or_conn.execute(f"PRAGMA journal_mode = {journal_mode}")+ if journal_mode == "WAL":+ # nosemgrep: semgrep.rules.sql-execute-with-string-format, reason: journal_mode is one of the six literal modes checked above; PRAGMA mode cannot be bound+ cursor_or_conn.execute(f"PRAGMA journal_mode = {journal_mode}")+ else:+ # Leaving WAL mode closes the WAL inside SQLite's pager. On SQLite+ # 3.51.0/3.51.1 that takes the same inverted VFS mutexes as closing+ # a WAL connection, so serialize it with guarded opens and closes.+ from .sqlcipher_compat import wal_lifecycle_guard++ with wal_lifecycle_guard():+ # nosemgrep: semgrep.rules.sql-execute-with-string-format, reason: journal_mode is one of the six literal modes checked above; PRAGMA mode cannot be bound+ cursor_or_conn.execute(f"PRAGMA journal_mode = {journal_mode}")# Synchronous mode - same defense-in-depth pattern.sync_mode = get_env_setting("db_config.synchronous", "NORMAL")@@ -896,7 +907,7 @@ def create_sqlcipher_connection(ImportError: If sqlcipher3 is not availableValueError: If the connection cannot be established"""- from .sqlcipher_compat import get_sqlcipher_module+ from .sqlcipher_compat import connect_sqlcipher, get_sqlcipher_moduletry:sqlcipher3 = get_sqlcipher_module()@@ -906,7 +917,7 @@ def create_sqlcipher_connection("Ensure SQLCipher system library is installed, then run: pdm install")- conn = sqlcipher3.connect(str(db_path), **(connect_kwargs or {}))+ conn = connect_sqlcipher(sqlcipher3, str(db_path), **(connect_kwargs or {}))try:cursor = conn.cursor()diff --git a/tests/database/test_migration_chain_integrity.py b/tests/database/test_migration_chain_integrity.pyindex b821f0c67d..bf581613d0 100644--- a/tests/database/test_migration_chain_integrity.py+++ b/tests/database/test_migration_chain_integrity.py@@ -205,6 +205,9 @@ KNOWN_CONNECTION_SITES = {"database/encrypted_db.py::DatabaseManager._open_user_database_cold": ("user-db"),+ "database/sqlcipher_compat.py::connect_sqlcipher": (+ "delegate:sqlcipher-wrapper"+ ),"database/sqlcipher_utils.py::create_sqlcipher_connection": "user-db",}@@ -442,8 +445,11 @@ def _connection_calls(func):continueif name == "create_engine":found.append(("create_engine", node))- elif name == "connect" and any(- token in base for token in ("sqlcipher", "sqlite", "dbapi")+ elif name == "connect_sqlcipher":+ found.append(("connect_sqlcipher", node))+ elif name == "connect" and (+ base == "driver"+ or any(token in base for token in ("sqlcipher", "sqlite", "dbapi"))):found.append((f"{base}.connect", node))return found@@ -1324,6 +1330,31 @@ def test_the_set_of_connection_opening_functions_is_the_known_one():)+def test_sqlcipher_wrapper_has_only_classified_callers():+ """The lifecycle wrapper delegates one open to classified call sites."""+ inventory = _connection_site_inventory()+ wrapper_site = "database/sqlcipher_compat.py::connect_sqlcipher"+ _wrapper, calls = inventory[wrapper_site]+ assert [kind for kind, _call in calls] == ["driver.connect"]++ callers = {+ site+ for site, (_func, site_calls) in inventory.items()+ if any(kind == "connect_sqlcipher" for kind, _call in site_calls)+ }+ expected_callers = {+ "database/backup/backup_service.py::BackupService._verify_backup",+ "database/encrypted_db.py::DatabaseManager._check_encryption_available",+ "database/encrypted_db.py::DatabaseManager._make_sqlcipher_connection",+ "database/sqlcipher_utils.py::create_sqlcipher_connection",+ }+ assert callers == expected_callers+ assert all(+ KNOWN_CONNECTION_SITES[site] in ("user-db", "exempt:backup-verify")+ for site in callers+ )++def test_every_user_database_connection_path_reaches_the_pragma_helper():"""The routing question, answered for each user-database path."""inventory = _connection_site_inventory()diff --git a/tests/database/test_sqlcipher_lifecycle.py b/tests/database/test_sqlcipher_lifecycle.pynew file mode 100644index 0000000000..f5913d00ea--- /dev/null+++ b/tests/database/test_sqlcipher_lifecycle.py@@ -0,0 +1,525 @@+"""Keep the affected native WAL lifecycle from wedging the Python process."""++import json+import os+from pathlib import Path+import subprocess+import sys+import textwrap+import threading+from types import SimpleNamespace+from unittest.mock import Mock++import pytest++from local_deep_research.database import sqlcipher_compat+++def _run_driver_process(tmp_path, source, *args):+ pytest.importorskip(+ "sqlcipher3", reason="requires the real SQLCipher driver"+ )+ env = dict(os.environ)+ env["PYTHONPATH"] = str(+ Path(sqlcipher_compat.__file__).resolve().parents[2]+ )+ result = subprocess.run(+ [sys.executable, "-c", textwrap.dedent(source), str(tmp_path), *args],+ env=env,+ cwd=tmp_path,+ capture_output=True,+ text=True,+ timeout=30,+ check=False,+ )+ assert result.returncode == 0, result.stdout + result.stderr+ return json.loads(result.stdout.splitlines()[-1])++[email protected]("cleanup", ["explicit", "gc"])+def test_concurrent_native_wal_open_close_completes(tmp_path, cleanup):+ # A native deadlock also prevents pytest-timeout's Python thread from+ # running. Bound the entire probe from its independent parent process.+ result = _run_driver_process(+ tmp_path,+ """+ import gc+ import json+ from pathlib import Path+ import sys+ import threading+ import sqlcipher3+ from local_deep_research.database.sqlcipher_compat import connect_sqlcipher++ path = Path(sys.argv[1]) / 'native.db'+ cleanup = sys.argv[2]+ counts = [0, 0]+ errors = []++ def connect():+ connection = connect_sqlcipher(sqlcipher3, str(path), check_same_thread=False)+ assert isinstance(connection, sqlcipher3.Connection)+ connection.execute('PRAGMA key = "x\\\'' + ('ab' * 32) + '\\\'"')+ return connection++ connection = connect()+ assert connection.execute('PRAGMA cipher_version').fetchone()+ assert connection.execute('PRAGMA journal_mode=WAL').fetchone()[0] == 'wal'+ connection.execute('CREATE TABLE canary (value INTEGER)')+ connection.execute('INSERT INTO canary VALUES (1)')+ connection.commit()+ connection.close()+ barrier = threading.Barrier(2)++ def churn(index):+ try:+ barrier.wait(timeout=5)+ for iteration in range(2000):+ connection = connect()+ assert connection.execute('SELECT value FROM canary').fetchone() == (1,)+ if index == 0:+ connection.execute('PRAGMA wal_checkpoint(TRUNCATE)').fetchone()+ if cleanup == 'explicit':+ connection.close()+ del connection+ counts[index] = iteration + 1+ except BaseException as exc:+ errors.append(repr(exc))++ threads = [threading.Thread(target=churn, args=(index,)) for index in range(2)]+ for thread in threads:+ thread.start()+ for thread in threads:+ thread.join()+ gc.collect()+ assert counts == [2000, 2000] and not errors, (counts, errors)+ assert path.read_bytes()[:16] != b'SQLite format 3\\x00'+ print(json.dumps({'counts': counts, 'errors': errors}))+ """,+ cleanup,+ )+ assert result == {"counts": [2000, 2000], "errors": []}+++def test_failed_constructor_and_transaction_controls(tmp_path):+ result = _run_driver_process(+ tmp_path,+ """+ import gc+ import json+ from pathlib import Path+ import sys+ import sqlcipher3+ from local_deep_research.database.sqlcipher_compat import connect_sqlcipher++ root = Path(sys.argv[1])+ failures = 0+ for _ in range(20):+ try:+ connect_sqlcipher(sqlcipher3, str(root / 'absent' / 'bad.db'))+ except sqlcipher3.OperationalError:+ failures += 1+ else:+ raise AssertionError('An invalid path unexpectedly opened')+ gc.collect()+ connection = connect_sqlcipher(sqlcipher3, ':memory:', isolation_level='', check_same_thread=False)+ connection.execute('CREATE TABLE canary (value INTEGER)')+ connection.execute('INSERT INTO canary VALUES (1)')+ assert connection.in_transaction+ connection.rollback()+ assert connection.execute('SELECT count(*) FROM canary').fetchone() == (0,)+ with connection:+ connection.execute('INSERT INTO canary VALUES (2)')+ assert connection.execute('SELECT value FROM canary').fetchone() == (2,)+ connection.close()+ connection.close()+ print(json.dumps({'expected_failures': failures, 'transactions': 'passed'}))+ """,+ )+ assert result == {"expected_failures": 20, "transactions": "passed"}++[email protected]("version", [(3, 50, 4), (3, 51, 2), (3, 53, 1)])+def test_unaffected_driver_receives_original_options(version):+ driver = SimpleNamespace(sqlite_version_info=version, connect=Mock())+ result = sqlcipher_compat.connect_sqlcipher(+ driver, "example.db", timeout=7, isolation_level=None+ )+ driver.connect.assert_called_once_with(+ "example.db", timeout=7, isolation_level=None+ )+ assert result is driver.connect.return_value+++def test_explicit_custom_factory_keeps_native_semantics():+ factory = Mock()+ driver = SimpleNamespace(+ sqlite_version_info=(3, 51, 1), Connection=object, connect=Mock()+ )+ sqlcipher_compat.connect_sqlcipher(driver, "example.db", factory=factory)+ driver.connect.assert_called_once_with("example.db", factory=factory)++[email protected](not hasattr(os, "fork"), reason="requires POSIX fork")+def test_child_does_not_inherit_parent_lifecycle_lock(tmp_path):+ result = _run_driver_process(+ tmp_path,+ """+ import json+ import os+ import select+ import signal+ import threading+ import sqlcipher3+ from local_deep_research.database import sqlcipher_compat++ held = threading.Event()+ release = threading.Event()+ def hold_parent_lock():+ with sqlcipher_compat._lifecycle_lock:+ held.set()+ release.wait(timeout=20)+ holder = threading.Thread(target=hold_parent_lock)+ holder.start()+ assert held.wait(timeout=5)+ reader, writer = os.pipe()+ pid = os.fork()+ if pid == 0:+ try:+ os.close(reader)+ connection = sqlcipher_compat.connect_sqlcipher(sqlcipher3, ':memory:')+ assert connection.execute('SELECT 1').fetchone() == (1,)+ connection.close()+ os.write(writer, b'1')+ os._exit(0)+ except BaseException:+ os._exit(1)+ try:+ os.close(writer)+ ready, _, _ = select.select([reader], [], [], 5)+ if not ready:+ os.kill(pid, signal.SIGKILL)+ _, status = os.waitpid(pid, 0)+ assert ready and os.read(reader, 1) == b'1'+ assert os.waitstatus_to_exitcode(status) == 0+ finally:+ os.close(reader)+ release.set()+ holder.join(timeout=5)+ print(json.dumps({'child': 'passed'}))+ """,+ )+ assert result == {"child": "passed"}+++def test_foreign_thread_finalization_closes_under_lifecycle_lock(tmp_path):+ # The driver's close() refuses a foreign thread under its own+ # check_same_thread, which once let the native deallocator close a+ # connection finalised elsewhere with no guard held.+ result = _run_driver_process(+ tmp_path,+ """+ import gc+ import json+ from pathlib import Path+ import sys+ import threading+ import sqlcipher3+ from local_deep_research.database import sqlcipher_compat++ path = Path(sys.argv[1]) / 'owned.db'+ wal = Path(str(path) + '-wal')+ key = 'PRAGMA key = "x\\\'' + ('ab' * 32) + '\\\'"'++ setup = sqlcipher_compat.connect_sqlcipher(sqlcipher3, str(path))+ setup.execute(key)+ assert setup.execute('PRAGMA journal_mode=WAL').fetchone()[0] == 'wal'+ setup.execute('CREATE TABLE canary (value INTEGER)')+ setup.execute('INSERT INTO canary VALUES (1)')+ setup.commit()+ setup.close()++ class RecordingLock:+ def __init__(self):+ self.lock = threading.RLock()+ self.releases = []+ def __enter__(self):+ self.lock.acquire()+ return self+ def __exit__(self, *exc_info):+ self.releases.append((threading.get_ident(), wal.exists()))+ self.lock.release()++ recorder = RecordingLock()+ sqlcipher_compat._lifecycle_lock = recorder+ handed_over = []+ opened = threading.Event()+ finish = threading.Event()++ def owner():+ # Default check_same_thread=True, as the backup and key-check+ # sites use it.+ connection = sqlcipher_compat.connect_sqlcipher(sqlcipher3, str(path))+ connection.execute(key)+ cursor = connection.cursor()+ cursor.execute('SELECT value FROM canary')+ handed_over.extend([connection, cursor])+ del connection, cursor+ opened.set()+ finish.wait(timeout=20)++ creator = threading.Thread(target=owner)+ creator.start()+ assert opened.wait(timeout=10)+ assert wal.exists()+ connection, cursor = handed_over+ handed_over.clear()+ refused = []+ for name, call in [+ ('connection.execute', lambda: connection.execute('SELECT 1')),+ ('connection.cursor', connection.cursor),+ ('connection.commit', connection.commit),+ ('connection.close', connection.close),+ ('cursor.fetchone', cursor.fetchone),+ ('cursor.execute', lambda: cursor.execute('SELECT 1')),+ ]:+ try:+ call()+ except sqlcipher3.ProgrammingError as exc:+ if 'same thread' in str(exc):+ refused.append(name)+ assert wal.exists()+ recorder.releases.clear()+ del cursor, call+ del connection+ gc.collect()+ closed_under_lock = (threading.get_ident(), False) in recorder.releases+ wal_removed = not wal.exists()+ finish.set()+ creator.join(timeout=10)++ shared = sqlcipher_compat.connect_sqlcipher(+ sqlcipher3, ':memory:', check_same_thread=False+ )+ shared_rows = []+ worker = threading.Thread(+ target=lambda: shared_rows.append(shared.execute('SELECT 1').fetchone())+ )+ worker.start()+ worker.join(timeout=10)+ shared.close()+ print(json.dumps({+ 'closed_under_lock': closed_under_lock,+ 'wal_removed': wal_removed,+ 'refused': refused,+ 'shared_rows': shared_rows,+ }))+ """,+ )+ assert result == {+ "closed_under_lock": True,+ "wal_removed": True,+ "refused": [+ "connection.execute",+ "connection.cursor",+ "connection.commit",+ "connection.close",+ "cursor.fetchone",+ "cursor.execute",+ ],+ "shared_rows": [[1]],+ }++[email protected](os.name != "posix", reason="the guard is POSIX-only")+def test_isolation_level_setter_matches_native_thread_check():+ # Setting isolation_level to None commits through the driver's own+ # commit, bypassing the wrapped commit(). The native check refuses it+ # from a foreign thread; other values and the getter stay unchecked.+ sqlcipher3 = pytest.importorskip(+ "sqlcipher3", reason="requires the real SQLCipher driver"+ )+ native_driver = SimpleNamespace(+ sqlite_version_info=(3, 51, 1),+ Connection=sqlcipher3.Connection,+ Cursor=sqlcipher3.Cursor,+ connect=sqlcipher3.connect,+ )+ opened = {}+ ready = threading.Event()+ finish = threading.Event()++ def owner():+ opened["native"] = sqlcipher3.connect(":memory:")+ opened["guarded"] = sqlcipher_compat.connect_sqlcipher(+ native_driver, ":memory:"+ )+ for connection in opened.values():+ connection.execute("CREATE TABLE canary (value INTEGER)")+ connection.execute("INSERT INTO canary VALUES (1)")+ ready.set()+ finish.wait(timeout=10)+ for connection in opened.values():+ connection.close()++ thread = threading.Thread(target=owner)+ thread.start()+ try:+ assert ready.wait(timeout=10)+ outcomes = {}+ for name, connection in opened.items():+ try:+ connection.isolation_level = None+ except sqlcipher3.ProgrammingError as exc:+ refused = "same thread" in str(exc)+ else:+ refused = False+ connection.isolation_level = "IMMEDIATE"+ with pytest.raises(AttributeError):+ del connection.isolation_level+ outcomes[name] = (+ refused,+ connection.in_transaction,+ connection.isolation_level,+ )+ finally:+ finish.set()+ thread.join(timeout=10)+ assert type(opened["guarded"]) is not sqlcipher3.Connection+ assert (+ outcomes["guarded"]+ == outcomes["native"]+ == (+ True,+ True,+ "IMMEDIATE",+ )+ )+++def test_leaving_wal_mode_does_not_wedge_concurrent_opens(tmp_path):+ # Leaving WAL closes the WAL inside SQLite's pager and takes the same+ # inverted VFS mutexes as a connection close on SQLite 3.51.0/3.51.1.+ result = _run_driver_process(+ tmp_path,+ """+ import json+ import os+ from pathlib import Path+ import sys+ import threading+ import time+ os.environ['LDR_DB_CONFIG_JOURNAL_MODE'] = 'DELETE'+ # No fsync, so the switch loop is not bounded by the disk.+ os.environ['LDR_DB_CONFIG_SYNCHRONOUS'] = 'OFF'+ import sqlcipher3+ from local_deep_research.database.sqlcipher_compat import connect_sqlcipher+ from local_deep_research.database.sqlcipher_utils import apply_performance_pragmas++ path = Path(sys.argv[1]) / 'switch.db'+ key = 'PRAGMA key = "x\\\'' + ('ab' * 32) + '\\\'"'++ def connect():+ connection = connect_sqlcipher(sqlcipher3, str(path), check_same_thread=False)+ connection.execute(key)+ return connection++ connection = connect()+ assert connection.execute('PRAGMA journal_mode=WAL').fetchone()[0] == 'wal'+ connection.execute('CREATE TABLE canary (value INTEGER)')+ connection.execute('INSERT INTO canary VALUES (1)')+ connection.commit()+ connection.close()+ state = {'done': False, 'switched': 0, 'opens': 0, 'errors': []}+ barrier = threading.Barrier(3)++ def switch():+ try:+ barrier.wait(timeout=5)+ deadline = time.monotonic() + 8+ while state['switched'] < 1500 and time.monotonic() < deadline:+ connection = connect()+ try:+ connection.execute('PRAGMA synchronous = OFF')+ assert connection.execute('SELECT value FROM canary').fetchone() == (1,)+ apply_performance_pragmas(connection)+ if connection.execute('PRAGMA journal_mode').fetchone()[0] == 'delete':+ state['switched'] += 1+ connection.execute('PRAGMA journal_mode = WAL').fetchone()+ finally:+ connection.close()+ except BaseException as exc:+ state['errors'].append(repr(exc))+ finally:+ state['done'] = True++ def churn():+ try:+ barrier.wait(timeout=5)+ while not state['done']:+ connect().close()+ state['opens'] += 1+ except BaseException as exc:+ state['errors'].append(repr(exc))++ threads = [threading.Thread(target=target) for target in (switch, churn, churn)]+ for thread in threads:+ thread.start()+ for thread in threads:+ thread.join()+ print(json.dumps({+ 'switched': state['switched'] >= 50,+ 'opened': state['opens'] > 0,+ 'errors': state['errors'],+ }))+ """,+ )+ assert result == {"switched": True, "opened": True, "errors": []}+++ ("mode", "guarded"),+ [+ ("DELETE", True),+ ("TRUNCATE", True),+ ("PERSIST", True),+ ("MEMORY", True),+ ("OFF", True),+ ("WAL", False),+ ],+)+def test_journal_mode_change_holds_lifecycle_lock_unless_wal(+ monkeypatch, mode, guarded+):+ from local_deep_research.database.sqlcipher_utils import (+ apply_performance_pragmas,+ )++ monkeypatch.setenv("LDR_DB_CONFIG_JOURNAL_MODE", mode)+ held = []++ def execute(statement):+ if statement.startswith("PRAGMA journal_mode"):+ held.append(+ (statement, sqlcipher_compat._lifecycle_lock._is_owned())+ )++ apply_performance_pragmas(SimpleNamespace(execute=execute))+ assert held == [(f"PRAGMA journal_mode = {mode}", guarded)]+++def test_journal_mode_refuses_sql_payload_before_execution(monkeypatch):+ from local_deep_research.database import sqlcipher_utils++ def get_setting(key, default=None):+ if key == "db_config.journal_mode":+ return "WAL; ATTACH DATABASE '/tmp/other.db' AS other"+ return default++ monkeypatch.setattr(sqlcipher_utils, "get_env_setting", get_setting)+ statements = []+ with pytest.raises(ValueError, match="Invalid journal_mode"):+ sqlcipher_utils.apply_performance_pragmas(+ SimpleNamespace(execute=statements.append)+ )+ assert not any("journal_mode" in statement for statement in statements)