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 create_user_database per user with the init lock (#6377)

Lukas Buck064cd30b9fb0
diff --git a/src/local_deep_research/database/encrypted_db.py b/src/local_deep_research/database/encrypted_db.py
index e7c450bb03..2bc4e34e3d 100644
--- a/src/local_deep_research/database/encrypted_db.py
+++ b/src/local_deep_research/database/encrypted_db.py
@@ -534,7 +534,14 @@ class DatabaseManager:
return conn
def create_user_database(self, username: str, password: str) -> Engine:
- """Create a new encrypted database for a user."""
+ """Create a new database for a user (encrypted, or the unencrypted
+ fallback when SQLCipher is unavailable).
+
+ Serialized per user by the same init lock that guards cold opens:
+ two concurrent creates for one username used to both pass the
+ ``db_path.exists()`` guard, and the loser's orphaned-salt recovery
+ then unlinked the winner's in-flight ``.db``/``.salt`` (#6355).
+ """
# Validate the encryption key
if not self._is_valid_encryption_key(password):
@@ -545,6 +552,87 @@ class DatabaseManager:
"Invalid encryption key: password cannot be None or empty"
)
+ # Everything up to and including the cache publish runs under the
+ # lock, as in _open_user_database_cold: a concurrent first open of
+ # this user then waits here instead of migrating the same file at
+ # the same time as the create.
+ with self._get_init_lock(username):
+ db_path, engine = self._create_user_database_files(
+ username, password
+ )
+ self._initialize_new_user_database(
+ username, password, db_path, engine
+ )
+
+ logger.info(f"Created encrypted database for user {username}")
+ return engine
+
+ def _initialize_new_user_database(
+ self, username: str, password: str, db_path: Path, engine: Engine
+ ) -> None:
+ """Migrate a just-created user database and publish its engine.
+
+ Called by ``create_user_database`` while holding this user's init
+ lock. Removes the partial database when the migrations fail.
+ """
+ # Initialize database tables using centralized initialization
+ from .initialize import initialize_database
+
+ # Mirror of the fail-loud change #3635 made to open_user_database.
+ # Previously this swallowed the exception with "tables exist but
+ # schema version not stamped — migrations will be retried on next
+ # process restart". That left a half-broken DB on disk: tables
+ # present, no alembic_version row. The next login then re-ran
+ # alembic, hit the same error, and (post-#3635) 503'd — so the
+ # user could register but never log in again. Better to fail
+ # registration loudly with the partial DB removed, so the real
+ # cause (e.g. world-writable migrations dir) gets fixed instead
+ # of producing a permanently-locked-out account.
+ try:
+ Session = sessionmaker(bind=engine)
+ with Session() as session:
+ initialize_database(engine, session)
+ except Exception as e:
+ # ``password`` is in scope and was passed into the engine
+ # creator closure above. Drop the traceback to avoid leaking
+ # frame locals under ``diagnose=True`` and redact the
+ # password from str(e) defensively.
+ from ..security.log_sanitizer import redact_secrets
+
+ safe_msg = redact_secrets(str(e), password)
+ logger.warning(
+ f"Database migration failed for {username} during creation"
+ f" — removing partial DB: {safe_msg}"
+ )
+ engine.dispose()
+ # Remove the partial DB *and* its salt/WAL/journal sidecars so a
+ # retry of the same username isn't blocked by a leftover salt.
+ _remove_partial_user_db_files(db_path)
+ raise
+
+ # Restrict DB file to owner-only (0o600). The encrypted branch
+ # chmod's right after create_sqlcipher_connection, but the
+ # unencrypted fallback creates the file lazily on first connect
+ # (during initialize_database above), so it is only guaranteed to
+ # exist here. This file holds PLAINTEXT user data — leaving it at
+ # umask-default perms (commonly 0o644) would expose it to other
+ # local accounts.
+ if not self.has_encryption and db_path.exists():
+ _best_effort_chmod(db_path, 0o600, warn=True)
+
+ # Store connection AFTER migrations complete. This password just proved
+ # itself by creating the database; publish the engine and its verifier
+ # together so the cache is never briefly trusted without one.
+ self._cache_connection(username, engine, password)
+
+ def _create_user_database_files(
+ self, username: str, password: str
+ ) -> tuple[Path, Engine]:
+ """Create the on-disk database and its engine; caller holds the init lock.
+
+ Returns the database path and an engine whose tables exist but whose
+ migrations have not run yet.
+ """
db_path = self._get_user_db_path(username)
if db_path.exists():
@@ -751,58 +839,7 @@ class DatabaseManager:
# Tables have already been created using raw SQLCipher above
# No need to create them again with SQLAlchemy
- # Initialize database tables using centralized initialization
- from .initialize import initialize_database
-
- # Mirror of the fail-loud change #3635 made to open_user_database.
- # Previously this swallowed the exception with "tables exist but
- # schema version not stamped — migrations will be retried on next
- # process restart". That left a half-broken DB on disk: tables
- # present, no alembic_version row. The next login then re-ran
- # alembic, hit the same error, and (post-#3635) 503'd — so the
- # user could register but never log in again. Better to fail
- # registration loudly with the partial DB removed, so the real
- # cause (e.g. world-writable migrations dir) gets fixed instead
- # of producing a permanently-locked-out account.
- try:
- Session = sessionmaker(bind=engine)
- with Session() as session:
- initialize_database(engine, session)
- except Exception as e:
- # ``password`` is in scope and was passed into the engine
- # creator closure above. Drop the traceback to avoid leaking
- # frame locals under ``diagnose=True`` and redact the
- # password from str(e) defensively.
- from ..security.log_sanitizer import redact_secrets
-
- safe_msg = redact_secrets(str(e), password)
- logger.warning(
- f"Database migration failed for {username} during creation"
- f" — removing partial DB: {safe_msg}"
- )
- engine.dispose()
- # Remove the partial DB *and* its salt/WAL/journal sidecars so a
- # retry of the same username isn't blocked by a leftover salt.
- _remove_partial_user_db_files(db_path)
- raise
-
- # Restrict DB file to owner-only (0o600). The encrypted branch
- # chmod's right after create_sqlcipher_connection, but the
- # unencrypted fallback creates the file lazily on first connect
- # (during initialize_database above), so it is only guaranteed to
- # exist here. This file holds PLAINTEXT user data — leaving it at
- # umask-default perms (commonly 0o644) would expose it to other
- # local accounts.
- if not self.has_encryption and db_path.exists():
- _best_effort_chmod(db_path, 0o600, warn=True)
-
- # Store connection AFTER migrations complete. This password just proved
- # itself by creating the database; publish the engine and its verifier
- # together so the cache is never briefly trusted without one.
- self._cache_connection(username, engine, password)
-
- logger.info(f"Created encrypted database for user {username}")
- return engine
+ return db_path, engine
def _compute_verifier_digest(self, salt: bytes, password: str) -> bytes:
"""Keyed digest binding ``password`` to a per-entry ``salt``.
diff --git a/tests/database/test_create_user_database_serialized.py b/tests/database/test_create_user_database_serialized.py
new file mode 100644
index 0000000000..8960f10864
--- /dev/null
+++ b/tests/database/test_create_user_database_serialized.py
@@ -0,0 +1,100 @@
+"""``create_user_database`` must be serialized per user by the init lock.
+
+Only ``open_user_database`` took ``_get_init_lock``. Two concurrent creates
+for the same username could both pass the ``db_path.exists()`` guard; the
+loser's orphaned-salt recovery then unlinked the winner's in-flight
+``.db``/``.salt`` and both registrations failed (#6355). The exists-check,
+salt and file creation, the migrations and the cache publish now all run
+under the lock, exactly like the cold-open path.
+"""
+
+import threading
+
+import pytest
+
+from local_deep_research.database import encrypted_db
+from local_deep_research.database.encrypted_db import DatabaseManager
+
+PASSWORD = "CorrectHorse1!"
+
+
+def manager(tmp_path, monkeypatch):
+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))
+ mgr = DatabaseManager()
+ mgr.data_dir = tmp_path
+ if not mgr.has_encryption:
+ pytest.skip("SQLCipher not available; the salt path is encrypted-only")
+ yield mgr
+ mgr.close_all_databases()
+
+
+def test_file_creation_runs_under_the_init_lock(manager, monkeypatch):
+ username = "locked_create_user"
+ lock = manager._get_init_lock(username)
+ real_create_salt = encrypted_db.create_database_salt
+ seen = []
+
+ def observed_create_salt(db_path):
+ seen.append(lock.locked())
+ return real_create_salt(db_path)
+
+ monkeypatch.setattr(
+ encrypted_db, "create_database_salt", observed_create_salt
+ )
+
+ manager.create_user_database(username, PASSWORD)
+
+ assert seen == [True]
+ assert not lock.locked()
+
+
+def test_migrations_run_under_the_init_lock(manager, monkeypatch):
+ from local_deep_research.database import initialize
+
+ username = "migrated_user"
+ lock = manager._get_init_lock(username)
+ real_initialize = initialize.initialize_database
+ seen = []
+
+ def observed_initialize(engine, session):
+ seen.append(lock.locked())
+ return real_initialize(engine, session)
+
+ monkeypatch.setattr(initialize, "initialize_database", observed_initialize)
+
+ manager.create_user_database(username, PASSWORD)
+
+ assert seen == [True]
+ assert not lock.locked()
+
+
+def test_concurrent_creates_for_one_user_leave_a_usable_database(manager):
+ username = "raced_user"
+ barrier = threading.Barrier(2)
+ outcomes: list = []
+
+ def create():
+ barrier.wait()
+ try:
+ outcomes.append(
+ ("ok", manager.create_user_database(username, PASSWORD))
+ )
+ except ValueError as exc:
+ outcomes.append(("error", str(exc)))
+
+ threads = [threading.Thread(target=create) for _ in range(2)]
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join(timeout=60)
+
+ kinds = sorted(kind for kind, _ in outcomes)
+ assert kinds == ["error", "ok"], outcomes
+ error_message = next(msg for kind, msg in outcomes if kind == "error")
+ assert "already exists" in error_message
+
+ db_path = manager._get_user_db_path(username)
+ assert db_path.exists()
+ manager.close_all_databases()
+ assert manager.open_user_database(username, PASSWORD) is not None
diff --git a/tests/database/test_migration_chain_integrity.py b/tests/database/test_migration_chain_integrity.py
index 12b12b7b35..a3cc0993e2 100644
--- a/tests/database/test_migration_chain_integrity.py
+++ b/tests/database/test_migration_chain_integrity.py
@@ -196,7 +196,9 @@ KNOWN_CONNECTION_SITES = {
"database/encrypted_db.py::DatabaseManager._make_sqlcipher_connection": (
"user-db"
),
- "database/encrypted_db.py::DatabaseManager.create_user_database": "user-db",
+ "database/encrypted_db.py::DatabaseManager._create_user_database_files": (
+ "user-db"
+ ),
"database/encrypted_db.py::DatabaseManager._open_user_database_cold": (
"user-db"
),
@@ -1292,7 +1294,7 @@ def test_every_user_database_connection_path_reaches_the_pragma_helper():
def test_both_branches_of_each_user_database_engine_configure_connections():
"""The unencrypted fallback is a second path, not a footnote.
- ``create_user_database`` and ``_open_user_database_cold`` each build
+ ``_create_user_database_files`` and ``_open_user_database_cold`` each build
an Engine twice: once with a SQLCipher ``creator=`` and once, when
SQLCipher is unavailable, over a plain ``sqlite:///`` URL. Reaching
the pragma helper *somewhere* in the function would be satisfied by
@@ -1331,7 +1333,7 @@ def test_both_branches_of_each_user_database_engine_configure_connections():
assert checked >= 4, (
f"only {checked} create_engine call(s) inspected on user-database "
"paths -- expected the encrypted and unencrypted branches of both "
- "create_user_database and _open_user_database_cold"
+ "_create_user_database_files and _open_user_database_cold"
)
assert unconfigured == [], (
"create_engine call(s) on a user-database path with neither a "
diff --git a/tests/security/test_db_connection_get_session_no_open.py b/tests/security/test_db_connection_get_session_no_open.py
index 1ec7beb2a8..d334e824f0 100644
--- a/tests/security/test_db_connection_get_session_no_open.py
+++ b/tests/security/test_db_connection_get_session_no_open.py
@@ -87,6 +87,10 @@ def test_get_session_none_when_db_file_exists_but_connection_closed(manager):
This is the "browser closed but DB idle" resting state from the
incident. A lazy-open regression here would revive the engine with no
credential, making the username alone sufficient again.
+
+ ``create_user_database`` takes the per-user init lock (#6377), so the
+ registry may already hold this user's entry after setup; the invariant
+ is that ``get_session`` does not add or take one.
"""
username = f"closed_db_{uuid.uuid4().hex[:8]}"
password = "CorrectHorseBattery1!" # noqa: S105
@@ -106,6 +110,7 @@ def test_get_session_none_when_db_file_exists_but_connection_closed(manager):
db_path = manager._get_user_db_path(username)
assert db_path.exists(), "setup: the closed DB file must still exist"
before = _dir_fingerprint(manager.data_dir)
+ locks_before = dict(manager._init_locks)
# Repeated asks: no revival on the first call, the second, or the tenth.
for _ in range(10):
@@ -119,9 +124,12 @@ def test_get_session_none_when_db_file_exists_but_connection_closed(manager):
# the on-disk artifacts byte-identical (no checkpoint/write/chmod).
assert username not in manager.connections
assert username not in manager._password_verifiers
- assert manager._init_locks.get(username) is None, (
- "get_session must not even run the open-path machinery (init lock)"
+ assert manager._init_locks == locks_before, (
+ "get_session must not even run the open-path machinery (init lock): "
+ "the registry changed"
)
+ lock = manager._init_locks.get(username)
+ assert lock is None or not lock.locked()
assert _dir_fingerprint(manager.data_dir) == before, (
"get_session modified on-disk artifacts for a closed user"
)
@@ -214,12 +222,17 @@ def test_get_session_repeated_calls_are_pure_noop(manager):
Guards against a "harmless-looking" regression where a miss spawns a
throwaway engine, session, or lock per call (FD/resource leak that also
widens the attack surface the incident exploited).
+
+ ``create_user_database`` takes the per-user init lock (#6377), so the
+ registry may already hold this user's entry after setup; the invariant
+ is that ``get_session`` does not add or take one.
"""
username = f"noop_hammer_{uuid.uuid4().hex[:8]}"
password = "NoOpPassword3!" # noqa: S105
manager.create_user_database(username, password)
manager.close_user_database(username)
before = _dir_fingerprint(manager.data_dir)
+ locks_before = dict(manager._init_locks)
for _ in range(50):
assert manager.get_session(username) is None
@@ -229,5 +242,10 @@ def test_get_session_repeated_calls_are_pure_noop(manager):
)
assert manager.connections == {}
assert manager._password_verifiers == {}
- assert manager._init_locks == {}
+ assert manager._init_locks == locks_before, (
+ "get_session must not even run the open-path machinery (init lock): "
+ "the registry changed"
+ )
+ lock = manager._init_locks.get(username)
+ assert lock is None or not lock.locked()
assert manager.get_connected_usernames() == set()