~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: cache auth database engine to prevent file descriptor leak
LearningCircuit2aab0628d1f7
diff --git a/src/local_deep_research/database/auth_db.py b/src/local_deep_research/database/auth_db.pyindex 0f0eb623ed..0657fc68ce 100644--- a/src/local_deep_research/database/auth_db.py+++ b/src/local_deep_research/database/auth_db.py@@ -3,22 +3,69 @@ Authentication database initialization and management.This manages the central ldr_auth.db which only stores usernames."""+import threading+from contextlib import contextmanagerfrom pathlib import Path+from typing import Optionalfrom loguru import loggerfrom sqlalchemy import create_engine-from sqlalchemy.orm import sessionmaker+from sqlalchemy.engine import Engine+from sqlalchemy.orm import sessionmaker, Session+from sqlalchemy.pool import QueuePoolfrom ..config.paths import get_data_directoryfrom .models.auth import Userfrom .models.base import Base+# Global cached engine for auth database to prevent file descriptor leaks+_auth_engine: Optional[Engine] = None+_auth_engine_lock = threading.Lock()++def get_auth_db_path() -> Path:"""Get the path to the authentication database."""return get_data_directory() / "ldr_auth.db"+def _get_auth_engine() -> Engine:+ """+ Get or create a cached engine for the auth database.++ This prevents file descriptor leaks by reusing a single engine+ instead of creating a new one for every session.+ """+ global _auth_engine++ if _auth_engine is not None:+ return _auth_engine++ with _auth_engine_lock:+ # Double-check after acquiring lock+ if _auth_engine is not None:+ return _auth_engine++ auth_db_path = get_auth_db_path()++ # Ensure database exists+ if not auth_db_path.exists():+ init_auth_database()++ # Create engine with connection pooling+ _auth_engine = create_engine(+ f"sqlite:///{auth_db_path}",+ poolclass=QueuePool,+ pool_size=5,+ max_overflow=10,+ pool_pre_ping=True, # Verify connections before use+ echo=False,+ )+ logger.debug("Created cached auth database engine")++ return _auth_engine++def init_auth_database():"""Initialize the authentication database if it doesn't exist."""auth_db_path = get_auth_db_path()@@ -33,26 +80,60 @@ def init_auth_database():logger.info(f"Creating auth database at {auth_db_path}")- # Create the database+ # Create the database with a temporary engineengine = create_engine(f"sqlite:///{auth_db_path}")# Create tablesBase.metadata.create_all(engine, tables=[User.__table__])- logger.info("Auth database initialized successfully")-+ # Dispose the temporary engine+ engine.dispose()-def get_auth_db_session():- """Get a session for the auth database."""- auth_db_path = get_auth_db_path()+ logger.info("Auth database initialized successfully")- # Ensure database exists- if not auth_db_path.exists():- init_auth_database()- engine = create_engine(f"sqlite:///{auth_db_path}")- Session = sessionmaker(bind=engine)- return Session()+def get_auth_db_session() -> Session:+ """+ Get a session for the auth database.++ IMPORTANT: The caller MUST close the session when done to return+ the connection to the pool. Use auth_db_session() context manager+ for automatic cleanup.+ """+ engine = _get_auth_engine()+ SessionFactory = sessionmaker(bind=engine)+ return SessionFactory()+++@contextmanager+def auth_db_session():+ """+ Context manager for auth database sessions.++ Usage:+ with auth_db_session() as session:+ user = session.query(User).filter_by(username=username).first()++ The session is automatically closed when the context exits.+ """+ session = get_auth_db_session()+ try:+ yield session+ finally:+ session.close()+++def dispose_auth_engine():+ """+ Dispose the auth engine (for shutdown/cleanup).+ """+ global _auth_engine++ with _auth_engine_lock:+ if _auth_engine is not None:+ _auth_engine.dispose()+ _auth_engine = None+ logger.debug("Disposed auth database engine")# Initialize on import