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(auth): clean up orphaned auth row + partial DB/salt files on registration failure (#4934)

LearningCircuit4c561f5c2a9d
diff --git a/changelog.d/4934.bugfix.md b/changelog.d/4934.bugfix.md
new file mode 100644
index 0000000000..d6f28428e2
--- /dev/null
+++ b/changelog.d/4934.bugfix.md
@@ -0,0 +1 @@
+Registration no longer leaves a bricked account behind: if creating the encrypted user database fails after the auth row is committed, both the orphaned auth row and any partial on-disk database files (including the per-database salt) are now cleaned up, so the username is genuinely reusable on retry.
diff --git a/changelog.d/4942.bugfix.md b/changelog.d/4942.bugfix.md
new file mode 100644
index 0000000000..9f8aa60b10
--- /dev/null
+++ b/changelog.d/4942.bugfix.md
@@ -0,0 +1 @@
+Registration now recovers from an orphaned per-database salt file (left with no matching database by a prior interrupted registration), so a username that was previously stuck as un-registerable can be registered again.
diff --git a/src/local_deep_research/database/encrypted_db.py b/src/local_deep_research/database/encrypted_db.py
index 4223bb9704..f1fc792442 100644
--- a/src/local_deep_research/database/encrypted_db.py
+++ b/src/local_deep_research/database/encrypted_db.py
@@ -44,6 +44,7 @@ from .sqlcipher_utils import (
apply_performance_pragmas,
verify_sqlcipher_connection,
create_database_salt,
+ get_salt_file_path,
has_per_database_salt,
get_key_from_password,
get_sqlcipher_version,
@@ -87,6 +88,53 @@ def _best_effort_chmod(path, mode: int, *, warn: bool = False) -> None:
)
+def _remove_partial_user_db_files(db_path: Path) -> None:
+ """Remove a half-created user database and all of its sidecar files.
+
+ Called from ``create_user_database``'s failure paths. The encrypted
+ branch writes a per-database ``.salt`` file (via ``create_database_salt``)
+ *before* the DB itself, and SQLCipher/WAL leaves ``-wal``/``-shm``
+ sidecars. Removing only the ``.db`` — as these cleanup paths used to —
+ orphans the ``.salt``: a retry then hits ``create_database_salt``'s
+ ``FileExistsError`` (it refuses to overwrite to prevent data loss), so the
+ username stays permanently un-registerable even after the orphaned auth
+ row is cleaned up. Delete every artifact so the on-disk state is atomic
+ and the username is reusable on a subsequent retry.
+
+ ``create_user_database`` calls this from four sites: its three
+ failure-cleanup blocks (structure creation, engine build, migration — a
+ graceful error mid-creation) and its salt-creation recovery path (an
+ orphan left by a prior hard-killed create or by pre-#4934 cleanup that
+ removed only the ``.db``). In every case the ``db_path.exists()`` guard at
+ the top of ``create_user_database`` already ran and found no *pre-existing*
+ database, so any ``.db``/``.salt`` present now is this call's own partial
+ work — removing it cannot destroy live data, because a valid encrypted DB
+ always has both the ``.db`` and its ``.salt``.
+
+ Both the ``-wal``/``-shm`` (WAL mode, the default) and ``-journal``
+ (rollback-journal modes: DELETE/TRUNCATE/PERSIST) sidecars are removed so
+ the cleanup is correct regardless of the configured ``journal_mode``.
+
+ Never raises — cleanup must not mask the original creation error.
+ """
+ db_path = Path(db_path)
+ for path in (
+ db_path,
+ get_salt_file_path(db_path),
+ db_path.with_name(db_path.name + "-wal"),
+ db_path.with_name(db_path.name + "-shm"),
+ db_path.with_name(db_path.name + "-journal"),
+ ):
+ try:
+ path.unlink(missing_ok=True)
+ except OSError:
+ # Best-effort: a leftover artifact is worth surfacing but must not
+ # mask the original creation error. The path is enough to
+ # diagnose; skip the exception detail per the sensitive-logging
+ # policy.
+ logger.warning(f"Could not remove partial user DB artifact {path}")
+
+
class DatabaseManager:
"""Manages encrypted SQLCipher databases for each user."""
@@ -418,15 +466,52 @@ class DatabaseManager:
# Create directory if it doesn't exist
db_path.parent.mkdir(parents=True, exist_ok=True)
- # Create per-database salt for new databases (v2 security improvement)
- create_database_salt(db_path)
+ # Create per-database salt for new databases (v2 security improvement).
+ #
+ # A pre-existing salt here is an ORPHAN, not live data: the
+ # ``db_path.exists()`` guard above already established that no
+ # database file exists, and a valid encrypted DB always has BOTH
+ # the ``.db`` and its ``.salt``. Such an orphan is left by a create
+ # that died before completing — a hard process death (SIGKILL/OOM/
+ # power loss) mid-creation, or the pre-#4934 cleanup code that
+ # removed only the ``.db``. Without recovery, ``create_database_salt``
+ # raises ``FileExistsError`` (it refuses to overwrite to protect
+ # live data) on every retry, so the username stays permanently
+ # un-registerable. Remove the stale artifacts and create fresh —
+ # safe precisely because no database depends on this salt.
+ #
+ # Note: backups are keyed off the *source* DB's salt (they store no
+ # salt copy — see backup_service), so deleting a salt also strands
+ # any backups for it. That is not reachable here: this only fires
+ # when db_path is absent, and the app never removes a live .db while
+ # keeping its .salt (there is no in-app restore). Only out-of-band
+ # manual deletion of the .db could turn this into backup loss.
+ #
+ # SAFETY INVARIANT: this deletion is safe only while a salt-without-
+ # a-.db always means garbage. That holds today because create_user_
+ # database is the sole salt writer/caller and nothing restores or
+ # imports a .db from a salt. If an in-app restore/import that stages
+ # a .salt ahead of its .db is ever added, RE-EVALUATE this branch —
+ # it could delete a salt whose database is legitimately incoming.
+ try:
+ create_database_salt(db_path)
+ except FileExistsError:
+ logger.warning(
+ f"Removing orphaned salt (no matching database) for "
+ f"{username} before creating a fresh one"
+ )
+ _remove_partial_user_db_files(db_path)
+ create_database_salt(db_path)
logger.info(f"Created per-database salt for {username}")
- # Pre-derive key before closures to avoid capturing plaintext password
- hex_key = get_key_from_password(password, db_path=db_path).hex()
-
# Create database structure using raw SQLCipher outside SQLAlchemy
try:
+ # Pre-derive key before closures to avoid capturing plaintext
+ # password. Kept inside the try so a derivation failure here
+ # also triggers the partial-file cleanup below, rather than
+ # orphaning the just-created salt file.
+ hex_key = get_key_from_password(password, db_path=db_path).hex()
+
conn = create_sqlcipher_connection(
db_path,
password=password,
@@ -499,9 +584,9 @@ class DatabaseManager:
safe_msg = redact_secrets(str(e), password)
logger.warning(f"Error creating database structure: {safe_msg}")
- # Cleanup partial DB file on failure
- if db_path.exists():
- db_path.unlink(missing_ok=True)
+ # 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
# Small delay to ensure file is fully written
@@ -531,15 +616,27 @@ class DatabaseManager:
},
)
- # Create engine with custom creator function and optimized cache
- engine = create_engine(
- "sqlite://",
- creator=create_engine_connection,
- poolclass=self._pool_class,
- echo=False,
- query_cache_size=1000,
- **self._get_pool_kwargs(),
- )
+ # Create engine with custom creator function and optimized cache.
+ # The .db and .salt already exist on disk (structure creation
+ # succeeded above). This step sits between the structure-creation
+ # and migration cleanup blocks; without its own cleanup a failure
+ # here would orphan those files, and unlike every other failure
+ # path it would NOT be self-healing — the retry trips the
+ # db_path.exists() guard and bricks the username. So clean up on
+ # any escape. (create_engine is lazy so this is near-unreachable,
+ # but it closes the one gap in the otherwise-uniform coverage.)
+ try:
+ engine = create_engine(
+ "sqlite://",
+ creator=create_engine_connection,
+ poolclass=self._pool_class,
+ echo=False,
+ query_cache_size=1000,
+ **self._get_pool_kwargs(),
+ )
+ except Exception:
+ _remove_partial_user_db_files(db_path)
+ raise
else:
logger.warning(
f"SQLCipher not available - creating UNENCRYPTED database for user {username}"
@@ -590,8 +687,9 @@ class DatabaseManager:
f" — removing partial DB: {safe_msg}"
)
engine.dispose()
- if db_path.exists():
- db_path.unlink(missing_ok=True)
+ # 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
diff --git a/src/local_deep_research/web/auth/routes.py b/src/local_deep_research/web/auth/routes.py
index d8cfaaceb1..6bf862b0e2 100644
--- a/src/local_deep_research/web/auth/routes.py
+++ b/src/local_deep_research/web/auth/routes.py
@@ -544,6 +544,14 @@ def register():
try:
new_user = User(username=username)
auth_db.add(new_user)
+ auth_db.flush()
+ # Capture the PK after flush (the INSERT has run and assigned the
+ # id) but before commit: reading it here needs no post-commit
+ # refresh SELECT (expire_on_commit), and if the commit below fails
+ # nothing is persisted, so there is no orphan to clean up. Cleanup
+ # deletes by this id rather than re-querying by username, which
+ # could race a concurrent registration reusing the same username.
+ new_user_id = new_user.id
auth_db.commit()
except IntegrityError:
# Catch duplicate username specifically (race condition case)
@@ -560,7 +568,10 @@ def register():
password_requirements=PasswordValidator.get_requirements(),
), 400
except Exception:
- logger.exception(f"Registration failed for {username}")
+ logger.exception(
+ f"Registration failed for {username} while creating the "
+ f"auth record"
+ )
auth_db.rollback()
flash("Registration failed. Please try again.", "error")
return render_template(
@@ -569,10 +580,50 @@ def register():
password_requirements=PasswordValidator.get_requirements(),
), 500
+ # Create encrypted database for user.
+ #
+ # This is the only step that can leave an orphaned auth row: the User
+ # row is already committed, but no encrypted DB exists yet, so the
+ # username is taken (blocking re-registration via user_exists()) while
+ # login also fails (no DB to open) — a permanently bricked account.
+ # The cleanup scope is intentionally narrow: later failures (session
+ # setup, library init) must NOT delete the auth row, because by then
+ # the user DB exists and the account is legitimate.
try:
- # Create encrypted database for user
db_manager.create_user_database(username, password)
+ except Exception:
+ logger.exception(
+ f"Registration failed for {username} while creating the "
+ f"encrypted database"
+ )
+ # Delete the orphaned auth row by primary key in a fresh session
+ # (the original auth_db session has already closed). Deleting by ID
+ # avoids racing a concurrent registration that re-uses the username.
+ try:
+ with auth_db_session() as cleanup_db:
+ orphaned_user = (
+ cleanup_db.query(User).filter_by(id=new_user_id).first()
+ )
+ if orphaned_user is not None:
+ cleanup_db.delete(orphaned_user)
+ cleanup_db.commit()
+ logger.info(
+ f"Cleaned up orphaned auth entry for {username}"
+ )
+ except Exception:
+ # Surface a stuck orphan so it's diagnosable, but don't mask the
+ # original registration failure returned to the user.
+ logger.exception(
+ f"Failed to clean up orphaned auth entry for {username}"
+ )
+ flash("Registration failed. Please try again.", "error")
+ return render_template(
+ "auth/register.html",
+ has_encryption=db_manager.has_encryption,
+ password_requirements=PasswordValidator.get_requirements(),
+ ), 500
+ try:
# Auto-login after registration (remember=False: fresh
# registrations should not persist as "remember me" sessions).
_create_user_session(session, username, password, remember=False)
@@ -616,7 +667,13 @@ def register():
return redirect(url_for("index"))
except Exception:
- logger.exception(f"Registration failed for {username}")
+ # The encrypted DB already exists at this point, so this failure is in
+ # post-creation setup (auto-login / session). The account is created
+ # and loginable; do NOT clean up the auth row here (narrow scope).
+ logger.exception(
+ f"Registration failed for {username} after database creation "
+ f"(post-creation session/login setup)"
+ )
flash("Registration failed. Please try again.", "error")
return render_template(
"auth/register.html",
diff --git a/tests/auth_tests/test_auth_routes.py b/tests/auth_tests/test_auth_routes.py
index 2a42d67839..f20b9f9111 100644
--- a/tests/auth_tests/test_auth_routes.py
+++ b/tests/auth_tests/test_auth_routes.py
@@ -249,6 +249,317 @@ class TestAuthRoutes:
in response.data
)
+ def test_orphaned_auth_row_cleaned_up_on_db_creation_failure(
+ self, client, monkeypatch
+ ):
+ """Registration must not leave a bricked account behind.
+
+ If ``create_user_database()`` fails after the auth-DB ``User`` row
+ has been committed, that orphaned row must be deleted. Otherwise the
+ username stays taken (``user_exists()`` blocks re-registration) while
+ login also fails (no encrypted DB to open) — a permanently unusable
+ account. Regression test for PR #3142.
+ """
+ username = "testuser_orphan"
+ row_existed_at_failure = {}
+
+ def _fail_create(uname, password):
+ # The auth row is committed before create_user_database() runs.
+ # Record its presence here so the test proves the row was
+ # created-then-cleaned, not merely never created.
+ check_db = get_auth_db_session()
+ row_existed_at_failure["value"] = (
+ check_db.query(User).filter_by(username=uname).first()
+ is not None
+ )
+ check_db.close()
+ raise RuntimeError("simulated encrypted DB creation failure")
+
+ monkeypatch.setattr(db_manager, "create_user_database", _fail_create)
+
+ response = client.post(
+ "/auth/register",
+ data={
+ "username": username,
+ "password": "TestPass123",
+ "confirm_password": "TestPass123",
+ "acknowledge": "true",
+ },
+ )
+
+ # Registration reports failure to the user...
+ assert response.status_code == 500
+ assert b"Registration failed" in response.data
+ # ...but only after the auth row was actually committed...
+ assert row_existed_at_failure.get("value") is True
+
+ # ...and the orphaned row must have been cleaned up, freeing the
+ # username so the user can retry registration.
+ auth_db = get_auth_db_session()
+ orphan = auth_db.query(User).filter_by(username=username).first()
+ auth_db.close()
+ assert orphan is None
+
+ def test_partial_db_creation_failure_leaves_username_reusable(
+ self, client, monkeypatch
+ ):
+ """A real mid-flight ``create_user_database()`` failure must leave no
+ on-disk residue that blocks re-registration.
+
+ ``create_user_database()`` writes a per-database ``.salt`` file before
+ the DB itself. If a later step fails and only the ``.db`` is removed,
+ the orphaned salt makes ``create_database_salt()`` raise
+ ``FileExistsError`` on every retry — so the username stays permanently
+ un-registerable even after the auth row is cleaned up. This drives a
+ genuine failure *after* the salt is written (by making the first
+ SQLCipher connection raise) and asserts the username can be registered
+ afterwards. Complements the stubbed auth-row test above by exercising
+ the real filesystem cleanup end-to-end.
+ """
+ if not db_manager.has_encryption:
+ pytest.skip(
+ "Salt files only exist on the encrypted (SQLCipher) path"
+ )
+
+ import local_deep_research.database.encrypted_db as encrypted_db
+ from local_deep_research.database.sqlcipher_utils import (
+ get_salt_file_path,
+ )
+
+ username = "testuser_partial"
+ real_create_conn = encrypted_db.create_sqlcipher_connection
+ calls = {"n": 0}
+
+ def _flaky_conn(*args, **kwargs):
+ calls["n"] += 1
+ if calls["n"] == 1:
+ # Fail the first creation attempt, AFTER the real salt file has
+ # already been written by create_database_salt().
+ raise RuntimeError("simulated SQLCipher failure")
+ return real_create_conn(*args, **kwargs)
+
+ monkeypatch.setattr(
+ encrypted_db, "create_sqlcipher_connection", _flaky_conn
+ )
+
+ register_data = {
+ "username": username,
+ "password": "TestPass123",
+ "confirm_password": "TestPass123",
+ "acknowledge": "true",
+ }
+
+ # First attempt fails mid-creation.
+ first = client.post("/auth/register", data=register_data)
+ assert first.status_code == 500
+ # The injected failure actually fired (not some unrelated 500).
+ assert calls["n"] >= 1
+
+ # The salt file (and DB) must have been cleaned up, not orphaned —
+ # otherwise the retry below would trip create_database_salt()'s
+ # FileExistsError.
+ salt_path = get_salt_file_path(db_manager._get_user_db_path(username))
+ assert not salt_path.exists()
+
+ # The username must now be genuinely reusable: a retry (which no longer
+ # trips the injected failure) succeeds end-to-end and actually creates
+ # the encrypted DB file (user_exists() only checks the auth DB).
+ second = client.post(
+ "/auth/register", data=register_data, follow_redirects=True
+ )
+ assert second.status_code == 200
+ assert db_manager.user_exists(username)
+ assert db_manager._get_user_db_path(username).exists()
+
+ def test_migration_failure_leaves_username_reusable(
+ self, client, monkeypatch
+ ):
+ """The *migration-path* cleanup site must also leave no on-disk residue.
+
+ ``create_user_database()`` has two failure-cleanup sites: the SQLCipher
+ structure-creation step (exercised by the test above) and the alembic
+ migration step (``initialize_database``). The migration failure — e.g.
+ a world-writable migrations dir — is the historically realistic one
+ (see the "no such table: papers" / #3635 lineage). This drives a failure
+ there, *after* the real ``.db`` and salt have been written, and asserts
+ both are removed and the username is reusable — guarding the second
+ cleanup call site, which the SQLCipher-path test cannot reach.
+ """
+ if not db_manager.has_encryption:
+ pytest.skip(
+ "Salt files only exist on the encrypted (SQLCipher) path"
+ )
+
+ import local_deep_research.database.initialize as initialize_mod
+ from local_deep_research.database.sqlcipher_utils import (
+ get_salt_file_path,
+ )
+
+ username = "testuser_migfail"
+ real_initialize = initialize_mod.initialize_database
+ calls = {"n": 0}
+
+ def _flaky_initialize(*args, **kwargs):
+ calls["n"] += 1
+ if calls["n"] == 1:
+ # Fail the first attempt at the migration step, AFTER the real
+ # .db + salt were created by the SQLCipher structure step.
+ raise RuntimeError("simulated migration failure")
+ return real_initialize(*args, **kwargs)
+
+ monkeypatch.setattr(
+ initialize_mod, "initialize_database", _flaky_initialize
+ )
+
+ register_data = {
+ "username": username,
+ "password": "TestPass123",
+ "confirm_password": "TestPass123",
+ "acknowledge": "true",
+ }
+ db_path = db_manager._get_user_db_path(username)
+
+ # First attempt fails at the migration step — after .db + salt exist.
+ first = client.post("/auth/register", data=register_data)
+ assert first.status_code == 500
+ assert calls["n"] >= 1 # the injected migration failure actually fired
+
+ # The migration-path cleanup must remove BOTH the .db and its salt
+ # (the pre-fix code unlinked only the .db).
+ assert not db_path.exists()
+ assert not get_salt_file_path(db_path).exists()
+
+ # The username is reusable: the retry (no longer failing) succeeds.
+ second = client.post(
+ "/auth/register", data=register_data, follow_redirects=True
+ )
+ assert second.status_code == 200
+ assert db_manager.user_exists(username)
+ assert db_path.exists()
+
+ def test_registration_recovers_from_orphaned_salt(self, client):
+ """A pre-existing salt with no matching database must not permanently
+ block registration.
+
+ A create that dies before completing — a hard process kill mid-creation,
+ or the pre-#4934 cleanup that removed only the ``.db`` — can leave a
+ ``.salt`` file with no ``.db``. ``create_database_salt()`` refuses to
+ overwrite it (``FileExistsError``), so without recovery the username is
+ permanently un-registerable. This simulates that orphan and asserts
+ registration heals it (removes the stale salt, creates fresh) and
+ succeeds. Fails without the salt-creation recovery (the first
+ registration 500s on the FileExistsError).
+
+ The 200 alone proves the DB was created and opens with the *fresh*
+ salt: create_user_database() runs initialize_database() against the
+ newly-keyed DB, which 500s if the salt/key are inconsistent. We also
+ assert the on-disk salt bytes changed, to prove regenerate-not-reuse.
+ """
+ if not db_manager.has_encryption:
+ pytest.skip(
+ "Salt files only exist on the encrypted (SQLCipher) path"
+ )
+
+ from local_deep_research.database.sqlcipher_utils import (
+ create_database_salt,
+ get_salt_file_path,
+ )
+
+ username = "testuser_saltorphan"
+ db_path = db_manager._get_user_db_path(username)
+ db_path.parent.mkdir(parents=True, exist_ok=True)
+
+ # Simulate the orphan: a salt file with no matching database.
+ create_database_salt(db_path)
+ salt_path = get_salt_file_path(db_path)
+ assert salt_path.exists()
+ assert not db_path.exists()
+ planted_salt = salt_path.read_bytes()
+
+ # Registration must recover (remove the orphan, create fresh) and
+ # succeed end-to-end rather than 500 on the salt collision.
+ response = client.post(
+ "/auth/register",
+ data={
+ "username": username,
+ "password": "TestPass123",
+ "confirm_password": "TestPass123",
+ "acknowledge": "true",
+ },
+ follow_redirects=True,
+ )
+ assert response.status_code == 200
+ assert db_manager.user_exists(username)
+ assert db_path.exists()
+ # A freshly-generated salt now backs the real database — the recovery
+ # removed and recreated it, it did not reuse the planted orphan.
+ assert salt_path.exists()
+ assert salt_path.read_bytes() != planted_salt
+
+ def test_engine_build_failure_leaves_username_reusable(
+ self, client, monkeypatch
+ ):
+ """A failure building the SQLAlchemy engine — the step BETWEEN the
+ structure-creation and migration cleanup blocks — must still clean up
+ the already-created .db and salt.
+
+ Without cleanup at this step a failure here orphans the .db, and unlike
+ the salt path it is NOT self-healing: the retry trips
+ create_user_database's ``db_path.exists()`` guard and bricks the
+ username permanently. This injects an engine-build failure after the
+ structure step has written the .db + salt and asserts both are removed
+ and the username is reusable.
+ """
+ if not db_manager.has_encryption:
+ pytest.skip(
+ "Salt files only exist on the encrypted (SQLCipher) path"
+ )
+
+ import local_deep_research.database.encrypted_db as encrypted_db
+ from local_deep_research.database.sqlcipher_utils import (
+ get_salt_file_path,
+ )
+
+ username = "testuser_engfail"
+ real_create_engine = encrypted_db.create_engine
+ calls = {"n": 0}
+
+ def _flaky_create_engine(*args, **kwargs):
+ calls["n"] += 1
+ if calls["n"] == 1:
+ # Fail the first engine build, AFTER the structure step wrote
+ # the real .db + salt.
+ raise RuntimeError("simulated engine build failure")
+ return real_create_engine(*args, **kwargs)
+
+ monkeypatch.setattr(encrypted_db, "create_engine", _flaky_create_engine)
+
+ register_data = {
+ "username": username,
+ "password": "TestPass123",
+ "confirm_password": "TestPass123",
+ "acknowledge": "true",
+ }
+ db_path = db_manager._get_user_db_path(username)
+
+ first = client.post("/auth/register", data=register_data)
+ assert first.status_code == 500
+ # Exactly one create_engine call fired (the F1a engine build) and it
+ # raised — pins the failure to that site, not some earlier 500.
+ assert calls["n"] == 1
+
+ # Both the .db and its salt must have been removed, not orphaned.
+ assert not db_path.exists()
+ assert not get_salt_file_path(db_path).exists()
+
+ # The username is reusable: the retry (no longer failing) succeeds.
+ second = client.post(
+ "/auth/register", data=register_data, follow_redirects=True
+ )
+ assert second.status_code == 200
+ assert db_manager.user_exists(username)
+ assert db_path.exists()
+
def test_successful_login(self, client):
"""Test successful login."""
# Register user first
diff --git a/tests/database/test_encrypted_db_manager.py b/tests/database/test_encrypted_db_manager.py
index 3319bea32b..77edd90c6b 100644
--- a/tests/database/test_encrypted_db_manager.py
+++ b/tests/database/test_encrypted_db_manager.py
@@ -1499,3 +1499,50 @@ class TestTimingAttackPrevention:
# has_per_database_salt must NOT be called for non-existent db
mock_salt.assert_not_called()
+
+
+class TestRemovePartialUserDbFiles:
+ """Unit tests for _remove_partial_user_db_files (create-failure cleanup)."""
+
+ def test_removes_db_salt_and_all_sidecars(self, tmp_path):
+ """Every artifact a half-created DB can leave — the .db, its .salt,
+ and the -wal/-shm/-journal sidecars — must be removed, so a failed
+ create leaves nothing that blocks a retry.
+
+ Guards each unlink line independently of journal_mode: a typo in any
+ one of them leaves its file behind and fails this test (the
+ registration-flow tests only ever create/assert .db and .salt, so a
+ broken sidecar line ships silently without this).
+ """
+ from local_deep_research.database.encrypted_db import (
+ _remove_partial_user_db_files,
+ )
+ from local_deep_research.database.sqlcipher_utils import (
+ get_salt_file_path,
+ )
+
+ db_path = tmp_path / "ldr_user_deadbeef.db"
+ artifacts = [
+ db_path,
+ get_salt_file_path(db_path),
+ db_path.with_name(db_path.name + "-wal"),
+ db_path.with_name(db_path.name + "-shm"),
+ db_path.with_name(db_path.name + "-journal"),
+ ]
+ for path in artifacts:
+ path.write_bytes(b"x")
+ assert path.exists()
+
+ _remove_partial_user_db_files(db_path)
+
+ for path in artifacts:
+ assert not path.exists(), f"{path.name} was not removed"
+
+ def test_missing_files_are_a_noop_not_an_error(self, tmp_path):
+ """Never raises when artifacts are already absent (missing_ok)."""
+ from local_deep_research.database.encrypted_db import (
+ _remove_partial_user_db_files,
+ )
+
+ # No files created — must not raise.
+ _remove_partial_user_db_files(tmp_path / "ldr_user_absent.db")