~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): keep held init locks across close_all_databases (#6421)
Vladimir Babind406310c1d59
diff --git a/changelog.d/6417.bugfix.md b/changelog.d/6417.bugfix.mdnew file mode 100644index 0000000000..26c9f17dd7--- /dev/null+++ b/changelog.d/6417.bugfix.md@@ -0,0 +1 @@+`close_all_databases` no longer drops per-user init locks, so a concurrent `open_user_database` during shutdown can no longer end up with a second lock for the same user and run two cold-opens against one database file.diff --git a/src/local_deep_research/database/encrypted_db.py b/src/local_deep_research/database/encrypted_db.pyindex 0566eb4a6d..f17c57cca4 100644--- a/src/local_deep_research/database/encrypted_db.py+++ b/src/local_deep_research/database/encrypted_db.py@@ -1412,7 +1412,7 @@ class DatabaseManager:# could migrate one DB file at once -- the very race this lock# exists to prevent. The dict is bounded by the number of# distinct usernames (one small Lock each), so retaining it is- # cheap; close_all_databases clears it wholesale at shutdown.+ # cheap; close_all_databases likewise retains it (see there).logger.info(f"Closed database for user {username}")def close_all_databases(self):@@ -1426,7 +1426,16 @@ class DatabaseManager:logger.debug(f"Error disposing engine for {username}")self.connections.clear()self._password_verifiers.clear()- self._init_locks.clear()+ # _init_locks is deliberately NOT cleared, for the same reason as+ # _password_change_locks below: a concurrent open_user_database+ # may already hold a reference to a user's cold-open lock (fetched+ # via _get_init_lock) and be about to enter it. Dropping the entry+ # would let a later open create a SECOND lock for that user, so+ # two cold-opens could migrate one DB file at once -- the exact+ # race the lock exists to stop. A lock.locked() sweep cannot close+ # that window either (the reference is taken before the lock is+ # acquired). Bounded by the number of distinct usernames, one+ # small Lock each, so retaining it is cheap.# _password_change_locks is deliberately NOT cleared. An entry may# be held by a change_password still in flight, and dropping it# would let the next caller build a SECOND gate for that user anddiff --git a/tests/database/test_concurrent_user_db_open.py b/tests/database/test_concurrent_user_db_open.pyindex 1a05b8279f..9fcab8be63 100644--- a/tests/database/test_concurrent_user_db_open.py+++ b/tests/database/test_concurrent_user_db_open.py@@ -102,8 +102,8 @@ def test_close_user_database_keeps_init_lock(db_manager):Dropping it on close would let a concurrent open that already holds areference to the old lock race a later open that creates a fresh one --two cold-opens migrating one DB file at once, the race the lock prevents.- The lock is kept (bounded, one small Lock per username); only- close_all_databases clears the dict wholesale, at shutdown.+ The lock is kept (bounded, one small Lock per username);+ close_all_databases retains it for the same reason."""username, password = "lockcleanup", "TestPassword123!"db_manager.create_user_database(username, password)@@ -112,20 +112,50 @@ def test_close_user_database_keeps_init_lock(db_manager):db_manager.close_user_database(username)- # Retained on purpose -- see docstring; only close_all clears it.+ # Retained on purpose -- see docstring.assert username in db_manager._init_locks-def test_close_all_databases_clears_init_locks(db_manager):- """close_all_databases clears the per-user init-lock dict too."""+def test_close_all_databases_retains_init_locks(db_manager):+ """close_all_databases keeps every per-user init lock, held or not.++ A lock.locked() sweep cannot tell an idle entry from one that a concurrent+ open has already fetched via _get_init_lock but not yet entered, so the+ only safe policy is to retain the dict (bounded, one small Lock per user).+ """+ locks = {}for name in ("user_a", "user_b"):db_manager.create_user_database(name, "TestPassword123!")- db_manager._get_init_lock(name)- assert db_manager._init_locks+ locks[name] = db_manager._get_init_lock(name)db_manager.close_all_databases()- assert db_manager._init_locks == {}+ for name, lock in locks.items():+ assert db_manager._get_init_lock(name) is lock+++def test_close_all_databases_retains_held_init_lock(db_manager):+ """A held init lock survives close_all_databases with its identity intact.++ open_user_database holds the per-user init lock across the whole cold-open,+ so an entry may be held when close_all_databases runs. Dropping it would+ let the next open for that user create a second lock and run a second+ cold-open against the same file concurrently.+ """+ held = db_manager._get_init_lock("in_flight")+ held.acquire()+ try:+ db_manager.close_all_databases()++ assert db_manager._get_init_lock("in_flight") is held++ contender = db_manager._get_init_lock("in_flight")+ acquired = contender.acquire(blocking=False)+ if acquired:+ contender.release()+ assert acquired is False+ finally:+ held.release()def test_concurrent_opens_of_different_users_run_in_parallel(diff --git a/tests/database/test_encrypted_db_manager_contracts.py b/tests/database/test_encrypted_db_manager_contracts.pyindex 39f04515d0..7ee36d63a1 100644--- a/tests/database/test_encrypted_db_manager_contracts.py+++ b/tests/database/test_encrypted_db_manager_contracts.py@@ -343,11 +343,11 @@ def test_checkpoint_wal_failure_is_invisible_at_default_log_level(tmp_path):def test_init_lock_is_retained_after_close(tmp_path):- """The per-user init lock deliberately survives the close.+ """The per-user init lock deliberately survives BOTH close paths.Documented invariant: dropping it would let a later open create a SECONDlock for the same user, so two cold-opens could migrate one file at once.- ``close_all_databases`` is the only thing that clears it.+ Neither ``close_user_database`` nor ``close_all_databases`` clears it."""with _manager(lambda: tmp_path / "root") as mgr:lock = mgr._get_init_lock("alice")@@ -357,7 +357,7 @@ def test_init_lock_is_retained_after_close(tmp_path):assert mgr._init_locks.get("alice") is lockmgr.close_all_databases()- assert "alice" not in mgr._init_locks+ assert mgr._init_locks.get("alice") is lock# ===========================================================================diff --git a/tests/security/test_db_connection_close_all_race.py b/tests/security/test_db_connection_close_all_race.pyindex b761ce877e..7031330ee2 100644--- a/tests/security/test_db_connection_close_all_race.py+++ b/tests/security/test_db_connection_close_all_race.py@@ -3,10 +3,11 @@Incident context (PR #5596): the trust model of the connection cache is"an entry exists only together with its verifier, and only while acredential-verified open put it there". ``close_all_databases`` is the-shutdown-scale eviction: it clears ``connections``,-``_password_verifiers`` AND ``_init_locks`` wholesale, all under-``_connections_lock``. Racing it against open/close churn must never tear-that model:+shutdown-scale eviction: it clears ``connections`` and+``_password_verifiers`` wholesale, all under ``_connections_lock``+(``_init_locks`` is deliberately retained, like+``_password_change_locks``, so an in-flight open keeps its lock). Racing+it against open/close churn must never tear that model:* O1 single user: a churn thread cycling open(correct)+close while ateardown thread repeatedly calls close_all_databases. At every sampleddiff --git a/tests/security/test_db_connection_many_users.py b/tests/security/test_db_connection_many_users.pyindex 4a4ac049f0..f37fa5691c 100644--- a/tests/security/test_db_connection_many_users.py+++ b/tests/security/test_db_connection_many_users.py@@ -6,9 +6,9 @@ the connection layer. At scale -- many accounts churning through oneprocess -- two operational security properties must hold:* W1 after 30 sequential create/write/close cycles and a final- ``close_all_databases``, every map is empty (close_all clears all- three, encrypted_db.py::close_all_databases) and the liveness- accessors read zero;+ ``close_all_databases``, the engine and verifier maps are empty+ (encrypted_db.py::close_all_databases; ``_init_locks`` is deliberately+ retained, see that method) and the liveness accessors read zero;* W2 the same 30 users created and churned CONCURRENTLY across 4 threads(each owning a subset, barrier-start, EVERY user with its own distinctpassword), with the engine/verifier pairing invariant sampled under@@ -139,14 +139,16 @@ def _assert_fully_drained(manager):with manager._connections_lock:assert manager.connections == {}, "close_all left cached engines"assert manager._password_verifiers == {}, "close_all left verifiers"- assert manager._init_locks == {}, "close_all left init locks"+ # _init_locks is deliberately NOT drained by close_all: a cold-open+ # may still hold a per-user lock (see close_all_databases). Not a+ # leak -- the dict is bounded, one small Lock per username.assert manager.get_connected_usernames() == set()assert manager.get_memory_usage()["active_connections"] == 0def test_thirty_sequential_users_drain_all_state(manager):"""W1: 30 sequential create+canary+close cycles, then close_all:- all three maps empty, liveness accessors zero."""+ engine + verifier maps empty, liveness accessors zero."""if not manager.has_encryption:pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")@@ -171,9 +173,9 @@ def test_thirty_sequential_users_drain_all_state(manager):).scalar()assert note.startswith("gap-W-")manager.close_user_database(username)- # close_user_database deliberately RETAINS per-user init locks (see- # tests/database/test_concurrent_user_db_open.py); only close_all- # clears them, so drain via close_all before asserting emptiness.+ # Both close paths deliberately RETAIN per-user init locks (see+ # tests/database/test_concurrent_user_db_open.py and+ # close_all_databases); close_all drains engines + verifiers only.manager.close_all_databases()_assert_fully_drained(manager)@@ -182,7 +184,7 @@ def test_thirty_users_concurrent_churn_stays_paired(manager):"""W2: 30 users created and churned by 4 barrier-synced threads (eachowning a subset, each user with its OWN password): no open failures,pairing invariant at every sample, every user reopen+canary at the- end, all maps drained after close_all."""+ end, engine + verifier maps drained after close_all."""if not manager.has_encryption:pytest.skip("requires SQLCipher (encrypted mode) to be meaningful")