~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
refactor(db): remove per-thread NullPool engines to fix FD leak (#3441)
LearningCircuit8e11dcf72901
diff --git a/docs/architecture.md b/docs/architecture.mdindex 5acd88a620..f20881856b 100644--- a/docs/architecture.md+++ b/docs/architecture.md@@ -465,10 +465,22 @@ flowchart TBUnlike typical web apps that share a single database connection pool, this application maintains **separate database engines per user** because each user has their own encrypted SQLite file with a unique SQLCipher key ([SQLCipher](https://www.zetetic.net/sqlcipher/) is an encrypted extension of SQLite). This creates a threading challenge: every background thread needs its own engine for the user it serves.-Two SQLAlchemy pooling strategies coexist:--- **QueuePool** — one per user, shared across Flask request-handler threads (`pool_size=10`, `max_overflow=30`). Maintains a fixed-size pool of reusable connections that persist between requests.-- **NullPool** — per-thread engines for background work (research workers, scheduler jobs). Creates a new connection per checkout and closes it on return (no pooling). The SQLAlchemy `Session` using this engine is held for the background thread's lifetime.+A single **QueuePool** engine is kept per user (`pool_size=20`,+`max_overflow=40`, `pool_timeout=10`) in+`DatabaseManager.connections[username]`. It is created with+`check_same_thread=False`, so it is shared safely across Flask+request-handler threads AND background threads (research workers,+scheduler jobs, metric writers). All of these acquire sessions from the+same pool, which keeps FD usage bounded by `pool_size + max_overflow`+per user.++> Earlier revisions of the code maintained a second, parallel system of+> per-`(username, thread_id)` **NullPool** engines for background metric+> writes. That system was removed because orphaned entries leaked+> SQLCipher + WAL file handles (3 FDs per active connection) under load,+> eventually exhausting the 1024 FD soft limit. Routing all work through+> the single per-user QueuePool made FD usage bounded and let us delete+> ~200 lines of thread-engine bookkeeping.##### Resource Cleanup Layers@@ -476,10 +488,10 @@ Cleanup is defense-in-depth with multiple layers:| Layer | Trigger | What it cleans ||-------|---------|----------------|-| `@thread_cleanup` decorator | Thread function exit (normal or exception) | DB session, thread engine, settings context, search context |+| `@thread_cleanup` decorator | Thread function exit (normal or exception) | DB session (returned to per-user pool), settings context, search context || `finally` blocks | Per-research in `run_research_process()` | Search engine HTTP sessions, strategy thread pool executors |-| `teardown_appcontext` | After each HTTP request | QueuePool session, thread-local session, triggers dead-thread engine sweep (rate-limited to 60s) and dead-thread credential tracking cleanup (every request) |-| Dead-thread engine sweep | Every ~60s (rate-limited) | Disposes NullPool engines for threads no longer in `threading.enumerate()` |+| `teardown_appcontext` | After each HTTP request | QueuePool session, thread-local session, triggers dead-thread credential sweep |+| Periodic pool dispose | Every 30 min | Calls `engine.dispose()` on per-user QueuePool engines to release SQLCipher+WAL file handles that accumulate from out-of-order connection closes || Logout cascade | User logout | Scheduler unregister (removes password) → DB close (`engine.dispose()`) → session destroy || Stale session cleanup | `before_request` (~1% of requests, sampled) | Clears Flask sessions for users whose DB connection is gone |diff --git a/src/local_deep_research/database/encrypted_db.py b/src/local_deep_research/database/encrypted_db.pyindex 5d7cc054ef..00f826e494 100644--- a/src/local_deep_research/database/encrypted_db.py+++ b/src/local_deep_research/database/encrypted_db.py@@ -5,15 +5,14 @@ Handles per-user encrypted databases with browser-friendly authentication.import osimport threading-import timefrom pathlib import Path-from typing import Any, Dict, Optional, Tuple+from typing import Any, Dict, Optionalfrom loguru import loggerfrom sqlalchemy import create_engine, event, textfrom sqlalchemy.engine import Enginefrom sqlalchemy.orm import Session, sessionmaker-from sqlalchemy.pool import QueuePool, NullPool, StaticPool+from sqlalchemy.pool import QueuePool, StaticPoolfrom ..config.paths import get_data_directory, get_user_database_filenamefrom ..settings.env_registry import get_env_setting@@ -40,11 +39,6 @@ class DatabaseManager:def __init__(self):self.connections: Dict[str, Engine] = {}self._connections_lock = threading.RLock()- # Track thread-specific engines for cleanup (key: (username, thread_id) tuple)- self._thread_engines: Dict[Tuple[str, int], Engine] = {}- self._thread_engine_lock = threading.Lock()- self._sweep_lock = threading.Lock()- self._last_sweep_time = 0.0self.data_dir = get_data_directory() / "encrypted_databases"self.data_dir.mkdir(parents=True, exist_ok=True)@@ -99,8 +93,9 @@ class DatabaseManager:if self._use_static_pool:return {}return {- "pool_size": 10,- "max_overflow": 20,+ "pool_size": 20,+ "max_overflow": 40,+ "pool_timeout": 10,"pool_pre_ping": POOL_PRE_PING,"pool_recycle": POOL_RECYCLE_SECONDS,}@@ -637,9 +632,6 @@ class DatabaseManager:del self.connections[username]logger.info(f"Closed database for user {username}")- # Also cleanup any thread engines for this user- self.cleanup_thread_engines(username=username)-def close_all_databases(self):"""Close all open user database connections and release file locks."""with self._connections_lock:@@ -649,7 +641,6 @@ class DatabaseManager:except Exception:logger.debug(f"Error disposing engine for {username}")self.connections.clear()- self.cleanup_all_thread_engines()def check_database_integrity(self, username: str) -> bool:"""Check integrity of a user's encrypted database."""@@ -740,152 +731,37 @@ class DatabaseManager:num_connections = len(self.connections)return {"active_connections": num_connections,- "thread_engines": len(self._thread_engines),"active_sessions": 0, # Sessions are created on-demand, not tracked- "estimated_memory_mb": (num_connections + len(self._thread_engines))+ "estimated_memory_mb": num_connections* 3.5, # ~3.5MB per connection}- def cleanup_thread_engines(- self, username: str = None, thread_id: int = None- ):- """- Clean up thread-specific engines.-- Args:- username: If provided, cleanup engines for this user only- thread_id: If provided, cleanup engines for this thread only- If neither provided, cleanup current thread's engines- """- if thread_id is None and username is None:- thread_id = threading.get_ident()-- with self._thread_engine_lock:- keys_to_remove = []- for key in self._thread_engines:- # Key is a tuple: (username, thread_id)- key_user, key_thread = key-- should_remove = False- if username and thread_id:- should_remove = (- key_user == username and key_thread == thread_id- )- elif username:- should_remove = key_user == username- elif thread_id:- should_remove = key_thread == thread_id-- if should_remove:- keys_to_remove.append(key)-- for key in keys_to_remove:- try:- self._thread_engines[key].dispose()- logger.debug(f"Disposed thread engine: {key}")- except Exception:- logger.warning(f"Error disposing thread engine {key}")- del self._thread_engines[key]-- def cleanup_dead_thread_engines(self):- """Remove engines for threads that are no longer alive.-- DEAD THREAD ENGINE SWEEP — Defense-in-depth safety net.-- Context: Each thread that accesses the encrypted database gets its- own NullPool engine stored in _thread_engines[(username, thread_id)].- Normal cleanup happens via @thread_cleanup decorator, which calls- cleanup_thread_engines() when the thread's function exits (including- on exceptions).-- Why NullPool engines don't leak FDs: NullPool creates and closes- connections per use — it does NOT hold persistent connections like- QueuePool. An orphaned NullPool engine is a small memory leak- (the engine object stays in _thread_engines dict), NOT an FD leak.-- Why we sweep anyway:- 1. Prevents unbounded memory growth in _thread_engines dict- 2. Defense-in-depth: if @thread_cleanup fails to fire (e.g.- interpreter crash, daemon thread killed at shutdown), this- catches the leftovers- 3. Provides observability via log messages-- Known limitation: Python recycles thread IDs. A new thread could- get the same ID as a dead thread. The sweep checks- threading.enumerate() which only includes alive threads, so a- recycled-ID thread that's alive won't have its engine disposed.- The race window (thread dies after enumerate() snapshot but before- dispose()) is benign — the engine would just be cleaned up on the- next sweep cycle.-- Rate limiting: Sweeps run at most every 60 seconds to avoid- overhead. Three trigger points: teardown_appcontext (request-driven,- via maybe_sweep_dead_engines), processor_v2 queue loop- (timer-driven, every 6 iterations x 10s = ~60s), and- connection_cleanup scheduler (timer-driven, every ~300s).- """- with self._thread_engine_lock:- alive_ids = {t.ident for t in threading.enumerate()}- dead_keys = [- k for k in self._thread_engines if k[1] not in alive_ids- ]- if not dead_keys:- return- for key in dead_keys:- try:- self._thread_engines[key].dispose()- except Exception:- logger.warning(f"Error disposing dead thread engine {key}")- del self._thread_engines[key]- logger.info(- f"Swept {len(dead_keys)} dead thread engine(s), "- f"{len(self._thread_engines)} remaining"- )-- def maybe_sweep_dead_engines(self, interval: float = 60.0):- """Run dead-thread sweep if enough time has passed."""- with self._sweep_lock:- now = time.monotonic()- if now - self._last_sweep_time < interval:- return- self._last_sweep_time = now- self.cleanup_dead_thread_engines()-- def cleanup_all_thread_engines(self):- """Clean up all thread-specific engines (for shutdown)."""- with self._thread_engine_lock:- count = len(self._thread_engines)- for key, engine in list(self._thread_engines.items()):- try:- engine.dispose()- except Exception:- logger.warning(f"Error disposing thread engine {key}")- self._thread_engines.clear()- logger.info(f"All thread engines disposed ({count} total)")-def create_thread_safe_session_for_metrics(self, username: str, password: str):"""Create a new database session safe for use in background threads.- This is specifically for metrics/logging - NOT for settings or user data.++ Previously this method created a dedicated NullPool engine per+ (username, thread_id) pair, which leaked file descriptors under+ load (SQLCipher + WAL holds 3 FDs per active connection and+ orphaned engines accumulated when @thread_cleanup did not fire).++ It now routes through the shared per-user QueuePool engine at+ ``self.connections[username]``. That engine is already created+ with ``check_same_thread=False`` (so background threads are+ safe), is bounded by ``pool_size + max_overflow``, and is+ subject to the periodic ``dispose()`` workaround in+ ``connection_cleanup.py`` that mitigates the SQLCipher+WAL+ out-of-order-close FD leak.Args:username: The username- password: The user's password (encryption key)+ password: The user's password (encryption key), used only+ to open the user database on cache miss.Returns:- A SQLAlchemy session that can be used in the current thread-- IMPORTANT: This should ONLY be used for:- - Writing token metrics- - Writing search metrics- - Writing logs-- DO NOT use this for:- - Reading/writing settings- - Modifying user data- - Any operation that should be synchronized with user requests+ A SQLAlchemy Session bound to the per-user QueuePool engine."""db_path = self._get_user_db_path(username)@@ -901,82 +777,18 @@ class DatabaseManager:f"fully functional but are less resistant to multi-target attacks.")- # Create thread-specific key for engine reuse (tuple is cleaner than string)- thread_id = threading.get_ident()- engine_key = (username, thread_id)-- # Check for existing engine for this thread/user combo- with self._thread_engine_lock:- if engine_key in self._thread_engines:- engine = self._thread_engines[engine_key]- # Verify engine is still valid- try:- with engine.connect() as conn:- conn.execute(text("SELECT 1"))- # Engine is valid, create session from it- Session = sessionmaker(bind=engine)- return Session()- except Exception as e:- # Engine is stale, remove it and create new one- logger.debug(- f"Stale thread engine for {engine_key}, recreating: {e}"- )- try:- engine.dispose()- except Exception as dispose_error:- logger.debug(- f"Error disposing stale engine: {dispose_error}"- )- del self._thread_engines[engine_key]-- # Only derive key when creating a new engine (cache miss).- # This method is only called for already-authenticated users in- # background threads, so timing-attack resistance is not needed here- # (unlike open_user_database which handles login).- hex_key = get_key_from_password(password, db_path=db_path).hex()-- # Create a thread-local engine- if self.has_encryption:-- def create_thread_connection():- """Create a SQLCipher connection for this thread."""- try:- return create_sqlcipher_connection(- db_path,- hex_key=hex_key,- creation_mode=False,- connect_kwargs={"check_same_thread": False},- )- except Exception:- logger.exception(- f"Failed to create thread connection for {username}"- )- raise-- engine = create_engine(- "sqlite://",- creator=create_thread_connection,- # NullPool: each checkout creates a fresh connection, closed on- # checkin. No persistent FDs, but each SQLCipher connection- # briefly uses 1-3 FDs (main db + WAL + SHM in WAL mode).- # With per-user databases, FD usage = concurrent_threads × users × 3.- poolclass=NullPool,- echo=False,- )- else:- # Unencrypted fallback- logger.warning("Creating unencrypted thread session for metrics")- engine = create_engine(- f"sqlite:///{db_path}",- poolclass=NullPool,- echo=False,- )+ with self._connections_lock:+ engine = self.connections.get(username)- # Store engine for reuse within this thread- with self._thread_engine_lock:- self._thread_engines[engine_key] = engine+ if engine is None:+ # Cache miss — open the user database. This is idempotent:+ # after the first call it just returns the cached engine.+ engine = self.open_user_database(username, password)+ if engine is None:+ raise ValueError(f"Failed to open database for user {username}")- # Create session+ # Use SQLAlchemy's default expire_on_commit=True to match the+ # previous NullPool path's behavior.Session = sessionmaker(bind=engine)return Session()diff --git a/src/local_deep_research/database/thread_local_session.py b/src/local_deep_research/database/thread_local_session.pyindex 2f3f509e8d..a8b10af559 100644--- a/src/local_deep_research/database/thread_local_session.py+++ b/src/local_deep_research/database/thread_local_session.py@@ -114,7 +114,12 @@ class ThreadLocalSessionManager:return Nonedef _cleanup_thread_session(self):- """Clean up the current thread's session and engine."""+ """Clean up the current thread's session.++ Sessions are bound to the shared per-user QueuePool engine, so+ closing the session returns its connection to the pool — there+ are no per-thread engines to dispose.+ """thread_id = threading.get_ident()if hasattr(self._local, "session") and self._local.session:@@ -132,11 +137,7 @@ class ThreadLocalSessionManager:finally:self._local.session = None- # Clean up the thread engine too- if hasattr(self._local, "username") and self._local.username:- db_manager.cleanup_thread_engines(- username=self._local.username, thread_id=thread_id- )+ if hasattr(self._local, "username"):self._local.username = None# Remove from tracking@@ -163,21 +164,15 @@ class ThreadLocalSessionManager:def cleanup_dead_threads(self):"""Remove credential entries for threads that are no longer alive.- Companion to encrypted_db.cleanup_dead_thread_engines().- Removes credentials and session tracking for threads no longer alive.-- This is separate from cleanup_current_thread() which handles the- normal case (thread cleans up its own session on exit via- @thread_cleanup decorator).-- cleanup_dead_threads() handles the abnormal case: threads that died- without triggering their cleanup handler. It uses- threading.enumerate() to identify alive threads and removes entries- for dead ones.+ Handles the abnormal case of threads that died without triggering+ their cleanup handler. Uses threading.enumerate() to identify+ alive threads and removes credential entries for dead ones.+ Sessions on dead threads are garbage-collected normally and+ their connections return to the shared per-user QueuePool.Called from:- processor_v2.py: every ~60s in the queue loop- - app_factory.py: in teardown_appcontext (engine sweep rate-limited)+ - app_factory.py: in teardown_appcontext- connection_cleanup.py: in cleanup_idle_connections (every ~300s)"""alive_ids = {t.ident for t in threading.enumerate()}@@ -198,9 +193,6 @@ class ThreadLocalSessionManager:for thread_id in thread_ids:self.cleanup_thread(thread_id)- # Also cleanup any remaining thread engines- db_manager.cleanup_all_thread_engines()-# Global instancethread_session_manager = ThreadLocalSessionManager()@@ -228,15 +220,7 @@ def cleanup_current_thread():def cleanup_dead_threads():- """Sweep dead-thread entries from both session manager and engine dict.-- Each call is independently guarded so one failure does not block the other.- Engine sweep is rate-limited internally (at most once per 60 s).- """- try:- db_manager.maybe_sweep_dead_engines()- except Exception:- logger.warning("Dead-thread engine sweep failed")+ """Sweep dead-thread credential entries from the session manager."""try:thread_session_manager.cleanup_dead_threads()except Exception:diff --git a/src/local_deep_research/web/app_factory.py b/src/local_deep_research/web/app_factory.pyindex f58c91f3e1..130f60656a 100644--- a/src/local_deep_research/web/app_factory.py+++ b/src/local_deep_research/web/app_factory.py@@ -490,11 +490,6 @@ def create_app():queue_processor.start()logger.info("Started research queue processor v2")- # Register shutdown cleanup for thread engine disposal- import atexit-- atexit.register(db_manager.cleanup_all_thread_engines)-logger.info("App factory completed successfully")return app, socket_service@@ -587,11 +582,9 @@ def apply_middleware(app):except Exception:logger.warning("Error closing request session during cleanup")- # Dead thread sweep — rate-limited internally to every 60 seconds.- # See encrypted_db.cleanup_dead_thread_engines() for detailed- # rationale. Multiple trigger points (here, processor_v2, and- # connection_cleanup scheduler) ensure sweeps happen regardless- # of traffic patterns.+ # Sweep credential entries for dead threads. Multiple trigger+ # points (here, processor_v2, and connection_cleanup scheduler)+ # ensure sweeps happen regardless of traffic patterns.try:from ..database.thread_local_session import cleanup_dead_threadsdiff --git a/src/local_deep_research/web/auth/connection_cleanup.py b/src/local_deep_research/web/auth/connection_cleanup.pyindex 4567eb81e4..2c223ff806 100644--- a/src/local_deep_research/web/auth/connection_cleanup.py+++ b/src/local_deep_research/web/auth/connection_cleanup.py@@ -158,12 +158,18 @@ def cleanup_idle_connections(session_manager, db_manager):# --- FD monitoring ---try:fd_count = _count_open_fds()- thread_engine_count = len(db_manager._thread_engines)pool_engine_count = len(db_manager.connections)+ pool_checked_out = 0+ with db_manager._connections_lock:+ for engine in db_manager.connections.values():+ try:+ pool_checked_out += engine.pool.checkedout()+ except Exception: # noqa: silent-exception+ passlogger.debug(f"Resource monitor: open_fds={fd_count}, "f"pool_engines={pool_engine_count}, "- f"thread_engines={thread_engine_count}, "+ f"pool_checked_out={pool_checked_out}, "f"protected_users={len(protected)}")if fd_count > 800:diff --git a/src/local_deep_research/web/database/README.md b/src/local_deep_research/web/database/README.mdindex f29a7df09e..4b0a2d1286 100644--- a/src/local_deep_research/web/database/README.md+++ b/src/local_deep_research/web/database/README.md@@ -55,12 +55,11 @@ The unified database contains:## Thread Safety & Connection Model-The application uses per-user encrypted SQLite databases (via [SQLCipher](https://www.zetetic.net/sqlcipher/)) with two [SQLAlchemy pool](https://docs.sqlalchemy.org/en/20/core/pooling.html) strategies:+The application uses per-user encrypted SQLite databases (via [SQLCipher](https://www.zetetic.net/sqlcipher/)) with a single shared [SQLAlchemy QueuePool](https://docs.sqlalchemy.org/en/20/core/pooling.html) per user:-- **QueuePool** (shared per-user engine in `DatabaseManager.connections`): Serves Flask request handlers. `pool_size=10`, `max_overflow=30`. Connections persist in the pool.-- **NullPool** (per-thread engines in `DatabaseManager._thread_engines`): Used by background threads (research workers, scheduler jobs). Each checkout creates a fresh SQLCipher connection with the user's encryption key. The SQLAlchemy `Session` using this engine is held for the thread's lifetime.+- **QueuePool** (shared per-user engine in `DatabaseManager.connections`): Serves both Flask request handlers AND background threads (research workers, scheduler jobs, metric writers). `pool_size=20`, `max_overflow=40`, `pool_timeout=10`. Engines are created with `check_same_thread=False` so they're safe to share across threads. FD usage is bounded by `pool_size + max_overflow` per user, not by the number of active background threads.-Cleanup is handled by the `@thread_cleanup` decorator (primary) and periodic dead-thread sweeps (fallback for daemon threads that exit without cleanup).+Cleanup is handled by the `@thread_cleanup` decorator (closes sessions at thread exit, returning connections to the pool) and by a periodic `engine.dispose()` sweep every 30 minutes that mitigates a SQLCipher+WAL handle leak triggered by out-of-order connection closes.Note: The core database module is at `src/local_deep_research/database/`, separate from this `web/database/` directory. See [Architecture - Thread & Resource Lifecycle](../../../../docs/architecture.md#thread--resource-lifecycle) for the full cleanup architecture.diff --git a/src/local_deep_research/web/queue/processor_v2.py b/src/local_deep_research/web/queue/processor_v2.pyindex 4aee530603..a7ae89fbbc 100644--- a/src/local_deep_research/web/queue/processor_v2.py+++ b/src/local_deep_research/web/queue/processor_v2.py@@ -449,12 +449,9 @@ class QueueProcessorV2:"thread-local cleanup on shutdown", exc_info=True)- # Periodic dead-thread sweep (every ~60 seconds).- # See encrypted_db.cleanup_dead_thread_engines() for- # detailed rationale. One of three sweep trigger points- # (app_factory teardown, connection_cleanup scheduler,- # and here). Multiple triggers ensure sweeps happen- # regardless of traffic patterns.+ # Periodic dead-thread credential sweep (every ~60s).+ # One of three sweep trigger points (app_factory+ # teardown, connection_cleanup scheduler, and here).self._loop_iteration += 1if self._loop_iteration % 6 == 0: # Every ~60s (10s × 6)try:diff --git a/tests/database/test_database_manager_extended.py b/tests/database/test_database_manager_extended.pyindex 9e462916e3..3e8f4dae7a 100644--- a/tests/database/test_database_manager_extended.py+++ b/tests/database/test_database_manager_extended.py@@ -6,7 +6,6 @@ Tests encrypted database management, connection pooling, and thread safety."""import pytest-import threadingfrom unittest.mock import patch, MagicMockfrom pathlib import Path@@ -161,8 +160,9 @@ class TestConnectionPooling:kwargs = manager._get_pool_kwargs()assert "pool_size" in kwargs- assert kwargs["pool_size"] == 10- assert kwargs["max_overflow"] == 20+ assert kwargs["pool_size"] == 20+ assert kwargs["max_overflow"] == 40+ assert kwargs["pool_timeout"] == 10@patch("local_deep_research.database.encrypted_db.get_data_directory")def test_connection_storage(self, mock_data_dir):@@ -187,129 +187,6 @@ class TestConnectionPooling:class TestThreadSafety:"""Tests for thread safety functionality"""- @patch("local_deep_research.database.encrypted_db.get_data_directory")- def test_thread_local_engine_isolation(self, mock_data_dir):- """Test thread-local engines are isolated"""- from local_deep_research.database.encrypted_db import DatabaseManager-- mock_data_dir.return_value = Path("/tmp/test_data")-- with patch.object(- DatabaseManager, "_check_encryption_available", return_value=True- ):- manager = DatabaseManager()-- # Add thread-specific engines- thread_id = threading.get_ident()- manager._thread_engines[("user1", thread_id)] = MagicMock()- manager._thread_engines[("user2", thread_id)] = MagicMock()-- assert len(manager._thread_engines) == 2-- @patch("local_deep_research.database.encrypted_db.get_data_directory")- def test_thread_cleanup_by_username(self, mock_data_dir):- """Test thread cleanup by username"""- from local_deep_research.database.encrypted_db import DatabaseManager-- mock_data_dir.return_value = Path("/tmp/test_data")-- with patch.object(- DatabaseManager, "_check_encryption_available", return_value=True- ):- manager = DatabaseManager()-- # Add thread-specific engines- mock_engine1 = MagicMock()- mock_engine2 = MagicMock()- manager._thread_engines[("user1", 100)] = mock_engine1- manager._thread_engines[("user2", 100)] = mock_engine2-- manager.cleanup_thread_engines(username="user1")-- assert ("user1", 100) not in manager._thread_engines- assert ("user2", 100) in manager._thread_engines- mock_engine1.dispose.assert_called_once()-- @patch("local_deep_research.database.encrypted_db.get_data_directory")- def test_thread_cleanup_by_thread_id(self, mock_data_dir):- """Test thread cleanup by thread ID"""- from local_deep_research.database.encrypted_db import DatabaseManager-- mock_data_dir.return_value = Path("/tmp/test_data")-- with patch.object(- DatabaseManager, "_check_encryption_available", return_value=True- ):- manager = DatabaseManager()-- # Add thread-specific engines- mock_engine1 = MagicMock()- mock_engine2 = MagicMock()- manager._thread_engines[("user1", 100)] = mock_engine1- manager._thread_engines[("user1", 200)] = mock_engine2-- manager.cleanup_thread_engines(thread_id=100)-- assert ("user1", 100) not in manager._thread_engines- assert ("user1", 200) in manager._thread_engines-- @patch("local_deep_research.database.encrypted_db.get_data_directory")- def test_thread_cleanup_all(self, mock_data_dir):- """Test cleaning up all thread engines"""- from local_deep_research.database.encrypted_db import DatabaseManager-- mock_data_dir.return_value = Path("/tmp/test_data")-- with patch.object(- DatabaseManager, "_check_encryption_available", return_value=True- ):- manager = DatabaseManager()-- # Add thread-specific engines- for i in range(5):- manager._thread_engines[(f"user{i}", i * 100)] = MagicMock()-- manager.cleanup_all_thread_engines()-- assert len(manager._thread_engines) == 0-- @patch("local_deep_research.database.encrypted_db.get_data_directory")- def test_concurrent_cleanup(self, mock_data_dir):- """Test concurrent cleanup operations"""- from local_deep_research.database.encrypted_db import DatabaseManager-- mock_data_dir.return_value = Path("/tmp/test_data")-- with patch.object(- DatabaseManager, "_check_encryption_available", return_value=True- ):- manager = DatabaseManager()-- # Add engines- for i in range(10):- manager._thread_engines[(f"user{i}", i)] = MagicMock()-- # Run cleanups from multiple threads- errors = []-- def cleanup_thread(username):- try:- manager.cleanup_thread_engines(username=username)- except Exception as e:- errors.append(e)-- threads = [- threading.Thread(target=cleanup_thread, args=(f"user{i}",))- for i in range(10)- ]-- for t in threads:- t.start()- for t in threads:- t.join()-- assert len(errors) == 0-class TestDatabaseOperations:"""Tests for database operations"""@@ -388,15 +265,13 @@ class TestDatabaseOperations:):manager = DatabaseManager()- # Add some connections and thread enginesmanager.connections["user1"] = MagicMock()manager.connections["user2"] = MagicMock()- manager._thread_engines[("user1", 100)] = MagicMock()usage = manager.get_memory_usage()assert usage["active_connections"] == 2- assert usage["thread_engines"] == 1+ assert "thread_engines" not in usageassert "estimated_memory_mb" in usagediff --git a/tests/database/test_encrypted_db_coverage.py b/tests/database/test_encrypted_db_coverage.pyindex e4a9f59f6c..e1a39afacc 100644--- a/tests/database/test_encrypted_db_coverage.py+++ b/tests/database/test_encrypted_db_coverage.py@@ -6,21 +6,16 @@ Covers:- is_user_connected- get_connected_usernames- get_memory_usage-- cleanup_thread_engines (filter logic)-- cleanup_dead_thread_engines-- maybe_sweep_dead_engines (rate limiting)-- cleanup_all_thread_engines- close_user_database / close_all_databases- check_database_integrity success/failure paths- get_pool_kwargs"""import threading-import timefrom contextlib import contextmanagerfrom unittest.mock import MagicMock, patch-import pytest+import pytest # noqa: F401MODULE = "local_deep_research.database.encrypted_db"@@ -54,10 +49,6 @@ def _unencrypted_manager():mgr = DatabaseManager.__new__(DatabaseManager)mgr.connections = {}mgr._connections_lock = threading.RLock()- mgr._thread_engines = {}- mgr._thread_engine_lock = threading.Lock()- mgr._sweep_lock = threading.Lock()- mgr._last_sweep_time = 0.0mgr.has_encryption = Falseimport os@@ -132,18 +123,16 @@ class TestGetMemoryUsage:with _unencrypted_manager() as mgr:stats = mgr.get_memory_usage()assert stats["active_connections"] == 0- assert stats["thread_engines"] == 0+ assert "thread_engines" not in statsassert stats["estimated_memory_mb"] == 0.0- def test_with_connections_and_thread_engines(self):+ def test_with_connections(self):with _unencrypted_manager() as mgr:mgr.connections["user1"] = MagicMock()mgr.connections["user2"] = MagicMock()- mgr._thread_engines[("user1", 100)] = MagicMock()stats = mgr.get_memory_usage()assert stats["active_connections"] == 2- assert stats["thread_engines"] == 1- assert stats["estimated_memory_mb"] == pytest.approx(3 * 3.5)+ assert stats["estimated_memory_mb"] == pytest.approx(2 * 3.5)# ---------------------------------------------------------------------------@@ -176,24 +165,20 @@ class TestCloseUserDatabase:with _unencrypted_manager() as mgr:mock_engine = MagicMock()mgr.connections["alice"] = mock_engine- with patch.object(mgr, "cleanup_thread_engines"):- mgr.close_user_database("alice")+ mgr.close_user_database("alice")mock_engine.dispose.assert_called_once()assert "alice" not in mgr.connectionsdef test_no_error_when_user_not_connected(self):with _unencrypted_manager() as mgr:- # Should not raise- with patch.object(mgr, "cleanup_thread_engines"):- mgr.close_user_database("nonexistent")+ mgr.close_user_database("nonexistent")def test_dispose_error_handled_gracefully(self):with _unencrypted_manager() as mgr:mock_engine = MagicMock()mock_engine.dispose.side_effect = RuntimeError("dispose failed")mgr.connections["alice"] = mock_engine- with patch.object(mgr, "cleanup_thread_engines"):- mgr.close_user_database("alice")+ mgr.close_user_database("alice")assert "alice" not in mgr.connections@@ -208,118 +193,7 @@ class TestCloseAllDatabases:e1, e2 = MagicMock(), MagicMock()mgr.connections["a"] = e1mgr.connections["b"] = e2- with patch.object(mgr, "cleanup_all_thread_engines"):- mgr.close_all_databases()+ mgr.close_all_databases()e1.dispose.assert_called_once()e2.dispose.assert_called_once()assert mgr.connections == {}---# ----------------------------------------------------------------------------# cleanup_thread_engines-# ------------------------------------------------------------------------------class TestCleanupThreadEngines:- def test_cleanup_by_username(self):- with _unencrypted_manager() as mgr:- e1, e2 = MagicMock(), MagicMock()- mgr._thread_engines[("alice", 100)] = e1- mgr._thread_engines[("bob", 200)] = e2- mgr.cleanup_thread_engines(username="alice")- e1.dispose.assert_called_once()- assert ("alice", 100) not in mgr._thread_engines- assert ("bob", 200) in mgr._thread_engines-- def test_cleanup_by_thread_id(self):- with _unencrypted_manager() as mgr:- e1, e2 = MagicMock(), MagicMock()- mgr._thread_engines[("alice", 100)] = e1- mgr._thread_engines[("alice", 200)] = e2- mgr.cleanup_thread_engines(thread_id=100)- e1.dispose.assert_called_once()- assert ("alice", 100) not in mgr._thread_engines- assert ("alice", 200) in mgr._thread_engines-- def test_cleanup_by_username_and_thread(self):- with _unencrypted_manager() as mgr:- e1, e2 = MagicMock(), MagicMock()- mgr._thread_engines[("alice", 100)] = e1- mgr._thread_engines[("alice", 200)] = e2- mgr.cleanup_thread_engines(username="alice", thread_id=100)- e1.dispose.assert_called_once()- e2.dispose.assert_not_called()-- def test_cleanup_current_thread_when_no_args(self):- with _unencrypted_manager() as mgr:- tid = threading.get_ident()- e = MagicMock()- mgr._thread_engines[("alice", tid)] = e- mgr.cleanup_thread_engines()- e.dispose.assert_called_once()---# ----------------------------------------------------------------------------# cleanup_dead_thread_engines-# ------------------------------------------------------------------------------class TestCleanupDeadThreadEngines:- def test_removes_dead_thread_engines(self):- with _unencrypted_manager() as mgr:- dead_tid = 999999 # very unlikely to be a real thread id- e = MagicMock()- mgr._thread_engines[("alice", dead_tid)] = e- mgr.cleanup_dead_thread_engines()- e.dispose.assert_called_once()- assert ("alice", dead_tid) not in mgr._thread_engines-- def test_keeps_alive_thread_engines(self):- with _unencrypted_manager() as mgr:- alive_tid = threading.get_ident()- e = MagicMock()- mgr._thread_engines[("alice", alive_tid)] = e- mgr.cleanup_dead_thread_engines()- e.dispose.assert_not_called()-- def test_no_error_when_empty(self):- with _unencrypted_manager() as mgr:- mgr.cleanup_dead_thread_engines() # Should not raise---# ----------------------------------------------------------------------------# maybe_sweep_dead_engines-# ------------------------------------------------------------------------------class TestMaybeSweepDeadEngines:- def test_sweeps_when_interval_elapsed(self):- with _unencrypted_manager() as mgr:- mgr._last_sweep_time = 0.0- with patch.object(mgr, "cleanup_dead_thread_engines") as mock_sweep:- mgr.maybe_sweep_dead_engines(interval=0.0)- mock_sweep.assert_called_once()-- def test_skips_when_interval_not_elapsed(self):- with _unencrypted_manager() as mgr:- mgr._last_sweep_time = time.monotonic() + 9999- with patch.object(mgr, "cleanup_dead_thread_engines") as mock_sweep:- mgr.maybe_sweep_dead_engines(interval=60.0)- mock_sweep.assert_not_called()---# ----------------------------------------------------------------------------# cleanup_all_thread_engines-# ------------------------------------------------------------------------------class TestCleanupAllThreadEngines:- def test_disposes_all_thread_engines(self):- with _unencrypted_manager() as mgr:- e1, e2 = MagicMock(), MagicMock()- mgr._thread_engines[("alice", 100)] = e1- mgr._thread_engines[("bob", 200)] = e2- mgr.cleanup_all_thread_engines()- e1.dispose.assert_called_once()- e2.dispose.assert_called_once()- assert mgr._thread_engines == {}diff --git a/tests/database/test_encrypted_db_manager.py b/tests/database/test_encrypted_db_manager.pyindex a37054f1bc..830fe5c06a 100644--- a/tests/database/test_encrypted_db_manager.py+++ b/tests/database/test_encrypted_db_manager.py@@ -305,32 +305,6 @@ class TestDatabaseClosure:mock_engine.dispose.assert_called_once()assert "testuser" not in manager.connections- @patch("local_deep_research.database.encrypted_db.get_data_directory")- def test_close_database_cleans_thread_engines(- self, mock_data_dir, tmp_path- ):- """Test closing database also cleans thread engines."""- from local_deep_research.database.encrypted_db import DatabaseManager-- mock_data_dir.return_value = tmp_path-- with patch.object(- DatabaseManager, "_check_encryption_available", return_value=True- ):- manager = DatabaseManager()-- mock_engine = MagicMock()- manager.connections["testuser"] = mock_engine-- # Add thread engine- thread_engine = MagicMock()- manager._thread_engines[("testuser", 12345)] = thread_engine-- manager.close_user_database("testuser")-- assert ("testuser", 12345) not in manager._thread_engines- thread_engine.dispose.assert_called_once()-@patch("local_deep_research.database.encrypted_db.get_data_directory")def test_close_nonexistent_database_no_error(self, mock_data_dir, tmp_path):"""Test closing nonexistent database doesn't raise error."""@@ -679,7 +653,6 @@ class TestMemoryUsage:usage = manager.get_memory_usage()assert usage["active_connections"] == 0- assert usage["thread_engines"] == 0assert usage["active_sessions"] == 0assert usage["estimated_memory_mb"] == 0@@ -695,16 +668,13 @@ class TestMemoryUsage:):manager = DatabaseManager()- # Add connectionsmanager.connections["user1"] = MagicMock()manager.connections["user2"] = MagicMock()- manager._thread_engines[("user1", 100)] = MagicMock()usage = manager.get_memory_usage()assert usage["active_connections"] == 2- assert usage["thread_engines"] == 1- assert usage["estimated_memory_mb"] == 10.5 # (2 + 1) * 3.5+ assert usage["estimated_memory_mb"] == 7.0 # 2 * 3.5@patch("local_deep_research.database.encrypted_db.get_data_directory")def test_memory_usage_calculation(self, mock_data_dir, tmp_path):@@ -718,165 +688,12 @@ class TestMemoryUsage:):manager = DatabaseManager()- # Add 5 connections and 3 thread enginesfor i in range(5):manager.connections[f"user{i}"] = MagicMock()- for i in range(3):- manager._thread_engines[(f"user{i}", i * 100)] = MagicMock()usage = manager.get_memory_usage()- # (5 + 3) * 3.5 = 28 MB- assert usage["estimated_memory_mb"] == 28---class TestThreadEngineCleanup:- """Tests for thread engine cleanup functionality."""-- @patch("local_deep_research.database.encrypted_db.get_data_directory")- def test_cleanup_by_username(self, mock_data_dir, tmp_path):- """Test cleanup thread engines by username."""- from local_deep_research.database.encrypted_db import DatabaseManager-- mock_data_dir.return_value = tmp_path-- with patch.object(- DatabaseManager, "_check_encryption_available", return_value=True- ):- manager = DatabaseManager()-- mock_engine1 = MagicMock()- mock_engine2 = MagicMock()- mock_engine3 = MagicMock()-- manager._thread_engines[("user1", 100)] = mock_engine1- manager._thread_engines[("user1", 200)] = mock_engine2- manager._thread_engines[("user2", 100)] = mock_engine3-- manager.cleanup_thread_engines(username="user1")-- assert ("user1", 100) not in manager._thread_engines- assert ("user1", 200) not in manager._thread_engines- assert ("user2", 100) in manager._thread_engines- mock_engine1.dispose.assert_called_once()- mock_engine2.dispose.assert_called_once()- mock_engine3.dispose.assert_not_called()-- @patch("local_deep_research.database.encrypted_db.get_data_directory")- def test_cleanup_by_thread_id(self, mock_data_dir, tmp_path):- """Test cleanup thread engines by thread ID."""- from local_deep_research.database.encrypted_db import DatabaseManager-- mock_data_dir.return_value = tmp_path-- with patch.object(- DatabaseManager, "_check_encryption_available", return_value=True- ):- manager = DatabaseManager()-- mock_engine1 = MagicMock()- mock_engine2 = MagicMock()-- manager._thread_engines[("user1", 100)] = mock_engine1- manager._thread_engines[("user1", 200)] = mock_engine2-- manager.cleanup_thread_engines(thread_id=100)-- assert ("user1", 100) not in manager._thread_engines- assert ("user1", 200) in manager._thread_engines-- @patch("local_deep_research.database.encrypted_db.get_data_directory")- def test_cleanup_by_both_username_and_thread_id(- self, mock_data_dir, tmp_path- ):- """Test cleanup with both username and thread_id specified."""- from local_deep_research.database.encrypted_db import DatabaseManager-- mock_data_dir.return_value = tmp_path-- with patch.object(- DatabaseManager, "_check_encryption_available", return_value=True- ):- manager = DatabaseManager()-- mock_engine1 = MagicMock()- mock_engine2 = MagicMock()- mock_engine3 = MagicMock()-- manager._thread_engines[("user1", 100)] = mock_engine1- manager._thread_engines[("user1", 200)] = mock_engine2- manager._thread_engines[("user2", 100)] = mock_engine3-- manager.cleanup_thread_engines(username="user1", thread_id=100)-- assert ("user1", 100) not in manager._thread_engines- assert ("user1", 200) in manager._thread_engines- assert ("user2", 100) in manager._thread_engines-- @patch("local_deep_research.database.encrypted_db.get_data_directory")- def test_cleanup_default_uses_current_thread(self, mock_data_dir, tmp_path):- """Test cleanup defaults to current thread when no args provided."""- from local_deep_research.database.encrypted_db import DatabaseManager-- mock_data_dir.return_value = tmp_path-- with patch.object(- DatabaseManager, "_check_encryption_available", return_value=True- ):- manager = DatabaseManager()-- current_thread_id = threading.get_ident()- mock_engine = MagicMock()-- manager._thread_engines[("user1", current_thread_id)] = mock_engine-- manager.cleanup_thread_engines()-- assert ("user1", current_thread_id) not in manager._thread_engines- mock_engine.dispose.assert_called_once()-- @patch("local_deep_research.database.encrypted_db.get_data_directory")- def test_cleanup_all_thread_engines(self, mock_data_dir, tmp_path):- """Test cleanup_all_thread_engines clears all engines."""- from local_deep_research.database.encrypted_db import DatabaseManager-- mock_data_dir.return_value = tmp_path-- with patch.object(- DatabaseManager, "_check_encryption_available", return_value=True- ):- manager = DatabaseManager()-- for i in range(5):- manager._thread_engines[(f"user{i}", i * 100)] = MagicMock()-- assert len(manager._thread_engines) == 5-- manager.cleanup_all_thread_engines()-- assert len(manager._thread_engines) == 0-- @patch("local_deep_research.database.encrypted_db.get_data_directory")- def test_cleanup_handles_dispose_errors(self, mock_data_dir, tmp_path):- """Test cleanup handles dispose errors gracefully."""- from local_deep_research.database.encrypted_db import DatabaseManager-- mock_data_dir.return_value = tmp_path-- with patch.object(- DatabaseManager, "_check_encryption_available", return_value=True- ):- manager = DatabaseManager()-- mock_engine = MagicMock()- mock_engine.dispose.side_effect = Exception("Dispose failed")-- manager._thread_engines[("user1", 100)] = mock_engine-- # Should not raise- manager.cleanup_thread_engines(username="user1")-- assert ("user1", 100) not in manager._thread_engines+ assert usage["estimated_memory_mb"] == 17.5 # 5 * 3.5class TestThreadSafeSessionForMetrics:@@ -906,8 +723,10 @@ class TestThreadSafeSessionForMetrics:)@patch("local_deep_research.database.encrypted_db.get_data_directory")- def test_thread_safe_session_reuses_engine(self, mock_data_dir, tmp_path):- """Test thread-safe session reuses existing engine for same thread/user."""+ def test_thread_safe_session_binds_to_queuepool_engine(+ self, mock_data_dir, tmp_path+ ):+ """The returned session is bound to the per-user QueuePool engine."""from local_deep_research.database.encrypted_db import DatabaseManagermock_data_dir.return_value = tmp_path@@ -921,32 +740,16 @@ class TestThreadSafeSessionForMetrics:):manager = DatabaseManager()- thread_id = threading.get_ident()mock_engine = MagicMock()- mock_conn = MagicMock()- mock_engine.connect.return_value.__enter__ = MagicMock(- return_value=mock_conn- )- mock_engine.connect.return_value.__exit__ = MagicMock(- return_value=False- )-- manager._thread_engines[("testuser", thread_id)] = mock_engine+ manager.connections["testuser"] = mock_enginewith patch.object(manager, "_get_user_db_path", return_value=db_file):- with patch(- "local_deep_research.database.encrypted_db.sessionmaker"- ) as mock_sm:- mock_session = MagicMock()- mock_sm.return_value = MagicMock(return_value=mock_session)-- result = manager.create_thread_safe_session_for_metrics(- "testuser", "password"- )-- assert result is mock_session+ session = manager.create_thread_safe_session_for_metrics(+ "testuser", "password"+ )+ assert session.bind is mock_engineclass TestSessionManagement:@@ -1053,42 +856,6 @@ class TestMultiUserIsolation:class TestConcurrentAccess:"""Tests for concurrent access handling."""- @patch("local_deep_research.database.encrypted_db.get_data_directory")- def test_concurrent_thread_cleanup(self, mock_data_dir, tmp_path):- """Test concurrent thread cleanup operations are safe."""- from local_deep_research.database.encrypted_db import DatabaseManager-- mock_data_dir.return_value = tmp_path-- with patch.object(- DatabaseManager, "_check_encryption_available", return_value=True- ):- manager = DatabaseManager()-- # Add many thread engines- for i in range(50):- manager._thread_engines[(f"user{i}", i)] = MagicMock()-- errors = []-- def cleanup_thread(username):- try:- manager.cleanup_thread_engines(username=username)- except Exception as e:- errors.append(e)-- threads = [- threading.Thread(target=cleanup_thread, args=(f"user{i}",))- for i in range(50)- ]-- for t in threads:- t.start()- for t in threads:- t.join()-- assert len(errors) == 0-@patch("local_deep_research.database.encrypted_db.get_data_directory")def test_concurrent_connection_storage(self, mock_data_dir, tmp_path):"""Test concurrent connection storage operations."""@@ -1198,8 +965,9 @@ class TestPoolConfiguration:kwargs = manager._get_pool_kwargs()assert "pool_size" in kwargs- assert kwargs["pool_size"] == 10- assert kwargs["max_overflow"] == 20+ assert kwargs["pool_size"] == 20+ assert kwargs["max_overflow"] == 40+ assert kwargs["pool_timeout"] == 10class TestValidEncryptionKey:diff --git a/tests/database/test_sqlcipher_connection_factory.py b/tests/database/test_sqlcipher_connection_factory.pyindex 0c08f261d4..32cabbd896 100644--- a/tests/database/test_sqlcipher_connection_factory.py+++ b/tests/database/test_sqlcipher_connection_factory.py@@ -337,52 +337,7 @@ class TestMakeSqlcipherConnection:mock_sqlcipher["performance"].assert_not_called()-class TestMetricsThreadConnectionLogging:- """Verify that create_thread_safe_session_for_metrics preserves error logging."""-- @patch(f"{_EDB}.get_data_directory")- def test_logs_exception_on_connection_failure(self, mock_dir, tmp_path):- """Metrics thread connection failures must be logged with logger.exception."""- mock_dir.return_value = tmp_path-- with patch.object(- DatabaseManager, "_check_encryption_available", return_value=True- ):- manager = DatabaseManager()- manager.has_encryption = True-- db_path = tmp_path / "test.db"- db_path.touch()-- with patch.object(- manager, "_get_user_db_path", return_value=db_path- ):- # Make create_sqlcipher_connection raise an error- with patch(- f"{_EDB}.create_sqlcipher_connection",- side_effect=RuntimeError("connection failed"),- ):- with patch(f"{_EDB}.logger") as mock_logger:- with patch(f"{_EDB}.create_engine") as mock_engine:- # create_engine should use our creator function- # Capture the creator argument and call it- def capture_creator(*args, **kwargs):- creator = kwargs.get("creator")- if creator:- with pytest.raises(RuntimeError):- creator()- return MagicMock()-- mock_engine.side_effect = capture_creator-- manager.create_thread_safe_session_for_metrics(- "testuser", "secret"- )-- # Verify logger.exception was called- mock_logger.exception.assert_called_once()- log_msg = mock_logger.exception.call_args[0][0]- assert "testuser" in log_msg- assert (- "Failed to create thread connection" in log_msg- )+# NOTE: The former TestMetricsThreadConnectionLogging tests exercised+# the inline SQLCipher creator inside create_thread_safe_session_for_metrics.+# That method now delegates to open_user_database(), so connection-failure+# logging is covered by the open_user_database tests instead.diff --git a/tests/database/test_sqlcipher_integration.py b/tests/database/test_sqlcipher_integration.pyindex fd22517e85..0c5cd8ba28 100644--- a/tests/database/test_sqlcipher_integration.py+++ b/tests/database/test_sqlcipher_integration.py@@ -26,13 +26,23 @@ def _sqlcipher_available():@pytest.fixturedef isolated_db_manager(tmp_path, monkeypatch):- """Create DatabaseManager with isolated temp directory."""+ """Create DatabaseManager with isolated temp directory.++ Forces QueuePool (not StaticPool) so concurrent-write integration+ tests exercise the same pooling path used in production. Under the+ default TESTING=1 StaticPool all threads would share a single+ underlying SQLite connection, which can't serialize concurrent+ writes at the driver level.+ """monkeypatch.setenv("LDR_DB_KDF_ITERATIONS", "1000") # Fast for testingmonkeypatch.setenv("LDR_ALLOW_UNENCRYPTED", "false") # Require encryptionfrom local_deep_research.database.encrypted_db import DatabaseManager+ from sqlalchemy.pool import QueuePoolmanager = DatabaseManager()+ manager._use_static_pool = False+ manager._pool_class = QueuePool# Point to temp directorymanager.data_dir = tmp_path / "encrypted_databases"manager.data_dir.mkdir(parents=True, exist_ok=True)diff --git a/tests/database/test_thread_engine_management.py b/tests/database/test_thread_engine_management.pydeleted file mode 100644index ce344411be..0000000000--- a/tests/database/test_thread_engine_management.py+++ /dev/null@@ -1,1262 +0,0 @@-"""-Tests for thread engine management in encrypted database.--These tests verify:-1. Thread engine tracking and reuse-2. Engine cleanup by username and thread ID-3. Connection leak prevention with multiple registrations-4. Thread isolation (different threads get different engines)-"""--import shutil-import tempfile-import threading-from concurrent.futures import ThreadPoolExecutor, as_completed-from pathlib import Path--import pytest-from sqlalchemy import text--from local_deep_research.database.auth_db import (- get_auth_db_session,- init_auth_database,-)-from local_deep_research.database.encrypted_db import DatabaseManager-from local_deep_research.database.models.auth import User---def temp_data_dir():- """Create a temporary data directory for testing."""- temp_dir = tempfile.mkdtemp()- yield Path(temp_dir)- shutil.rmtree(temp_dir)---def db_manager(temp_data_dir, monkeypatch):- """Create a DatabaseManager with test configuration."""- monkeypatch.setenv("LDR_DATA_DIR", str(temp_data_dir))- manager = DatabaseManager()- manager.data_dir = temp_data_dir / "encrypted_databases"- manager.data_dir.mkdir(parents=True, exist_ok=True)- yield manager- # Cleanup all engines after test- manager.cleanup_all_thread_engines()- for username in list(manager.connections.keys()):- manager.close_user_database(username)---def auth_user(temp_data_dir, monkeypatch):- """Create a test user in auth database."""- monkeypatch.setenv("LDR_DATA_DIR", str(temp_data_dir))- init_auth_database()- auth_db = get_auth_db_session()- user = User(username="testuser")- auth_db.add(user)- auth_db.commit()- auth_db.close()- return user---def db_manager_with_user(db_manager, auth_user):- """Create DB manager with established user database."""- username = "testuser"- password = "TestPassword123!"- db_manager.create_user_database(username, password)- yield db_manager, username, password- db_manager.close_user_database(username)---class TestThreadEngineTracking:- """Test thread engine tracking and key management."""-- def test_thread_engines_dict_initialized(self, db_manager):- """Thread engines dict should be initialized empty."""- assert hasattr(db_manager, "_thread_engines")- assert isinstance(db_manager._thread_engines, dict)- assert len(db_manager._thread_engines) == 0-- def test_thread_engine_lock_exists(self, db_manager):- """Thread engine lock should exist for thread safety."""- assert hasattr(db_manager, "_thread_engine_lock")- assert isinstance(- db_manager._thread_engine_lock, type(threading.Lock())- )-- def test_engine_key_format(self, db_manager_with_user):- """Engine key should be a (username, thread_id) tuple."""- db_manager, username, password = db_manager_with_user-- # Create a thread-safe session- session = db_manager.create_thread_safe_session_for_metrics(- username, password- )- session.close()-- # Check that engine was stored with correct key format (tuple)- assert len(db_manager._thread_engines) == 1- key = list(db_manager._thread_engines.keys())[0]- assert isinstance(key, tuple)- assert len(key) == 2- assert key == (username, threading.get_ident())-- def test_engine_stored_after_creation(self, db_manager_with_user):- """Engine should be stored in _thread_engines after creation."""- db_manager, username, password = db_manager_with_user-- assert len(db_manager._thread_engines) == 0-- session = db_manager.create_thread_safe_session_for_metrics(- username, password- )- session.close()-- assert len(db_manager._thread_engines) == 1---class TestEngineReuseWithinThread:- """Test that same thread reuses engine instead of creating new ones."""-- def test_same_thread_reuses_engine(self, db_manager_with_user):- """Multiple calls from same thread should reuse the same engine."""- db_manager, username, password = db_manager_with_user-- # First call creates engine- session1 = db_manager.create_thread_safe_session_for_metrics(- username, password- )- assert len(db_manager._thread_engines) == 1- engine_key = list(db_manager._thread_engines.keys())[0]- engine1 = db_manager._thread_engines[engine_key]- session1.close()-- # Second call should reuse same engine- session2 = db_manager.create_thread_safe_session_for_metrics(- username, password- )- assert len(db_manager._thread_engines) == 1 # Still only 1 engine- engine2 = db_manager._thread_engines[engine_key]- assert engine1 is engine2 # Same engine object- session2.close()-- # Third call should also reuse- session3 = db_manager.create_thread_safe_session_for_metrics(- username, password- )- assert len(db_manager._thread_engines) == 1- session3.close()-- def test_engine_validity_check(self, db_manager_with_user):- """Engine should be validated before reuse."""- db_manager, username, password = db_manager_with_user-- # Create initial session- session1 = db_manager.create_thread_safe_session_for_metrics(- username, password- )- session1.close()-- # Engine should still be valid and reused- session2 = db_manager.create_thread_safe_session_for_metrics(- username, password- )-- # Verify session works- result = session2.execute(text("SELECT 1"))- assert result.scalar() == 1- session2.close()---class TestThreadIsolation:- """Test that different threads get different engines."""-- def test_different_threads_different_engines(self, db_manager_with_user):- """Different threads should have different engines."""- db_manager, username, password = db_manager_with_user- results = {"thread_ids": [], "engine_keys": []}- errors = []-- def worker():- try:- thread_id = threading.get_ident()- session = db_manager.create_thread_safe_session_for_metrics(- username, password- )- # Verify session works- result = session.execute(text("SELECT 1"))- assert result.scalar() == 1- session.close()-- results["thread_ids"].append(thread_id)- expected_key = (username, thread_id)- results["engine_keys"].append(expected_key)- except Exception as e:- errors.append(str(e))-- # Run in multiple threads- threads = []- for _ in range(3):- t = threading.Thread(target=worker)- threads.append(t)- t.start()-- for t in threads:- t.join(timeout=10)-- assert len(errors) == 0, f"Errors: {errors}"- assert len(results["thread_ids"]) == 3-- # Each thread should have created its own engine- assert len(set(results["thread_ids"])) == 3 # All unique thread IDs-- # All engine keys should exist- for key in results["engine_keys"]:- assert key in db_manager._thread_engines-- def test_concurrent_engine_creation(self, db_manager_with_user):- """Multiple threads creating engines concurrently should not conflict."""- db_manager, username, password = db_manager_with_user- num_threads = 5- results = []- errors = []- barrier = threading.Barrier(num_threads)-- def worker(worker_id):- try:- barrier.wait(timeout=5) # Synchronize start- session = db_manager.create_thread_safe_session_for_metrics(- username, password- )- result = session.execute(text("SELECT 1"))- results.append((worker_id, result.scalar()))- session.close()- except Exception as e:- errors.append((worker_id, str(e)))-- with ThreadPoolExecutor(max_workers=num_threads) as executor:- futures = [executor.submit(worker, i) for i in range(num_threads)]- for future in as_completed(futures, timeout=30):- future.result() # Raise any exceptions-- assert len(errors) == 0, f"Errors: {errors}"- assert len(results) == num_threads- assert all(r[1] == 1 for r in results)---class TestCleanupThreadEngines:- """Test cleanup_thread_engines() method."""-- def test_cleanup_by_username_only(self, db_manager_with_user):- """cleanup_thread_engines(username=x) should clean all engines for user."""- db_manager, username, password = db_manager_with_user- engine_keys = []- barrier = threading.Barrier(3)-- def create_engine_in_thread():- barrier.wait(timeout=5) # Synchronize start- session = db_manager.create_thread_safe_session_for_metrics(- username, password- )- key = (username, threading.get_ident())- engine_keys.append(key)- session.close()-- # Create engines in multiple threads- threads = []- for _ in range(3):- t = threading.Thread(target=create_engine_in_thread)- threads.append(t)- t.start()-- for t in threads:- t.join(timeout=10)-- # Verify engines were created (at least 2 - timing can cause variations)- assert len(db_manager._thread_engines) >= 2-- # Cleanup by username- db_manager.cleanup_thread_engines(username=username)-- # All engines for this user should be removed- remaining_keys = list(db_manager._thread_engines.keys())- for key in remaining_keys:- assert key[0] != username # First element of tuple is username-- def test_cleanup_by_thread_id_only(self, db_manager_with_user):- """cleanup_thread_engines(thread_id=x) should clean engines for thread."""- db_manager, username, password = db_manager_with_user-- # Create engine in main thread- session = db_manager.create_thread_safe_session_for_metrics(- username, password- )- main_thread_id = threading.get_ident()- main_key = (username, main_thread_id)- session.close()-- assert main_key in db_manager._thread_engines-- # Cleanup by thread ID- db_manager.cleanup_thread_engines(thread_id=main_thread_id)-- # Engine for this thread should be removed- assert main_key not in db_manager._thread_engines-- def test_cleanup_by_both_username_and_thread_id(self, db_manager_with_user):- """cleanup_thread_engines(username, thread_id) should clean specific engine."""- db_manager, username, password = db_manager_with_user-- # Create engine- session = db_manager.create_thread_safe_session_for_metrics(- username, password- )- thread_id = threading.get_ident()- key = (username, thread_id)- session.close()-- assert key in db_manager._thread_engines-- # Cleanup with both parameters- db_manager.cleanup_thread_engines(- username=username, thread_id=thread_id- )-- assert key not in db_manager._thread_engines-- def test_cleanup_current_thread_default(self, db_manager_with_user):- """cleanup_thread_engines() with no args should clean current thread."""- db_manager, username, password = db_manager_with_user-- # Create engine- session = db_manager.create_thread_safe_session_for_metrics(- username, password- )- key = (username, threading.get_ident())- session.close()-- assert key in db_manager._thread_engines-- # Cleanup with no args (defaults to current thread)- db_manager.cleanup_thread_engines()-- assert key not in db_manager._thread_engines---class TestCleanupAllThreadEngines:- """Test cleanup_all_thread_engines() method."""-- def test_cleanup_all_disposes_all_engines(self, db_manager_with_user):- """cleanup_all_thread_engines() should dispose and clear all engines."""- db_manager, username, password = db_manager_with_user- barrier = threading.Barrier(4) # 3 worker threads + main thread-- def create_engine_in_thread():- barrier.wait(timeout=5) # Synchronize start- session = db_manager.create_thread_safe_session_for_metrics(- username, password- )- session.close()-- # Create engines in multiple threads- threads = []- for _ in range(3):- t = threading.Thread(target=create_engine_in_thread)- threads.append(t)- t.start()-- # Main thread also participates in barrier- barrier.wait(timeout=5)- session = db_manager.create_thread_safe_session_for_metrics(- username, password- )- session.close()-- for t in threads:- t.join(timeout=10)-- # Verify engines were created (at least 3 - timing can cause variations)- assert len(db_manager._thread_engines) >= 3-- # Cleanup all- db_manager.cleanup_all_thread_engines()-- # All engines should be removed- assert len(db_manager._thread_engines) == 0-- def test_cleanup_all_handles_errors(self, db_manager_with_user):- """cleanup_all_thread_engines() should handle disposal errors gracefully."""- db_manager, username, password = db_manager_with_user-- # Create engine- session = db_manager.create_thread_safe_session_for_metrics(- username, password- )- session.close()-- # Should not raise even if disposal fails- db_manager.cleanup_all_thread_engines()- assert len(db_manager._thread_engines) == 0---class TestCleanupDeadThreadEngines:- """Test cleanup_dead_thread_engines() method."""-- def test_removes_dead_thread_entries(self, db_manager_with_user):- """Engines for dead threads should be removed."""- db_manager, username, password = db_manager_with_user- dead_thread_ids = []- # Use a barrier to ensure all 3 threads are alive simultaneously- # before any of them exits. This prevents Python from recycling- # thread IDs (which causes fewer than 3 unique entries in- # _thread_engines).- barrier = threading.Barrier(3)-- def create_engine_in_thread():- session = db_manager.create_thread_safe_session_for_metrics(- username, password- )- dead_thread_ids.append(threading.get_ident())- session.close()- barrier.wait(timeout=10)-- # Create engines in threads that will die- threads = []- for _ in range(3):- t = threading.Thread(target=create_engine_in_thread)- threads.append(t)- t.start()-- for t in threads:- t.join(timeout=10)-- # Threads are dead now, but engines remain- assert len(db_manager._thread_engines) >= 3-- # Sweep dead thread engines- db_manager.cleanup_dead_thread_engines()-- # Dead thread entries should be gone- for tid in dead_thread_ids:- assert (username, tid) not in db_manager._thread_engines-- def test_preserves_alive_thread_entries(self, db_manager_with_user):- """Engines for alive threads should be preserved."""- db_manager, username, password = db_manager_with_user-- # Create engine in main thread (which is alive)- session = db_manager.create_thread_safe_session_for_metrics(- username, password- )- main_key = (username, threading.get_ident())- session.close()-- assert main_key in db_manager._thread_engines-- # Sweep should not remove it- db_manager.cleanup_dead_thread_engines()-- assert main_key in db_manager._thread_engines-- def test_mixed_alive_and_dead(self, db_manager_with_user):- """Should remove dead entries while preserving alive ones."""- db_manager, username, password = db_manager_with_user-- # Create engine in main thread (alive)- session = db_manager.create_thread_safe_session_for_metrics(- username, password- )- main_key = (username, threading.get_ident())- session.close()-- # Create engines in threads that will die- def create_engine_in_thread():- s = db_manager.create_thread_safe_session_for_metrics(- username, password- )- s.close()-- dead_threads = []- for _ in range(2):- t = threading.Thread(target=create_engine_in_thread)- dead_threads.append(t)- t.start()-- for t in dead_threads:- t.join(timeout=10)-- total_before = len(db_manager._thread_engines)- assert total_before >= 3-- db_manager.cleanup_dead_thread_engines()-- # Main thread engine preserved, dead ones removed- assert main_key in db_manager._thread_engines- assert len(db_manager._thread_engines) == 1-- def test_noop_when_no_dead_threads(self, db_manager_with_user):- """Should be a no-op when all threads are alive."""- db_manager, username, password = db_manager_with_user-- session = db_manager.create_thread_safe_session_for_metrics(- username, password- )- session.close()-- count_before = len(db_manager._thread_engines)- db_manager.cleanup_dead_thread_engines()- assert len(db_manager._thread_engines) == count_before---class TestMaybeSweepDeadEngines:- """Test maybe_sweep_dead_engines() rate limiting."""-- def test_sweeps_on_first_call(self, db_manager_with_user):- """First call should always sweep (initial _last_sweep_time is 0)."""- db_manager, username, password = db_manager_with_user-- # Create an engine in a dead thread- def create_engine_in_thread():- s = db_manager.create_thread_safe_session_for_metrics(- username, password- )- s.close()-- t = threading.Thread(target=create_engine_in_thread)- t.start()- t.join(timeout=10)-- assert len(db_manager._thread_engines) >= 1-- db_manager.maybe_sweep_dead_engines(interval=60.0)-- # Dead thread engine should have been swept- # Only alive thread engines remain (if any)- alive_ids = {th.ident for th in threading.enumerate()}- for key in db_manager._thread_engines:- assert key[1] in alive_ids-- def test_skips_within_interval(self, db_manager_with_user):- """Second call within interval should be skipped."""-- db_manager, username, password = db_manager_with_user-- # First call sets _last_sweep_time- db_manager.maybe_sweep_dead_engines(interval=60.0)- first_sweep_time = db_manager._last_sweep_time-- # Create an engine in a dead thread- def create_engine_in_thread():- s = db_manager.create_thread_safe_session_for_metrics(- username, password- )- s.close()-- t = threading.Thread(target=create_engine_in_thread)- t.start()- t.join(timeout=10)-- count_after_dead = len(db_manager._thread_engines)-- # Second call within interval should be a no-op- db_manager.maybe_sweep_dead_engines(interval=60.0)-- # Dead engine should NOT have been swept (interval not elapsed)- assert len(db_manager._thread_engines) == count_after_dead- assert db_manager._last_sweep_time == first_sweep_time-- def test_sweeps_after_interval(self, db_manager_with_user):- """Call after interval has elapsed should sweep."""- import time-- db_manager, username, password = db_manager_with_user-- # First call sets _last_sweep_time- db_manager.maybe_sweep_dead_engines(interval=60.0)-- # Create dead thread engine- def create_engine_in_thread():- s = db_manager.create_thread_safe_session_for_metrics(- username, password- )- s.close()-- t = threading.Thread(target=create_engine_in_thread)- t.start()- t.join(timeout=10)-- assert len(db_manager._thread_engines) >= 1-- # Backdate _last_sweep_time to simulate interval elapsing- # (avoids flaky time.sleep-based tests)- db_manager._last_sweep_time = time.monotonic() - 60.1-- # Should sweep now since interval has "elapsed"- db_manager.maybe_sweep_dead_engines(interval=60.0)-- # Dead engine should have been swept- alive_ids = {th.ident for th in threading.enumerate()}- for key in db_manager._thread_engines:- assert key[1] in alive_ids---class TestCloseUserDatabaseCleansThreadEngines:- """Test that close_user_database also cleans up thread engines."""-- def test_close_user_database_cleans_thread_engines(- self, db_manager_with_user- ):- """close_user_database should also cleanup thread engines for that user."""- db_manager, username, password = db_manager_with_user-- # Create thread engine- session = db_manager.create_thread_safe_session_for_metrics(- username, password- )- key = (username, threading.get_ident())- session.close()-- assert key in db_manager._thread_engines-- # Close user database- db_manager.close_user_database(username)-- # Thread engine for this user should also be cleaned- assert key not in db_manager._thread_engines---class TestConnectionLeakPrevention:- """Test that connection leak is prevented with multiple operations."""-- def test_multiple_session_calls_no_engine_leak(self, db_manager_with_user):- """Multiple session calls should not create multiple engines per thread."""- db_manager, username, password = db_manager_with_user-- # Make many session calls- for i in range(10):- session = db_manager.create_thread_safe_session_for_metrics(- username, password- )- result = session.execute(text("SELECT 1"))- assert result.scalar() == 1- session.close()-- # Should still only have 1 engine for this thread- assert len(db_manager._thread_engines) == 1-- def test_memory_usage_includes_thread_engines(self, db_manager_with_user):- """get_memory_usage should include thread engines count."""- db_manager, username, password = db_manager_with_user-- # Create thread engine- session = db_manager.create_thread_safe_session_for_metrics(- username, password- )- session.close()-- stats = db_manager.get_memory_usage()- assert "thread_engines" in stats- assert stats["thread_engines"] >= 1---class TestNonexistentDatabaseHandling:- """Test error handling for non-existent databases."""-- def test_create_thread_safe_session_nonexistent_db(self, db_manager):- """Should raise ValueError for non-existent database."""- with pytest.raises(ValueError, match="No database found"):- db_manager.create_thread_safe_session_for_metrics(- "nonexistent_user", "password"- )---class TestStaleEngineHandling:- """Test handling of stale/invalid engines."""-- def test_stale_engine_recreated(self, db_manager_with_user):- """Stale engines should be detected and recreated."""- db_manager, username, password = db_manager_with_user-- # Create initial session- session1 = db_manager.create_thread_safe_session_for_metrics(- username, password- )- session1.close()-- key = (username, threading.get_ident())- original_engine = db_manager._thread_engines[key]- original_engine_id = id(original_engine)-- # Mock the engine's connect to raise an exception (simulating stale engine)- def failing_connect(*args, **kwargs):- raise Exception("Simulated stale engine connection failure")-- original_engine.connect = failing_connect-- # Next call should detect staleness and recreate- session2 = db_manager.create_thread_safe_session_for_metrics(- username, password- )-- # Should work with new engine- result = session2.execute(text("SELECT 1"))- assert result.scalar() == 1- session2.close()-- # Engine should have been replaced (different object ID)- new_engine = db_manager._thread_engines[key]- assert id(new_engine) != original_engine_id---class TestMultipleUsersThreadEngines:- """Test thread engines with multiple users."""-- def test_different_users_different_engines(- self, db_manager, temp_data_dir, monkeypatch- ):- """Different users should have separate engines even in same thread."""- monkeypatch.setenv("LDR_DATA_DIR", str(temp_data_dir))- init_auth_database()-- # Create two users- auth_db = get_auth_db_session()- user1 = User(username="user1")- user2 = User(username="user2")- auth_db.add(user1)- auth_db.add(user2)- auth_db.commit()- auth_db.close()-- # Create databases for both users- db_manager.create_user_database("user1", "pass1")- db_manager.create_user_database("user2", "pass2")-- # Create thread engines for both- session1 = db_manager.create_thread_safe_session_for_metrics(- "user1", "pass1"- )- session2 = db_manager.create_thread_safe_session_for_metrics(- "user2", "pass2"- )-- session1.close()- session2.close()-- # Should have 2 engines (one per user)- assert len(db_manager._thread_engines) == 2-- thread_id = threading.get_ident()- assert ("user1", thread_id) in db_manager._thread_engines- assert ("user2", thread_id) in db_manager._thread_engines-- # Cleanup- db_manager.close_user_database("user1")- db_manager.close_user_database("user2")---class TestConnectionPoolExhaustionRegression:- """- Regression test for the connection pool exhaustion bug.-- Original bug: create_thread_safe_session_for_metrics() created a new- orphaned SQLAlchemy engine on every call. After ~4 user registrations- (4 registrations × 3 engines each = 12+ leaked connections), the- connection pool was exhausted, causing critical-ui-tests failures.-- Fix: Track engines in _thread_engines dict and reuse them per thread.- """-- def test_multiple_registrations_no_pool_exhaustion(- self, db_manager, temp_data_dir, monkeypatch- ):- """- Simulate multiple user registrations creating metric sessions.-- Before the fix, each registration would leak ~3 engines.- After the fix, engines are reused per thread.- """- monkeypatch.setenv("LDR_DATA_DIR", str(temp_data_dir))- init_auth_database()-- num_users = 6 # More than the ~4 that would exhaust the pool before- users_created = []-- for i in range(num_users):- username = f"reguser{i}"- password = f"Password{i}!"-- # Create auth user- auth_db = get_auth_db_session()- user = User(username=username)- auth_db.add(user)- auth_db.commit()- auth_db.close()-- # Create user database- db_manager.create_user_database(username, password)- users_created.append((username, password))-- # Simulate multiple metric session calls per registration- # (mimics what happens during user registration flow)- for _ in range(3):- session = db_manager.create_thread_safe_session_for_metrics(- username, password- )- result = session.execute(text("SELECT 1"))- assert result.scalar() == 1- session.close()-- # Key assertion: We should have exactly num_users engines- # (one per user in this thread), NOT num_users * 3 engines- thread_id = threading.get_ident()- user_engines_in_thread = [- key for key in db_manager._thread_engines if key[1] == thread_id- ]- assert len(user_engines_in_thread) == num_users-- # Total engines should be bounded, not growing unbounded- assert len(db_manager._thread_engines) == num_users-- # Cleanup- for username, _ in users_created:- db_manager.close_user_database(username)-- # After cleanup, no thread engines should remain- assert len(db_manager._thread_engines) == 0-- def test_concurrent_registrations_bounded_engines(- self, db_manager, temp_data_dir, monkeypatch- ):- """- Simulate concurrent user registrations from multiple threads.-- Each thread should have its own engine per user, but engines- should be reused within each thread.- """- monkeypatch.setenv("LDR_DATA_DIR", str(temp_data_dir))- init_auth_database()-- num_threads = 4- sessions_per_thread = 5- username = "concurrent_user"- password = "ConcurrentPass123!"-- # Create single user- auth_db = get_auth_db_session()- user = User(username=username)- auth_db.add(user)- auth_db.commit()- auth_db.close()- db_manager.create_user_database(username, password)-- errors = []- thread_ids = []- barrier = threading.Barrier(num_threads)-- def worker():- try:- barrier.wait(timeout=10)- thread_ids.append(threading.get_ident())-- # Each thread makes multiple session calls- for _ in range(sessions_per_thread):- session = db_manager.create_thread_safe_session_for_metrics(- username, password- )- result = session.execute(text("SELECT 1"))- assert result.scalar() == 1- session.close()- except Exception as e:- errors.append(str(e))-- threads = [threading.Thread(target=worker) for _ in range(num_threads)]- for t in threads:- t.start()- for t in threads:- t.join(timeout=30)-- assert len(errors) == 0, f"Errors: {errors}"-- # Key assertion: Should have exactly num_threads engines- # (one per thread), NOT num_threads * sessions_per_thread- assert len(db_manager._thread_engines) == num_threads-- # Each thread should have exactly one engine for this user- for tid in thread_ids:- assert (username, tid) in db_manager._thread_engines-- # Cleanup- db_manager.close_user_database(username)- assert len(db_manager._thread_engines) == 0---class TestThreadLocalSessionIntegration:- """- Integration tests for thread_local_session.py cleanup integration.-- These tests verify that the ThreadLocalSessionManager properly cleans up- thread engines when sessions are cleaned up.-- Note: These tests patch the global db_manager in thread_local_session module- to use our test fixture's db_manager instance.- """-- def test_cleanup_thread_cleans_engine(- self, db_manager, temp_data_dir, monkeypatch- ):- """- cleanup_thread() should clean up both the session AND the thread engine.-- This tests the integration between thread_local_session.py and- encrypted_db.py - when _cleanup_thread_session() is called, it should- also call db_manager.cleanup_thread_engines().- """- import local_deep_research.database.thread_local_session as tls_module- from local_deep_research.database.thread_local_session import (- ThreadLocalSessionManager,- )-- monkeypatch.setenv("LDR_DATA_DIR", str(temp_data_dir))- # Patch the global db_manager in thread_local_session module- monkeypatch.setattr(tls_module, "db_manager", db_manager)-- init_auth_database()-- # Create user- auth_db = get_auth_db_session()- user = User(username="integration_user")- auth_db.add(user)- auth_db.commit()- auth_db.close()-- username = "integration_user"- password = "IntegrationPass123!"- db_manager.create_user_database(username, password)-- # Create a fresh ThreadLocalSessionManager that uses our db_manager- session_manager = ThreadLocalSessionManager()-- # Get a session (this creates an engine in db_manager._thread_engines)- session = session_manager.get_session(username, password)- assert session is not None-- thread_id = threading.get_ident()- engine_key = (username, thread_id)-- # Verify engine was created- assert engine_key in db_manager._thread_engines-- # Cleanup the thread session- session_manager.cleanup_thread()-- # Verify engine was also cleaned up- assert engine_key not in db_manager._thread_engines-- # Cleanup- db_manager.close_user_database(username)-- def test_cleanup_all_cleans_all_engines(- self, db_manager, temp_data_dir, monkeypatch- ):- """- cleanup_all() should clean up all thread engines via cleanup_all_thread_engines().- """- import local_deep_research.database.thread_local_session as tls_module- from local_deep_research.database.thread_local_session import (- ThreadLocalSessionManager,- )-- monkeypatch.setenv("LDR_DATA_DIR", str(temp_data_dir))- monkeypatch.setattr(tls_module, "db_manager", db_manager)-- init_auth_database()-- # Create user- auth_db = get_auth_db_session()- user = User(username="cleanup_all_user")- auth_db.add(user)- auth_db.commit()- auth_db.close()-- username = "cleanup_all_user"- password = "CleanupAllPass123!"- db_manager.create_user_database(username, password)-- session_manager = ThreadLocalSessionManager()- engines_created = []-- # Create sessions in multiple threads- def create_session_in_thread():- session = session_manager.get_session(username, password)- if session:- engines_created.append((username, threading.get_ident()))-- threads = []- for _ in range(3):- t = threading.Thread(target=create_session_in_thread)- threads.append(t)- t.start()-- for t in threads:- t.join(timeout=10)-- # Also create one in main thread- _session = session_manager.get_session(username, password)- assert _session is not None- engines_created.append((username, threading.get_ident()))-- # Verify engines were created- assert len(db_manager._thread_engines) >= 1-- # Call cleanup_all- session_manager.cleanup_all()-- # All thread engines should be cleaned- assert len(db_manager._thread_engines) == 0-- # Cleanup- db_manager.close_user_database(username)-- def test_get_metrics_session_creates_tracked_engine(- self, db_manager, temp_data_dir, monkeypatch- ):- """- get_metrics_session() should create an engine that is properly tracked.- """- import local_deep_research.database.thread_local_session as tls_module- from local_deep_research.database.thread_local_session import (- ThreadLocalSessionManager,- )-- monkeypatch.setenv("LDR_DATA_DIR", str(temp_data_dir))- monkeypatch.setattr(tls_module, "db_manager", db_manager)-- init_auth_database()-- # Create user- auth_db = get_auth_db_session()- user = User(username="metrics_user")- auth_db.add(user)- auth_db.commit()- auth_db.close()-- username = "metrics_user"- password = "MetricsPass123!"- db_manager.create_user_database(username, password)-- # Create fresh session manager (uses patched db_manager)- session_manager = ThreadLocalSessionManager()- session = session_manager.get_session(username, password)- assert session is not None-- thread_id = threading.get_ident()- engine_key = (username, thread_id)-- # Verify engine is tracked- assert engine_key in db_manager._thread_engines-- # Verify session works- result = session.execute(text("SELECT 1"))- assert result.scalar() == 1-- # Cleanup current thread- session_manager.cleanup_thread()-- # Engine should be cleaned up- assert engine_key not in db_manager._thread_engines-- # Cleanup- db_manager.close_user_database(username)-- def test_thread_session_context_creates_tracked_engine(- self, db_manager, temp_data_dir, monkeypatch- ):- """- ThreadSessionContext should create an engine that can be cleaned up.- """- import local_deep_research.database.thread_local_session as tls_module- from local_deep_research.database.thread_local_session import (- ThreadLocalSessionManager,- ThreadSessionContext,- )-- monkeypatch.setenv("LDR_DATA_DIR", str(temp_data_dir))- monkeypatch.setattr(tls_module, "db_manager", db_manager)- # Also need to patch the global thread_session_manager used by ThreadSessionContext- patched_session_manager = ThreadLocalSessionManager()- monkeypatch.setattr(- tls_module, "thread_session_manager", patched_session_manager- )-- init_auth_database()-- # Create user- auth_db = get_auth_db_session()- user = User(username="context_user")- auth_db.add(user)- auth_db.commit()- auth_db.close()-- username = "context_user"- password = "ContextPass123!"- db_manager.create_user_database(username, password)-- thread_id = threading.get_ident()- engine_key = (username, thread_id)-- # Use context manager- with ThreadSessionContext(username, password) as session:- assert session is not None- result = session.execute(text("SELECT 1"))- assert result.scalar() == 1-- # Engine should be tracked while in context- assert engine_key in db_manager._thread_engines-- # Engine still tracked after context (by design - cleanup on thread end)- assert engine_key in db_manager._thread_engines-- # Manual cleanup via the patched session manager- patched_session_manager.cleanup_thread()- assert engine_key not in db_manager._thread_engines-- # Cleanup- db_manager.close_user_database(username)---class TestCleanupDeadThreadCredentials:- """Test that dead thread credentials are swept alongside engines."""-- def test_cleanup_dead_thread_credentials(- self, db_manager, temp_data_dir, monkeypatch- ):- """Credentials for dead threads should be removed by cleanup_dead_threads()."""- import local_deep_research.database.thread_local_session as tls_module- from local_deep_research.database.thread_local_session import (- ThreadLocalSessionManager,- )-- monkeypatch.setenv("LDR_DATA_DIR", str(temp_data_dir))- monkeypatch.setattr(tls_module, "db_manager", db_manager)-- init_auth_database()-- auth_db = get_auth_db_session()- user = User(username="cred_user")- auth_db.add(user)- auth_db.commit()- auth_db.close()-- username = "cred_user"- password = "CredPass123!"- db_manager.create_user_database(username, password)-- session_manager = ThreadLocalSessionManager()- dead_thread_ids = []-- def create_session_in_thread():- session = session_manager.get_session(username, password)- if session:- dead_thread_ids.append(threading.get_ident())-- # Create sessions in threads that will die- threads = []- for _ in range(3):- t = threading.Thread(target=create_session_in_thread)- threads.append(t)- t.start()- for t in threads:- t.join(timeout=10)-- # Verify credentials were tracked for those threads- with session_manager._lock:- for tid in dead_thread_ids:- assert tid in session_manager._thread_credentials-- # Verify engines exist for dead threads- for tid in dead_thread_ids:- assert (username, tid) in db_manager._thread_engines-- # Call cleanup_dead_threads on the session manager- session_manager.cleanup_dead_threads()- # Also clean up engines- db_manager.cleanup_dead_thread_engines()-- # Dead thread credentials should be swept- with session_manager._lock:- for tid in dead_thread_ids:- assert tid not in session_manager._thread_credentials-- # Dead thread engines should be swept- for tid in dead_thread_ids:- assert (username, tid) not in db_manager._thread_engines-- db_manager.close_user_database(username)-- def test_module_cleanup_dead_threads_calls_both(- self, db_manager, temp_data_dir, monkeypatch- ):- """Module-level cleanup_dead_threads() should sweep both credentials and engines."""- import local_deep_research.database.thread_local_session as tls_module- from local_deep_research.database.thread_local_session import (- ThreadLocalSessionManager,- )-- monkeypatch.setenv("LDR_DATA_DIR", str(temp_data_dir))- monkeypatch.setattr(tls_module, "db_manager", db_manager)-- init_auth_database()-- auth_db = get_auth_db_session()- user = User(username="module_user")- auth_db.add(user)- auth_db.commit()- auth_db.close()-- username = "module_user"- password = "ModulePass123!"- db_manager.create_user_database(username, password)-- # Use a fresh session manager and patch it as the global- session_manager = ThreadLocalSessionManager()- monkeypatch.setattr(- tls_module, "thread_session_manager", session_manager- )-- dead_thread_ids = []-- def create_session_in_thread():- session = session_manager.get_session(username, password)- if session:- dead_thread_ids.append(threading.get_ident())-- threads = []- for _ in range(2):- t = threading.Thread(target=create_session_in_thread)- threads.append(t)- t.start()- for t in threads:- t.join(timeout=10)-- # Verify both credentials and engines exist for dead threads- with session_manager._lock:- for tid in dead_thread_ids:- assert tid in session_manager._thread_credentials- for tid in dead_thread_ids:- assert (username, tid) in db_manager._thread_engines-- # Call the module-level function (sweeps both).- # Reset rate-limiter so the sweep is not skipped.- db_manager._last_sweep_time = 0.0- tls_module.cleanup_dead_threads()-- # Both should be swept- with session_manager._lock:- for tid in dead_thread_ids:- assert tid not in session_manager._thread_credentials- for tid in dead_thread_ids:- assert (username, tid) not in db_manager._thread_engines-- db_manager.close_user_database(username)diff --git a/tests/database/test_thread_local_session.py b/tests/database/test_thread_local_session.pyindex 9a5a9f4105..b215b248fc 100644--- a/tests/database/test_thread_local_session.py+++ b/tests/database/test_thread_local_session.py@@ -328,12 +328,10 @@ class TestThreadLocalSessionManager:2: ("user2", "pass2"),}- with patch(- "local_deep_research.database.thread_local_session.db_manager"- ) as mock_db:- manager.cleanup_all()-- mock_db.cleanup_all_thread_engines.assert_called_once()+ # cleanup_all should iterate credentials and call cleanup_thread+ # without touching any engine machinery.+ manager.cleanup_all()+ assert manager._thread_credentials == {}class TestThreadSessionContext:diff --git a/tests/database/test_thread_local_session_coverage.py b/tests/database/test_thread_local_session_coverage.pyindex d108e5f8e1..b654f48c1e 100644--- a/tests/database/test_thread_local_session_coverage.py+++ b/tests/database/test_thread_local_session_coverage.py@@ -90,38 +90,17 @@ class TestCleanupDeadThreads:assert dead_tid not in mgr._thread_credentialsdef test_module_level_cleanup_dead_threads(self):- """Module-level cleanup_dead_threads calls both managers."""- with (- patch(f"{MODULE}.thread_session_manager") as mock_mgr,- patch(f"{MODULE}.db_manager") as mock_db,- ):- cleanup_dead_threads()- mock_mgr.cleanup_dead_threads.assert_called_once()- mock_db.maybe_sweep_dead_engines.assert_called_once()-- def test_module_level_cleanup_engine_failure_does_not_block_session_cleanup(- self,- ):- """If engine sweep fails, session sweep still runs."""- with (- patch(f"{MODULE}.thread_session_manager") as mock_mgr,- patch(f"{MODULE}.db_manager") as mock_db,- ):- mock_db.maybe_sweep_dead_engines.side_effect = RuntimeError("boom")+ """Module-level cleanup_dead_threads delegates to session manager."""+ with patch(f"{MODULE}.thread_session_manager") as mock_mgr:cleanup_dead_threads()mock_mgr.cleanup_dead_threads.assert_called_once()- def test_module_level_cleanup_session_failure_does_not_block_engine_cleanup(- self,- ):- """If session sweep fails, engine sweep still runs."""- with (- patch(f"{MODULE}.thread_session_manager") as mock_mgr,- patch(f"{MODULE}.db_manager") as mock_db,- ):+ def test_module_level_cleanup_session_failure_swallowed(self):+ """If session sweep fails, the wrapper does not raise."""+ with patch(f"{MODULE}.thread_session_manager") as mock_mgr:mock_mgr.cleanup_dead_threads.side_effect = RuntimeError("boom")+ # Should not raisecleanup_dead_threads()- mock_db.maybe_sweep_dead_engines.assert_called_once()class TestThreadCleanupContextManager:diff --git a/tests/database/test_thread_local_session_deep_coverage.py b/tests/database/test_thread_local_session_deep_coverage.pyindex 3515557462..7305740652 100644--- a/tests/database/test_thread_local_session_deep_coverage.py+++ b/tests/database/test_thread_local_session_deep_coverage.py@@ -114,21 +114,11 @@ class TestCleanupAll:called_with.append(tid)mgr.cleanup_thread = track_cleanup- with patch(f"{MODULE}.db_manager"):- mgr.cleanup_all()+ mgr.cleanup_all()# Both thread IDs should have been cleaned upassert len(called_with) == 2- def test_cleanup_all_also_cleans_db_manager(self):- mgr = _make_manager()- with (- patch.object(mgr, "cleanup_thread"),- patch(f"{MODULE}.db_manager") as mock_db,- ):- mgr.cleanup_all()- mock_db.cleanup_all_thread_engines.assert_called_once()-# ---------------------------------------------------------------------------# Module-level helpers