~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
test(database): synchronize SQLCipher contention and readers (#7074)
LearningCircuitf217cd64c26c
diff --git a/changelog.d/+sqlcipher-contention-synchronization.misc.md b/changelog.d/+sqlcipher-contention-synchronization.misc.mdnew file mode 100644index 0000000000..bf6639d8f3--- /dev/null+++ b/changelog.d/+sqlcipher-contention-synchronization.misc.md@@ -0,0 +1,4 @@+Database contention tests now confirm the first writer holds its transaction before the second writer attempts an update, retaining the successful-write and timeout checks under slow SQLCipher connection setup.+The WAL reader test completes connection setup before measuring its query, and+the shutdown test waits for a real read before stopping its reader. Existing+read-latency and shutdown limits remain unchanged. Report the native busy timeout and actual transaction lock duration when contention checks fail.diff --git a/tests/database/test_busy_timeout_contention.py b/tests/database/test_busy_timeout_contention.pyindex 2dae5ffd6c..531c0384c5 100644--- a/tests/database/test_busy_timeout_contention.py+++ b/tests/database/test_busy_timeout_contention.py@@ -251,6 +251,94 @@ class TestBusyTimeoutUnderContention:conn.commit()conn.close()+ @staticmethod+ def _run_contention(sqlcipher_module, db_path, holder_duration):+ # Finish connection setup (including SQLCipher key derivation) before+ # either thread attempts a write. Measure the contended UPDATE itself.+ ready = threading.Barrier(2, timeout=10)+ lock_held = threading.Event()+ writer_started = threading.Event()+ writer_result = {+ "elapsed": None,+ "error": None,+ "busy_timeout_ms": None,+ "holder_elapsed": None,+ }+ holder_errors = []++ def holder():+ try:+ conn = _open_and_configure(sqlcipher_module, db_path)+ try:+ ready.wait()+ conn.execute("BEGIN IMMEDIATE")+ hold_started = time.monotonic()+ conn.execute("UPDATE counters SET n = n + 100 WHERE id = 1")+ lock_held.set()+ assert writer_started.wait(10), (+ "Writer did not attempt UPDATE"+ )+ time.sleep(holder_duration)+ conn.execute(+ "UPDATE counters SET n = n + 1000 WHERE id = 1"+ )+ conn.commit()+ writer_result["holder_elapsed"] = (+ time.monotonic() - hold_started+ )+ finally:+ conn.close()+ except Exception as exc:+ holder_errors.append(exc)+ ready.abort()++ def writer():+ try:+ conn = _open_and_configure(sqlcipher_module, db_path)+ try:+ writer_result["busy_timeout_ms"] = conn.execute(+ "PRAGMA busy_timeout"+ ).fetchone()[0]+ ready.wait()+ assert lock_held.wait(10), (+ "Holder did not acquire writer lock"+ )+ start = time.monotonic()+ writer_started.set()+ try:+ conn.execute(+ "UPDATE counters SET n = n + 1 WHERE id = 1"+ )+ conn.commit()+ finally:+ writer_result["elapsed"] = time.monotonic() - start+ finally:+ conn.close()+ except Exception as exc:+ writer_result["error"] = exc+ ready.abort()++ t_holder = threading.Thread(target=holder, name="busy-timeout-holder")+ t_writer = threading.Thread(target=writer, name="busy-timeout-writer")+ t_holder.start()+ t_writer.start()+ t_holder.join(15)+ t_writer.join(15)+ assert not t_holder.is_alive(), "Holder thread did not finish"+ assert not t_writer.is_alive(), "Writer thread did not finish"+ assert not holder_errors, f"Holder failed: {holder_errors!r}"+ assert writer_result["elapsed"] is not None, (+ "Writer did not attempt UPDATE"+ )+ conn = _open_and_configure(sqlcipher_module, db_path)+ try:+ writer_result["value"] = conn.execute(+ "SELECT n FROM counters WHERE id = 1"+ ).fetchone()[0]+ finally:+ conn.close()+ return writer_result+def test_writer_waits_for_long_transaction(self, sqlcipher_module, temp_db_path, monkeypatch):@@ -278,7 +366,7 @@ class TestBusyTimeoutUnderContention:We force ``busy_timeout`` to 2 s via the env var so the testruns in seconds, not the default 30 s. ``holder_duration`` is1 s -- well inside the timeout, so the writer's commit lands- while the holder is still sleeping. The default-value test+ after the holder commits. The default-value test(``TestBusyTimeoutDefault::test_default_is_30000ms``) pinsthe production default."""@@ -288,54 +376,21 @@ class TestBusyTimeoutUnderContention:self._init_db(sqlcipher_module, temp_db_path)holder_duration = 1.0 # seconds -- well within the 2 s timeout- writer_result = {"elapsed": None, "error": None}-- def holder():- conn = _open_and_configure(sqlcipher_module, temp_db_path)- try:- conn.execute("BEGIN IMMEDIATE")- conn.execute("UPDATE counters SET n = n + 100 WHERE id = 1")- # Hold the writer lock across a sleep. SQLite blocks- # any concurrent writer until COMMIT.- time.sleep(holder_duration)- conn.execute("UPDATE counters SET n = n + 1000 WHERE id = 1")- conn.commit()- finally:- conn.close()-- def writer():- start = time.monotonic()- try:- conn = _open_and_configure(sqlcipher_module, temp_db_path)- try:- conn.execute("UPDATE counters SET n = n + 1 WHERE id = 1")- conn.commit()- finally:- conn.close()- except Exception as e: # pragma: no cover -- failure path- writer_result["error"] = e- writer_result["elapsed"] = time.monotonic() - start-- t_holder = threading.Thread(target=holder)- t_writer = threading.Thread(target=writer)- # Start the holder first so its write transaction is in flight- # before the writer tries to commit. The small sleep gives the- # holder's BEGIN IMMEDIATE a chance to acquire the writer lock.- t_holder.start()- time.sleep(0.1)- t_writer.start()- t_holder.join()- t_writer.join()+ writer_result = self._run_contention(+ sqlcipher_module, temp_db_path, holder_duration+ )# The writer must have waited for the holder to commit, not# failed. If the writer finished in less than# ``holder_duration``, the lock wasn't actually held and the# test is degenerate -- surface that as a failure rather# than passing silently.+ assert writer_result["busy_timeout_ms"] == 2000, writer_resultassert writer_result["error"] is None, (f"Writer raised {writer_result['error']!r}; the configured ""busy_timeout (2 s) should have been long enough to wait "- f"out the holder's {holder_duration}s lock."+ f"out the holder's {holder_duration}s lock. "+ f"Actual contention: {writer_result!r}")assert writer_result["elapsed"] >= holder_duration * 0.8, (f"Writer elapsed ({writer_result['elapsed']:.2f}s) was much "@@ -351,6 +406,8 @@ class TestBusyTimeoutUnderContention:"may not have held the writer lock for the full duration.")+ assert writer_result["value"] == 1101+def test_writer_times_out_when_holder_exceeds_timeout(self, sqlcipher_module, temp_db_path, monkeypatch):@@ -374,42 +431,13 @@ class TestBusyTimeoutUnderContention:# Hold for longer than the timeout so the writer is guaranteed# to hit it.holder_duration = 1.5 # seconds- writer_result = {"elapsed": None, "error": None}-- def holder():- conn = _open_and_configure(sqlcipher_module, temp_db_path)- try:- conn.execute("BEGIN IMMEDIATE")- conn.execute("UPDATE counters SET n = n + 100 WHERE id = 1")- time.sleep(holder_duration)- conn.execute("UPDATE counters SET n = n + 1000 WHERE id = 1")- conn.commit()- finally:- conn.close()-- def writer():- start = time.monotonic()- try:- conn = _open_and_configure(sqlcipher_module, temp_db_path)- try:- conn.execute("UPDATE counters SET n = n + 1 WHERE id = 1")- conn.commit()- finally:- conn.close()- except Exception as e:- writer_result["error"] = e- writer_result["elapsed"] = time.monotonic() - start-- t_holder = threading.Thread(target=holder)- t_writer = threading.Thread(target=writer)- t_holder.start()- time.sleep(0.1)- t_writer.start()- t_holder.join()- t_writer.join()+ writer_result = self._run_contention(+ sqlcipher_module, temp_db_path, holder_duration+ )# The writer must have failed with a "database is locked" error# after waiting approximately ``busy_timeout`` (0.5 s here).+ assert writer_result["busy_timeout_ms"] == 500, writer_resultassert writer_result["error"] is not None, ("Writer did not raise; a 1.5 s holder against a 0.5 s ""busy_timeout should have caused the writer to time out."@@ -425,3 +453,4 @@ class TestBusyTimeoutUnderContention:"much shorter than the configured busy_timeout (0.5 s); ""the writer may not have actually waited.")+ assert writer_result["value"] == 1100diff --git a/tests/database/test_sqlcipher_integration.py b/tests/database/test_sqlcipher_integration.pyindex 3a749e3b87..2c3852ecf7 100644--- a/tests/database/test_sqlcipher_integration.py+++ b/tests/database/test_sqlcipher_integration.py@@ -1641,6 +1641,7 @@ class TestSQLCipherIntegration:"""import threadingimport time+ from contextlib import closingusername = "reader_writer_user"password = "SecurePassword123!"@@ -1657,6 +1658,7 @@ class TestSQLCipherIntegration:conn.execute(text("INSERT INTO rw_test VALUES (1, 100)"))conn.commit()+ connections_ready = threading.Barrier(3, timeout=10)writer_started = threading.Event()writer_release = threading.Event()reader_done = threading.Event()@@ -1665,61 +1667,84 @@ class TestSQLCipherIntegration:def writer():try:- sess = (+ with closing(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()+ ) as sess:+ # Finish physical connection setup before the writer+ # holds its lock and the reader's latency is measured.+ sess.connection()+ connections_ready.wait()+ sess.execute(+ text("UPDATE rw_test SET v = 200 WHERE id = 1")+ )+ writer_started.set()+ assert writer_release.wait(timeout=5), (+ "Writer was not released"+ )+ sess.commit()except Exception as e:errors.append(f"writer: {e}")+ connections_ready.abort()def reader():try:- writer_started.wait(timeout=5)- start = time.perf_counter()- sess = (+ with closing(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()+ ) as sess:+ sess.connection()+ connections_ready.wait()+ assert writer_started.wait(timeout=5), (+ "Writer did not acquire lock"+ )+ start = time.perf_counter()+ result = sess.execute(+ text("SELECT v FROM rw_test WHERE id = 1")+ ).fetchone()+ reader_elapsed_ms[0] = (time.perf_counter() - start) * 1000+ # The writer still owns its transaction: read the+ # committed snapshot, never its pending value.+ assert result is not None and result[0] == 100, (+ f"Reader saw wrong snapshot: {result}"+ )+ sess.rollback()except Exception as e:errors.append(f"reader: {e}")+ connections_ready.abort()+ finally:reader_done.set()- wt = threading.Thread(target=writer, daemon=True)- rt = threading.Thread(target=reader, daemon=True)+ wt = threading.Thread(+ target=writer, name="sqlcipher-writer", daemon=True+ )+ rt = threading.Thread(+ target=reader, name="sqlcipher-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)+ try:+ connections_ready.wait()+ assert reader_done.wait(timeout=3), (+ "Reader was blocked by writer — IMMEDIATE-style serialisation"+ )+ finally:+ writer_release.set()+ wt.join(timeout=5)+ rt.join(timeout=5)+ assert not wt.is_alive(), "Writer thread did not stop"+ assert not rt.is_alive(), "Reader thread did not stop"assert not errors, f"errors: {errors}"- assert reader_elapsed_ms[0] < 1000, (+ assert (+ reader_elapsed_ms[0] is not None and reader_elapsed_ms[0] < 1000+ ), (f"Reader took {reader_elapsed_ms[0]:.0f}ms — ""too long for a concurrent read under WAL + DEFERRED")@@ -4681,13 +4706,9 @@ class TestSQLCipherIntegration:assert count == 10, f"Thread {thread_id} got wrong count: {count}"def test_library_shutdown_thread_safety(self, tmp_path):- """Test library handles connection close while operations may be active.-- Thread safety improvements in SQLCipher 4.9.0 for shutdown sequences.- Tests graceful handling when closing connection from another thread.- """+ """A reader stops and closes its own connection cleanly after reading."""import threading- import time+ from contextlib import closingfrom local_deep_research.database.sqlcipher_compat import (get_sqlcipher_module,@@ -4709,70 +4730,51 @@ class TestSQLCipherIntegration:conn.commit()conn.close()- # Use separate connections for reader and closerread_errors = []read_count = [0]+ first_read = threading.Event()stop_reading = threading.Event()def continuous_reader():"""Continuously read from database until stopped."""try:- reader_conn = pysqlcipher3.connect(str(db_path))- reader_cursor = reader_conn.cursor()- reader_cursor.execute(f"PRAGMA key = '{password}'")-- while not stop_reading.is_set():- try:+ with closing(pysqlcipher3.connect(str(db_path))) as reader_conn:+ reader_cursor = reader_conn.cursor()+ reader_cursor.execute(f"PRAGMA key = '{password}'")+ while not stop_reading.is_set():reader_cursor.execute("SELECT COUNT(*) FROM shutdown_test")- reader_cursor.fetchone()+ assert reader_cursor.fetchone()[0] == 100read_count[0] += 1- except Exception as e:- error_msg = str(e).lower()- # Database closed/locked errors are expected- if not any(- x in error_msg- for x in ["closed", "locked", "cannot operate"]- ):- read_errors.append(str(e))- break- reader_conn.close()+ first_read.set()except Exception as e:- error_msg = str(e).lower()- if not any(x in error_msg for x in ["closed", "locked"]):- read_errors.append(str(e))+ read_errors.append(str(e))# Start reader threadreader_thread = threading.Thread(target=continuous_reader)reader_thread.start()- # Let reader run briefly- time.sleep(0.1)-- # Signal stop and wait for reader- stop_reading.set()- reader_thread.join(timeout=5)+ try:+ # Connection setup and SQLCipher's first-read key derivation+ # can exceed a fixed sleep. Stop only after a real read.+ assert first_read.wait(timeout=5), (+ f"Reader did not complete its first read: {read_errors}"+ )+ finally:+ stop_reading.set()+ reader_thread.join(timeout=5)- if reader_thread.is_alive():- pytest.fail("Reader thread did not stop gracefully")+ assert not reader_thread.is_alive(), (+ "Reader thread did not stop gracefully"+ )# Check that some reads completedassert read_count[0] >= 1, ("Reader should have completed at least one read")- # Check for unexpected errors (not related to normal shutdown)- critical_errors = [- e- for e in read_errors- if "crash" in e.lower()- or "segfault" in e.lower()- or "abort" in e.lower()- ]- assert not critical_errors, (- f"Critical errors during shutdown: {critical_errors}"- )+ assert not read_errors, f"Errors during reader shutdown: {read_errors}"# ========================================================================# SQLCipher 4.x Compatibility Tests (January 2026)