~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(db): drop isolation_level=IMMEDIATE — let WAL readers proceed (#3491)
LearningCircuit64403bbfcfa5
diff --git a/src/local_deep_research/database/encrypted_db.py b/src/local_deep_research/database/encrypted_db.pyindex 01a8133602..548762214b 100644--- a/src/local_deep_research/database/encrypted_db.py+++ b/src/local_deep_research/database/encrypted_db.py@@ -354,7 +354,16 @@ class DatabaseManager:password=password,creation_mode=True,connect_kwargs={- "isolation_level": "IMMEDIATE",+ # DEFERRED (empty string) so pure-SELECT transactions+ # acquire only SQLite's SHARED lock, letting WAL-mode+ # concurrent readers proceed while a writer is active.+ # IMMEDIATE was previously set "defensively" and made+ # every transaction (even reads) take a RESERVED lock,+ # which was the single biggest contention source on+ # the login-hang path. Race-prone check-then-insert+ # call sites were made race-free at the application+ # layer in the preceding prerequisite PR.+ "isolation_level": "","check_same_thread": False,},)@@ -407,7 +416,16 @@ class DatabaseManager:hex_key=hex_key,creation_mode=False,connect_kwargs={- "isolation_level": "IMMEDIATE",+ # DEFERRED (empty string) so pure-SELECT transactions+ # acquire only SQLite's SHARED lock, letting WAL-mode+ # concurrent readers proceed while a writer is active.+ # IMMEDIATE was previously set "defensively" and made+ # every transaction (even reads) take a RESERVED lock,+ # which was the single biggest contention source on+ # the login-hang path. Race-prone check-then-insert+ # call sites were made race-free at the application+ # layer in the preceding prerequisite PR.+ "isolation_level": "","check_same_thread": False,},)@@ -519,7 +537,16 @@ class DatabaseManager:hex_key=hex_key,creation_mode=False,connect_kwargs={- "isolation_level": "IMMEDIATE",+ # DEFERRED (empty string) so pure-SELECT transactions+ # acquire only SQLite's SHARED lock, letting WAL-mode+ # concurrent readers proceed while a writer is active.+ # IMMEDIATE was previously set "defensively" and made+ # every transaction (even reads) take a RESERVED lock,+ # which was the single biggest contention source on+ # the login-hang path. Race-prone check-then-insert+ # call sites were made race-free at the application+ # layer in the preceding prerequisite PR.+ "isolation_level": "","check_same_thread": False,},)diff --git a/src/local_deep_research/database/thread_local_session.py b/src/local_deep_research/database/thread_local_session.pyindex a8b10af559..88b07a1f29 100644--- a/src/local_deep_research/database/thread_local_session.py+++ b/src/local_deep_research/database/thread_local_session.py@@ -51,6 +51,13 @@ class ThreadLocalSessionManager:# Verify it's still validtry:self._local.session.execute(text("SELECT 1"))+ # Under DEFERRED isolation the validation SELECT opens+ # a transaction that holds a SHARED lock on SQLite+ # until an explicit commit/rollback. A long-lived+ # thread-local session reused across requests would+ # keep that lock held and block the first writer.+ # Roll it back so subsequent callers start fresh.+ self._local.session.rollback()return self._local.sessionexcept PendingRollbackError:# Session has a pending rollback (e.g. from a previous database lock error).@@ -61,6 +68,7 @@ class ThreadLocalSessionManager:try:self._local.session.rollback()self._local.session.execute(text("SELECT 1"))+ self._local.session.rollback()return self._local.sessionexcept Exception:logger.warning(diff --git a/tests/database/test_sqlcipher_integration.py b/tests/database/test_sqlcipher_integration.pyindex 0c5cd8ba28..f27690c483 100644--- a/tests/database/test_sqlcipher_integration.py+++ b/tests/database/test_sqlcipher_integration.py@@ -1630,6 +1630,100 @@ class TestSQLCipherIntegration:count = result.fetchone()[0]assert count == 50, f"Expected 50 rows, got {count}"+ def test_reader_not_blocked_by_concurrent_writer(self, isolated_db_manager):+ """Under DEFERRED isolation + WAL mode, a reader must not block+ behind an active writer. Previously IMMEDIATE isolation forced+ every transaction — including pure SELECTs — to take a RESERVED+ write lock, serialising readers behind writers and causing the+ login-hang symptom. After the IMMEDIATE → DEFERRED change, a+ reader should complete while a writer is still in its+ transaction.+ """+ import threading+ import time++ username = "reader_writer_user"+ password = "SecurePassword123!"++ isolated_db_manager.create_user_database(username, password)+ from sqlalchemy import text++ engine = isolated_db_manager.connections[username]++ with engine.connect() as conn:+ conn.execute(+ text("CREATE TABLE rw_test (id INTEGER PRIMARY KEY, v INT)")+ )+ conn.execute(text("INSERT INTO rw_test VALUES (1, 100)"))+ conn.commit()++ writer_started = threading.Event()+ writer_release = threading.Event()+ reader_done = threading.Event()+ reader_elapsed_ms = [None]+ errors = []++ def writer():+ try:+ sess = (+ isolated_db_manager.create_thread_safe_session_for_metrics(+ username, password+ )+ )+ # Open a write transaction and hold it until we say so.+ sess.execute(text("UPDATE rw_test SET v = 200 WHERE id = 1"))+ writer_started.set()+ writer_release.wait(timeout=5)+ sess.commit()+ sess.close()+ except Exception as e:+ errors.append(f"writer: {e}")++ def reader():+ try:+ writer_started.wait(timeout=5)+ start = time.perf_counter()+ sess = (+ isolated_db_manager.create_thread_safe_session_for_metrics(+ username, password+ )+ )+ result = sess.execute(+ text("SELECT v FROM rw_test WHERE id = 1")+ ).fetchone()+ sess.rollback()+ sess.close()+ reader_elapsed_ms[0] = (time.perf_counter() - start) * 1000+ # Must see the pre-commit snapshot value (100), not 200.+ assert result[0] == 100, (+ f"Reader saw uncommitted write (got {result[0]})"+ )+ reader_done.set()+ except Exception as e:+ errors.append(f"reader: {e}")+ reader_done.set()++ wt = threading.Thread(target=writer, daemon=True)+ rt = threading.Thread(target=reader, daemon=True)+ wt.start()+ rt.start()++ # The reader should finish quickly (well under 1s). If it takes+ # anywhere near busy_timeout (10s), we regressed into the+ # IMMEDIATE behaviour.+ assert reader_done.wait(timeout=3), (+ "Reader was blocked by writer — IMMEDIATE-style serialisation"+ )+ writer_release.set()+ wt.join(timeout=5)+ rt.join(timeout=5)++ assert not errors, f"errors: {errors}"+ assert reader_elapsed_ms[0] < 1000, (+ f"Reader took {reader_elapsed_ms[0]:.0f}ms — "+ "too long for a concurrent read under WAL + DEFERRED"+ )+def test_cipher_use_hmac_queryable(self, isolated_db_manager):"""Test that cipher_use_hmac returns expected value."""username = "testuser"diff --git a/tests/database/test_thread_local_session.py b/tests/database/test_thread_local_session.pyindex b215b248fc..62da557581 100644--- a/tests/database/test_thread_local_session.py+++ b/tests/database/test_thread_local_session.py@@ -210,7 +210,13 @@ class TestThreadLocalSessionManager:assert thread_id not in manager._thread_credentialsdef test_get_session_recovers_from_pending_rollback_error(self):- """Test that get_session recovers from PendingRollbackError via rollback."""+ """Test that get_session recovers from PendingRollbackError via rollback.++ Rollback is called twice in the recovery path: once to clear the+ pending-rollback state so the retry SELECT 1 can run, and once+ after that SELECT 1 succeeds to release the SHARED lock the+ validation transaction held under DEFERRED isolation.+ """from local_deep_research.database.thread_local_session import (ThreadLocalSessionManager,)@@ -231,7 +237,7 @@ class TestThreadLocalSessionManager:# Should recover the same session via rollbackassert result is mock_session- mock_session.rollback.assert_called_once()+ assert mock_session.rollback.call_count == 2assert mock_session.execute.call_count == 2def test_get_session_recreates_when_rollback_recovery_fails(self):diff --git a/tests/database/test_thread_local_session_coverage.py b/tests/database/test_thread_local_session_coverage.pyindex b654f48c1e..61eb2a3f01 100644--- a/tests/database/test_thread_local_session_coverage.py+++ b/tests/database/test_thread_local_session_coverage.py@@ -27,7 +27,13 @@ class TestGetSessionPendingRollback:"""Tests for PendingRollbackError recovery in get_session."""def test_pending_rollback_recovery_succeeds(self):- """PendingRollbackError is recovered via rollback."""+ """PendingRollbackError is recovered via rollback.++ Rollback is called twice in this path: once to clear the+ pending-rollback state so the retry SELECT 1 can run, and once+ more after the retry succeeds to release the SHARED lock the+ validation transaction holds under DEFERRED isolation.+ """mgr = ThreadLocalSessionManager()mock_session = MagicMock()# First call raises PendingRollbackError, after rollback it succeeds@@ -42,7 +48,7 @@ class TestGetSessionPendingRollback:result = mgr.get_session("user", "pass")assert result is mock_session- mock_session.rollback.assert_called_once()+ assert mock_session.rollback.call_count == 2def test_pending_rollback_recovery_fails_creates_new(self):"""When rollback recovery fails, creates a new session."""