~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: add checkfirst=True to auth DB init to prevent intermittent CI failures (#2146)
LearningCircuit1b6c11edf19b
diff --git a/.pre-commit-hooks/custom-checks.py b/.pre-commit-hooks/custom-checks.pyindex bb50ea3c5b..b0ef053b77 100755--- a/.pre-commit-hooks/custom-checks.py+++ b/.pre-commit-hooks/custom-checks.py@@ -267,6 +267,7 @@ def check_raw_sql(content: str, filename: str) -> List[Tuple[int, str]]:or "thread_local_session.py" in filenameor "encrypted_db.py" in filenameor "initialize.py" in filename+ or "auth_db.py" in filename)# Allow raw SQL in migrations, db utils, and all test filesdiff --git a/src/local_deep_research/database/auth_db.py b/src/local_deep_research/database/auth_db.pyindex 8b39667107..230dbc6ee6 100644--- a/src/local_deep_research/database/auth_db.py+++ b/src/local_deep_research/database/auth_db.py@@ -13,10 +13,10 @@ from sqlalchemy import create_enginefrom sqlalchemy.engine import Enginefrom sqlalchemy.orm import sessionmaker, Sessionfrom sqlalchemy.pool import QueuePool+from sqlalchemy.schema import CreateIndex, CreateTablefrom ..config.paths import get_data_directoryfrom .models.auth import User-from .models.base import Base# Global cached engine for auth database to prevent file descriptor leaks@@ -87,29 +87,33 @@ def _get_auth_engine() -> Engine:def init_auth_database():- """Initialize the authentication database if it doesn't exist."""+ """Initialize the authentication database if it doesn't exist.++ Uses SQL-level IF NOT EXISTS (via CreateTable/CreateIndex) so that+ concurrent calls are handled atomically by the database engine,+ eliminating the TOCTOU race in SQLAlchemy's checkfirst inspect.+ """auth_db_path = get_auth_db_path()# Ensure the data directory existsauth_db_path.parent.mkdir(parents=True, exist_ok=True)- # Check if database already exists- if auth_db_path.exists():- logger.debug(f"Auth database already exists at {auth_db_path}")- return-- logger.info(f"Creating auth database at {auth_db_path}")+ logger.debug(f"Ensuring auth database at {auth_db_path}")# Create the database with a temporary engineengine = create_engine(f"sqlite:///{auth_db_path}")- # Create tables- Base.metadata.create_all(engine, tables=[User.__table__])+ # Use SQL-level IF NOT EXISTS — idempotent and atomic, safe for+ # concurrent calls without Python-level locking.+ with engine.begin() as conn:+ conn.execute(CreateTable(User.__table__, if_not_exists=True))+ for index in User.__table__.indexes:+ conn.execute(CreateIndex(index, if_not_exists=True))# Dispose the temporary engineengine.dispose()- logger.info("Auth database initialized successfully")+ logger.debug("Auth database initialized successfully")def get_auth_db_session() -> Session:@@ -155,7 +159,3 @@ def dispose_auth_engine():_auth_engine = None_auth_engine_path = Nonelogger.debug("Disposed auth database engine")---# Initialize on import-init_auth_database()diff --git a/tests/database/test_auth_db.py b/tests/database/test_auth_db.pyindex 4c3f61d266..aad7510271 100644--- a/tests/database/test_auth_db.py+++ b/tests/database/test_auth_db.py@@ -67,17 +67,21 @@ class TestInitAuthDatabase:with patch("local_deep_research.database.auth_db.create_engine") as mock_engine:- mock_engine_instance = Mock()- mock_engine.return_value = mock_engine_instance+ mock_conn = Mock()+ mock_engine.return_value.begin.return_value.__enter__ = (+ Mock(return_value=mock_conn)+ )+ mock_engine.return_value.begin.return_value.__exit__ = Mock(+ return_value=False+ )- with patch("local_deep_research.database.auth_db.Base"):- init_auth_database()+ init_auth_database()# Directory should be createdassert db_path.parent.exists()- def test_skips_if_database_exists(self):- """init_auth_database skips creation if database already exists."""+ def test_idempotent_if_database_exists(self):+ """init_auth_database is idempotent when database already exists."""from local_deep_research.database.auth_db import init_auth_databasewith tempfile.TemporaryDirectory() as temp_dir:@@ -93,13 +97,22 @@ class TestInitAuthDatabase:with patch("local_deep_research.database.auth_db.create_engine") as mock_engine:+ mock_conn = Mock()+ mock_engine.return_value.begin.return_value.__enter__ = (+ Mock(return_value=mock_conn)+ )+ mock_engine.return_value.begin.return_value.__exit__ = Mock(+ return_value=False+ )++ # Should not raise even if DB already existsinit_auth_database()- # create_engine should not be called- mock_engine.assert_not_called()+ # create_engine is called (uses IF NOT EXISTS)+ mock_engine.assert_called_once()def test_creates_tables(self):- """init_auth_database creates User table."""+ """init_auth_database creates User table using CreateTable DDL."""from local_deep_research.database.auth_db import init_auth_databasewith tempfile.TemporaryDirectory() as temp_dir:@@ -113,21 +126,18 @@ class TestInitAuthDatabase:with patch("local_deep_research.database.auth_db.create_engine") as mock_engine:- mock_engine_instance = Mock()- mock_engine.return_value = mock_engine_instance+ mock_conn = Mock()+ mock_engine.return_value.begin.return_value.__enter__ = (+ Mock(return_value=mock_conn)+ )+ mock_engine.return_value.begin.return_value.__exit__ = Mock(+ return_value=False+ )- with patch(- "local_deep_research.database.auth_db.Base"- ) as mock_base:- with patch(- "local_deep_research.database.auth_db.User"- ) as mock_user:- mock_user.__table__ = Mock()-- init_auth_database()+ init_auth_database()- # Should call create_all with User table- mock_base.metadata.create_all.assert_called_once()+ # Should execute DDL via conn.execute+ assert mock_conn.execute.calledclass TestGetAuthDbSession: