Skip to content

~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.

fix(db): serialize per-user DB cold-open to prevent concurrent-migration race (#4665)

LearningCircuit74557c2ac676
diff --git a/src/local_deep_research/database/encrypted_db.py b/src/local_deep_research/database/encrypted_db.py
index 2d27a86cec..dbbab3e02f 100644
--- a/src/local_deep_research/database/encrypted_db.py
+++ b/src/local_deep_research/database/encrypted_db.py
@@ -68,6 +68,11 @@ class DatabaseManager:
def __init__(self):
self.connections: Dict[str, Engine] = {}
self._connections_lock = threading.RLock()
+ # Per-user locks serializing the cold-open (engine build + migration)
+ # so two concurrent first-opens of one user never run alembic against
+ # the same database file at once. Created lazily under
+ # _connections_lock; see open_user_database / _get_init_lock.
+ self._init_locks: Dict[str, threading.Lock] = {}
self.data_dir = get_data_directory() / "encrypted_databases"
self.data_dir.mkdir(parents=True, exist_ok=True)
@@ -563,6 +568,22 @@ class DatabaseManager:
logger.info(f"Created encrypted database for user {username}")
return engine
+ def _get_init_lock(self, username: str) -> threading.Lock:
+ """Return the per-user cold-open lock, creating it on first use.
+
+ Guards the engine-build + migration in ``open_user_database`` so two
+ concurrent first-opens of the same user serialize instead of running
+ migrations against one database file simultaneously. Per-user (not the
+ global ``_connections_lock``) so different users still open in
+ parallel.
+ """
+ with self._connections_lock:
+ lock = self._init_locks.get(username)
+ if lock is None:
+ lock = threading.Lock()
+ self._init_locks[username] = lock
+ return lock
+
def open_user_database(
self, username: str, password: str
) -> Optional[Engine]:
@@ -589,6 +610,28 @@ class DatabaseManager:
if username in self.connections:
return self.connections[username]
+ # Serialize the cold-open (engine build + migration) per user so two
+ # concurrent first-opens never run alembic against the same database
+ # file at once -- alembic's module-level proxy and the version-row
+ # UPDATE are not safe under concurrent migration of one DB.
+ init_lock = self._get_init_lock(username)
+ with init_lock:
+ # Re-check: another thread may have completed the cold-open while
+ # we were waiting for the per-user lock.
+ with self._connections_lock:
+ if username in self.connections:
+ return self.connections[username]
+ return self._open_user_database_cold(username, password, open_start)
+
+ def _open_user_database_cold(
+ self, username: str, password: str, open_start: float
+ ) -> Optional[Engine]:
+ """Build the engine and run migrations for a not-yet-cached user DB.
+
+ Must be called while holding this user's init lock (acquired in
+ ``open_user_database``) so concurrent first-opens of the same user do
+ not migrate one database file simultaneously.
+ """
db_path = self._get_user_db_path(username)
# Prevent timing attacks: always derive key before checking file existence
@@ -821,6 +864,15 @@ class DatabaseManager:
f"Failed to dispose engine for {username}",
)
del self.connections[username]
+ # Deliberately do NOT pop _init_locks[username] here. A
+ # concurrent open_user_database may already hold a reference to
+ # this user's lock (fetched via _get_init_lock) and be about to
+ # enter its cold-open; dropping the entry would let a later open
+ # create a *second* lock for the same user, so two cold-opens
+ # 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.
logger.info(f"Closed database for user {username}")
def close_all_databases(self):
@@ -833,6 +885,7 @@ class DatabaseManager:
except Exception:
logger.debug(f"Error disposing engine for {username}")
self.connections.clear()
+ self._init_locks.clear()
def check_database_integrity(self, username: str) -> bool:
"""Check integrity of a user's encrypted database."""
diff --git a/tests/database/test_concurrent_user_db_open.py b/tests/database/test_concurrent_user_db_open.py
new file mode 100644
index 0000000000..6b353e9bbb
--- /dev/null
+++ b/tests/database/test_concurrent_user_db_open.py
@@ -0,0 +1,176 @@
+"""Concurrency tests for ``DatabaseManager.open_user_database`` cold-open.
+
+Regression test for the race where two simultaneous first-opens of the same
+user's database both ran Alembic migrations against one database file at once,
+with the loser failing (Alembic's non-thread-safe module-level proxy / the
+``alembic_version`` row update). The per-user init lock must serialize the
+cold-open so the engine build + migration runs exactly once.
+"""
+
+import threading
+import time
+
+import pytest
+
+import local_deep_research.database.initialize as init_mod
+from local_deep_research.database.encrypted_db import DatabaseManager
+
+
+def db_manager(tmp_path, monkeypatch):
+ monkeypatch.setattr(
+ "local_deep_research.database.encrypted_db.get_data_directory",
+ lambda: tmp_path,
+ )
+ manager = DatabaseManager()
+ yield manager
+ for username in list(manager.connections.keys()):
+ manager.close_user_database(username)
+
+
+def test_get_init_lock_is_per_user_and_stable(db_manager):
+ """Same user -> same lock (serializes); different users -> different locks."""
+ alice_1 = db_manager._get_init_lock("alice")
+ alice_2 = db_manager._get_init_lock("alice")
+ bob = db_manager._get_init_lock("bob")
+ assert alice_1 is alice_2
+ assert alice_1 is not bob
+
+
+def test_concurrent_cold_open_runs_init_once(db_manager, monkeypatch):
+ """N simultaneous first-opens of one user trigger exactly one cold-open."""
+ username, password = "raceuser", "TestPassword123!"
+ db_manager.create_user_database(username, password)
+ # Evict (and dispose) the cached engine so the next opens are cold-opens
+ # that hit the build + migrate path concurrently. The DB file remains.
+ db_manager.close_user_database(username)
+
+ n_threads = 8
+ calls = []
+ barrier = threading.Barrier(n_threads)
+
+ def counting_init(engine, *args, **kwargs):
+ # create_user_database already migrated the DB to head, so a no-op is
+ # correct here; the sleep widens the window so all threads pile up on
+ # the per-user lock while the first thread is inside the cold-open.
+ calls.append(threading.current_thread().name)
+ # Real wall-clock sleep widens the race window so the other threads
+ # pile up on the per-user lock; freezegun cannot model concurrent
+ # thread timing, so the sleep is intentional here.
+ time.sleep(0.25) # allow: unmarked-sleep
+
+ monkeypatch.setattr(init_mod, "initialize_database", counting_init)
+
+ results = []
+ errors = []
+
+ def worker():
+ barrier.wait()
+ try:
+ results.append(db_manager.open_user_database(username, password))
+ except Exception as exc: # noqa: BLE001 - record any failure
+ errors.append(exc)
+
+ threads = [
+ threading.Thread(target=worker, name=f"open-{i}")
+ for i in range(n_threads)
+ ]
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join(timeout=30)
+
+ assert not errors, f"cold-open raced and failed: {errors!r}"
+ assert len(results) == n_threads
+ # The cold-open (hence the migration) ran exactly once despite n_threads
+ # simultaneous first-opens.
+ assert len(calls) == 1, (
+ f"init ran {len(calls)}x; expected 1 (cold-open not serialized)"
+ )
+ # Every caller received the single engine the cold-open built and cached.
+ assert results[0] is not None
+ assert all(r is results[0] for r in results)
+
+
+def test_close_user_database_keeps_init_lock(db_manager):
+ """close_user_database intentionally retains the per-user init lock.
+
+ Dropping it on close would let a concurrent open that already holds a
+ reference 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.
+ """
+ username, password = "lockcleanup", "TestPassword123!"
+ db_manager.create_user_database(username, password)
+ db_manager._get_init_lock(username) # ensure the lock exists
+ assert username in db_manager._init_locks
+
+ db_manager.close_user_database(username)
+
+ # Retained on purpose -- see docstring; only close_all clears it.
+ 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."""
+ 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
+
+ db_manager.close_all_databases()
+
+ assert db_manager._init_locks == {}
+
+
+def test_concurrent_opens_of_different_users_run_in_parallel(
+ db_manager, monkeypatch
+):
+ """Cold-opens of *different* users must not serialize against each other.
+
+ The lock is deliberately per-user, not a single global init lock, so two
+ users opening at once proceed in parallel. This is asserted
+ deterministically (no timing): a 2-party barrier inside the patched init
+ only releases when *both* users' cold-opens are inside it simultaneously.
+ If the opens serialized (e.g. a regression to one global lock), the first
+ thread would block at the barrier while holding the lock and the second
+ could never reach it -> the barrier times out with BrokenBarrierError,
+ surfaced as an error and failing the test.
+ """
+ users = [("alice_par", "TestPassword123!"), ("bob_par", "TestPassword123!")]
+ for name, pw in users:
+ db_manager.create_user_database(name, pw)
+ # Evict the cached engine so the next open is a cold-open.
+ db_manager.close_user_database(name)
+
+ both_inside_init = threading.Barrier(len(users))
+
+ def barrier_init(engine, *args, **kwargs):
+ # Both users' cold-opens must be in here at once for this to return;
+ # a global lock would deadlock one of them out and trip the timeout.
+ both_inside_init.wait(timeout=10)
+
+ monkeypatch.setattr(init_mod, "initialize_database", barrier_init)
+
+ results = []
+ errors = []
+
+ def worker(name, pw):
+ try:
+ results.append(db_manager.open_user_database(name, pw))
+ except Exception as exc: # noqa: BLE001 - record any failure
+ errors.append(exc)
+
+ threads = [
+ threading.Thread(target=worker, args=(n, p), name=f"open-{n}")
+ for n, p in users
+ ]
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join(timeout=30)
+
+ assert not errors, f"cross-user opens serialized / failed: {errors!r}"
+ assert len(results) == len(users)
+ assert all(r is not None for r in results)
diff --git a/tests/database/test_encrypted_db_coverage.py b/tests/database/test_encrypted_db_coverage.py
index e1a39afacc..2e13cbbfe2 100644
--- a/tests/database/test_encrypted_db_coverage.py
+++ b/tests/database/test_encrypted_db_coverage.py
@@ -49,6 +49,9 @@ def _unencrypted_manager():
mgr = DatabaseManager.__new__(DatabaseManager)
mgr.connections = {}
mgr._connections_lock = threading.RLock()
+ # __init__ is bypassed here; mirror its per-user init-lock dict so the
+ # close_*/open paths that reference mgr._init_locks don't AttributeError.
+ mgr._init_locks = {}
mgr.has_encryption = False
import os
diff --git a/tests/security/test_password_leakage.py b/tests/security/test_password_leakage.py
index 754351732d..a4b862a885 100644
--- a/tests/security/test_password_leakage.py
+++ b/tests/security/test_password_leakage.py
@@ -138,6 +138,9 @@ class TestEncryptedDBPasswordLeakage:
# uses a custom creator with ``sqlite://`` (no event.listen).
manager.has_encryption = True
manager.connections = {}
+ # __init__ is bypassed here; mirror its per-user init-lock dict so
+ # open_user_database -> _get_init_lock has its backing store.
+ manager._init_locks = {}
manager._connections_lock = MagicMock()
manager._connections_lock.__enter__ = lambda *a: None
manager._connections_lock.__exit__ = lambda *a: None
@@ -196,6 +199,9 @@ class TestEncryptedDBPasswordLeakage:
manager = DatabaseManager.__new__(DatabaseManager)
manager.has_encryption = True
manager.connections = {}
+ # __init__ is bypassed here; mirror its per-user init-lock dict so
+ # open_user_database -> _get_init_lock has its backing store.
+ manager._init_locks = {}
manager._connections_lock = MagicMock()
manager._connections_lock.__enter__ = lambda *a: None
manager._connections_lock.__exit__ = lambda *a: None