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(encrypted-db): fail loud when create_user_database hits migration error (#3663)

LearningCircuit7af8ec5436ae
diff --git a/src/local_deep_research/database/encrypted_db.py b/src/local_deep_research/database/encrypted_db.py
index b40c696702..a8d29d1604 100644
--- a/src/local_deep_research/database/encrypted_db.py
+++ b/src/local_deep_research/database/encrypted_db.py
@@ -474,17 +474,29 @@ class DatabaseManager:
# 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:
- # Create a session for settings initialization
Session = sessionmaker(bind=engine)
with Session() as session:
initialize_database(engine, session)
except Exception:
logger.exception(
- "Database migration failed during creation — "
- "tables exist but schema version not stamped. "
- "Migrations will be retried on next process restart."
+ f"Database migration failed for {username} during creation"
+ " — removing partial DB"
)
+ engine.dispose()
+ if db_path.exists():
+ db_path.unlink(missing_ok=True)
+ raise
# Store connection AFTER migrations complete
with self._connections_lock:
diff --git a/tests/database/test_encrypted_db_manager.py b/tests/database/test_encrypted_db_manager.py
index 0a5e741d0d..3319bea32b 100644
--- a/tests/database/test_encrypted_db_manager.py
+++ b/tests/database/test_encrypted_db_manager.py
@@ -119,6 +119,72 @@ class TestDatabaseCreation:
with pytest.raises(ValueError, match="already exists"):
manager.create_user_database("existinguser", "password")
+ @patch("local_deep_research.database.encrypted_db.get_data_directory")
+ def test_create_database_migration_failure_raises_and_cleans_up(
+ self, mock_data_dir, tmp_path
+ ):
+ """A failure inside ``initialize_database`` must propagate, not swallow.
+
+ Regression: the create path used to log the migration exception and
+ return the engine anyway, leaving a partial DB on disk (tables but
+ no alembic_version stamp). Every subsequent login then re-ran
+ alembic, hit the same error, and (post-#3635) 503'd — the user
+ could register but never log in. Now the failure surfaces, the
+ engine is disposed, the partial DB file is removed, and nothing
+ is cached in ``connections``.
+ """
+ from local_deep_research.database.encrypted_db import DatabaseManager
+
+ mock_data_dir.return_value = tmp_path
+
+ db_file = tmp_path / "encrypted_databases" / "newuser.db"
+ db_file.parent.mkdir(parents=True, exist_ok=True)
+
+ with patch.object(
+ DatabaseManager, "_check_encryption_available", return_value=False
+ ):
+ with patch.dict("os.environ", {"LDR_ALLOW_UNENCRYPTED": "true"}):
+ manager = DatabaseManager()
+
+ with patch.object(
+ manager, "_get_user_db_path", return_value=db_file
+ ):
+ # Simulate the encrypted-path structure-creation step
+ # having materialised the file before migrations run,
+ # so the cleanup branch has something to remove.
+ created_engines = []
+
+ def fake_engine(*args, **kwargs):
+ db_file.touch()
+ engine = MagicMock()
+ created_engines.append(engine)
+ return engine
+
+ with patch(
+ "local_deep_research.database.encrypted_db.create_engine",
+ side_effect=fake_engine,
+ ):
+ with patch(
+ "local_deep_research.database.encrypted_db.event"
+ ):
+ with patch(
+ "local_deep_research.database.initialize.initialize_database",
+ side_effect=ValueError(
+ "Migrations directory has insecure permissions (world-writable)"
+ ),
+ ):
+ with pytest.raises(
+ ValueError, match="world-writable"
+ ):
+ manager.create_user_database(
+ "newuser", "password"
+ )
+
+ assert "newuser" not in manager.connections
+ assert len(created_engines) == 1
+ created_engines[0].dispose.assert_called_once()
+ assert not db_file.exists()
+
class TestDatabaseOpening:
"""Tests for open_user_database functionality."""