~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: prevent file descriptor exhaustion (too many open files) (#2591)
LearningCircuit2ef2473bb5a8
diff --git a/src/local_deep_research/advanced_search_system/strategies/base_strategy.py b/src/local_deep_research/advanced_search_system/strategies/base_strategy.pyindex 6f856a8349..c5b5c157a3 100644--- a/src/local_deep_research/advanced_search_system/strategies/base_strategy.py+++ b/src/local_deep_research/advanced_search_system/strategies/base_strategy.py@@ -46,6 +46,27 @@ class BaseSearchStrategy(ABC):self.settings_snapshot = settings_snapshot or {}self.search_original_query = search_original_query+ def close(self):+ """Release any persistent resources held by this strategy.++ Override this method if your strategy creates persistent resources+ in __init__ (e.g. ThreadPoolExecutor, HTTP sessions).++ Currently, two strategies need this:+ - ConstraintParallelStrategy: holds search_executor ++ evaluation_executor+ - ConcurrentDualConfidenceStrategy: holds evaluation_executor++ The default source-based strategy uses context-managed ('with')+ executors that clean up automatically, so no override is needed.++ Note: This is called by AdvancedSearchSystem.close() which is+ called in run_research_process()'s finally block. Strategies+ should also clean up in their own finally blocks (as they already+ do) — this close() is a second line of defense.+ """+ pass+def get_setting(self, key: str, default=None):"""Get a setting value from the snapshot."""if key in self.settings_snapshot:diff --git a/src/local_deep_research/advanced_search_system/strategies/concurrent_dual_confidence_strategy.py b/src/local_deep_research/advanced_search_system/strategies/concurrent_dual_confidence_strategy.pyindex fa24786dce..c2778b1523 100644--- a/src/local_deep_research/advanced_search_system/strategies/concurrent_dual_confidence_strategy.py+++ b/src/local_deep_research/advanced_search_system/strategies/concurrent_dual_confidence_strategy.py@@ -88,6 +88,21 @@ class ConcurrentDualConfidenceStrategy(DualConfidenceWithRejectionStrategy):# Search stateself.state: Optional[SearchState] = None+ def close(self):+ """Shut down persistent thread pool executor.++ Also shut down in find_relevant_information()'s finally block, but+ this handles the edge case where the method is never called.++ Uses wait=False because wait=True would block the research thread.+ Safe due to double-cleanup pattern; shutdown() is idempotent.+ """+ if hasattr(self, "evaluation_executor"):+ try:+ self.evaluation_executor.shutdown(wait=False)+ except Exception:+ logger.exception("Error shutting down evaluation executor")+def find_relevant_information(self):"""Override to use concurrent search and evaluation."""# Initialize statediff --git a/src/local_deep_research/advanced_search_system/strategies/constraint_parallel_strategy.py b/src/local_deep_research/advanced_search_system/strategies/constraint_parallel_strategy.pyindex b17e0049cc..b2040e69f6 100644--- a/src/local_deep_research/advanced_search_system/strategies/constraint_parallel_strategy.py+++ b/src/local_deep_research/advanced_search_system/strategies/constraint_parallel_strategy.py@@ -104,6 +104,30 @@ class ConstraintParallelStrategy(DualConfidenceWithRejectionStrategy):# Search stateself.state: Optional[ConstraintSearchState] = None+ def close(self):+ """Shut down persistent thread pool executors.++ These executors are also shut down in find_relevant_information()'s+ finally block, but this close() handles the edge case where the+ strategy is instantiated but find_relevant_information() is never+ called (or raises before reaching its finally block).++ Uses wait=False because wait=True would block the research thread+ waiting for all submitted tasks to complete. This is safe because+ the double-cleanup pattern (finally block + this close()) ensures+ shutdown is called at least once; calling it twice is idempotent.+ """+ if hasattr(self, "search_executor"):+ try:+ self.search_executor.shutdown(wait=False)+ except Exception:+ logger.exception("Error shutting down search executor")+ if hasattr(self, "evaluation_executor"):+ try:+ self.evaluation_executor.shutdown(wait=False)+ except Exception:+ logger.exception("Error shutting down evaluation executor")+def find_relevant_information(self):"""Override to use parallel constraint-specific searches."""# Initialize statediff --git a/src/local_deep_research/database/encrypted_db.py b/src/local_deep_research/database/encrypted_db.pyindex 1c723035b2..24ec7e408d 100644--- a/src/local_deep_research/database/encrypted_db.py+++ b/src/local_deep_research/database/encrypted_db.py@@ -5,6 +5,7 @@ Handles per-user encrypted databases with browser-friendly authentication.import osimport threading+import timefrom pathlib import Pathfrom typing import Any, Dict, Optional, Tuple@@ -41,6 +42,8 @@ class DatabaseManager:# 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)@@ -694,6 +697,72 @@ class DatabaseManager:logger.warning(f"Error disposing thread engine {key}: {e}")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. Cleans up associated credentials from thread_local_session+ 3. Defense-in-depth: if @thread_cleanup fails to fire (e.g.+ interpreter crash, daemon thread killed at shutdown), this+ catches the leftovers+ 4. 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. Two trigger points: teardown_appcontext (request-driven,+ via maybe_sweep_dead_engines) and processor_v2 queue loop+ (timer-driven, every 6 iterations x 10s = ~60s).+ """+ 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 as e:+ logger.warning(+ f"Error disposing dead thread engine {key}: {e}"+ )+ 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:@@ -799,7 +868,11 @@ class DatabaseManager:engine = create_engine("sqlite://",creator=create_thread_connection,- poolclass=NullPool, # Important: no connection pooling for threads+ # 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:diff --git a/src/local_deep_research/database/thread_local_session.py b/src/local_deep_research/database/thread_local_session.pyindex 5e0c2c83f5..ca8db3db92 100644--- a/src/local_deep_research/database/thread_local_session.py+++ b/src/local_deep_research/database/thread_local_session.py@@ -151,6 +151,35 @@ class ThreadLocalSessionManager:with self._lock:self._thread_credentials.pop(thread_id, None)+ 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.++ Called from:+ - processor_v2.py: every ~60s in the queue loop+ - app_factory.py: in teardown_appcontext (rate-limited)+ """+ alive_ids = {t.ident for t in threading.enumerate()}+ with self._lock:+ dead_ids = [+ tid for tid in self._thread_credentials if tid not in alive_ids+ ]+ for tid in dead_ids:+ del self._thread_credentials[tid]+ if dead_ids:+ logger.debug(f"Swept {len(dead_ids)} dead thread credential(s)")+def cleanup_all(self):"""Clean up all tracked sessions (for shutdown)."""with self._lock:@@ -188,6 +217,12 @@ def cleanup_current_thread():thread_session_manager.cleanup_thread()+def cleanup_dead_threads():+ """Sweep dead-thread entries from both session manager and engine dict."""+ thread_session_manager.cleanup_dead_threads()+ db_manager.cleanup_dead_thread_engines()++class _ThreadCleanup(ContextDecorator):"""Context manager / decorator for thread-local resource cleanup."""diff --git a/src/local_deep_research/research_library/downloaders/generic.py b/src/local_deep_research/research_library/downloaders/generic.pyindex 086df4f805..cd70216ac0 100644--- a/src/local_deep_research/research_library/downloaders/generic.py+++ b/src/local_deep_research/research_library/downloaders/generic.py@@ -79,46 +79,58 @@ class GenericDownloader(BaseDownloader):logger.info(f"Successfully downloaded PDF from {pdf_url}")return DownloadResult(content=pdf_content, is_success=True)- # Try to determine more specific reason+ # Diagnostic request: determine WHY the download failed.+ #+ # IMPORTANT: stream=True is intentional here. DO NOT remove it.+ # This block only inspects response.status_code and headers+ # to determine why a download failed (404, 403, paywall, etc.).+ # Without stream=True, the full response body would be downloaded+ # into memory. Since GenericDownloader.can_handle() returns True+ # for ALL URLs, this could mean downloading multi-GB files just+ # to check a status code.+ #+ # The context manager (with ... as response) ensures the streamed+ # connection is properly closed on all code paths, preventing+ # file descriptor leaks (each unclosed stream=True response+ # holds an open socket FD).try:- response = self.session.get(+ with self.session.get(url, timeout=5, allow_redirects=True, stream=True- )-- # Check status code- if response.status_code == 200:- # Check if it's HTML instead of PDF- content_type = response.headers.get(- "content-type", ""- ).lower()- if "text/html" in content_type:+ ) as response:+ # Check status code+ if response.status_code == 200:+ # Check if it's HTML instead of PDF+ content_type = response.headers.get(+ "content-type", ""+ ).lower()+ if "text/html" in content_type:+ return DownloadResult(+ skip_reason="Article page requires login or subscription - no direct PDF link available"+ )+ else:+ return DownloadResult(+ skip_reason=f"Unexpected content type: {content_type} - expected PDF"+ )+ elif response.status_code == 404:+ return DownloadResult(+ skip_reason="Article not found (404) - may have been removed or URL is incorrect"+ )+ elif response.status_code == 403:+ return DownloadResult(+ skip_reason="Access denied (403) - article requires subscription or special permissions"+ )+ elif response.status_code == 401:+ return DownloadResult(+ skip_reason="Authentication required - please login to access this article"+ )+ elif response.status_code >= 500:return DownloadResult(- skip_reason="Article page requires login or subscription - no direct PDF link available"+ skip_reason=f"Server error ({response.status_code}) - website is experiencing technical issues")else:return DownloadResult(- skip_reason=f"Unexpected content type: {content_type} - expected PDF"+ skip_reason=f"Unable to access article - server returned error code {response.status_code}")- elif response.status_code == 404:- return DownloadResult(- skip_reason="Article not found (404) - may have been removed or URL is incorrect"- )- elif response.status_code == 403:- return DownloadResult(- skip_reason="Access denied (403) - article requires subscription or special permissions"- )- elif response.status_code == 401:- return DownloadResult(- skip_reason="Authentication required - please login to access this article"- )- elif response.status_code >= 500:- return DownloadResult(- skip_reason=f"Server error ({response.status_code}) - website is experiencing technical issues"- )- else:- return DownloadResult(- skip_reason=f"Unable to access article - server returned error code {response.status_code}"- )except requests.exceptions.Timeout:return DownloadResult(skip_reason="Connection timed out - server took too long to respond"diff --git a/src/local_deep_research/search_system.py b/src/local_deep_research/search_system.pyindex c1d334eeb4..dba494ec67 100644--- a/src/local_deep_research/search_system.py+++ b/src/local_deep_research/search_system.py@@ -221,6 +221,32 @@ class AdvancedSearchSystem:if hasattr(self, "progress_callback") and self.progress_callback:self.strategy.set_progress_callback(self.progress_callback)+ def close(self):+ """Close resources held by the search system.++ Cascades close to the strategy, which may hold persistent+ ThreadPoolExecutor instances (e.g. ConstraintParallelStrategy holds+ search_executor and evaluation_executor,+ ConcurrentDualConfidenceStrategy holds evaluation_executor).++ NOTE: Does NOT close self.search (the search engine) — the caller+ (run_research_process) manages search engine lifecycle separately+ because the search engine may be shared or reused.++ Most strategies (including the default source-based) use+ context-managed ThreadPoolExecutors that clean up automatically.+ The close() call here is a safety net for the two constraint-based+ strategies that hold persistent executors in __init__. Those+ strategies also shut down their executors in+ find_relevant_information()'s finally block, so this is a second+ line of defense for the edge case where the method is never called.+ """+ if hasattr(self, "strategy") and hasattr(self.strategy, "close"):+ try:+ self.strategy.close()+ except Exception:+ pass+def _progress_callback(self, message: str, progress: int, metadata: dict) -> None:diff --git a/src/local_deep_research/web/app_factory.py b/src/local_deep_research/web/app_factory.pyindex ec7faa93f1..12f3805880 100644--- a/src/local_deep_research/web/app_factory.py+++ b/src/local_deep_research/web/app_factory.py@@ -548,6 +548,28 @@ def apply_middleware(app):except Exception:pass+ # Dead thread sweep — rate-limited to every 60 seconds.+ # See encrypted_db.cleanup_dead_thread_engines() for detailed+ # rationale. This is one of two sweep trigger points; the other+ # is in processor_v2.py. The request-driven trigger here catches+ # dead threads promptly during active usage; the queue processor+ # trigger catches them during idle periods.+ try:+ from ..database.encrypted_db import db_manager++ db_manager.maybe_sweep_dead_engines()+ except Exception:+ pass++ try:+ from ..database.thread_local_session import (+ thread_session_manager,+ )++ thread_session_manager.cleanup_dead_threads()+ except Exception:+ pass+# Add a middleware layer to handle abrupt disconnections@app.before_requestdef handle_websocket_requests():diff --git a/src/local_deep_research/web/auth/routes.py b/src/local_deep_research/web/auth/routes.pyindex e6eed08d85..0d063cd168 100644--- a/src/local_deep_research/web/auth/routes.py+++ b/src/local_deep_research/web/auth/routes.py@@ -439,6 +439,36 @@ def logout():session_id = session.get("session_id")if username:+ # LOGOUT CLEANUP ORDER (order matters):+ # 1. Unregister from news scheduler — removes password from scheduler's+ # user_sessions dict and cancels scheduled jobs. Must happen BEFORE+ # close_user_database() because: scheduler jobs fetch the password+ # from user_sessions at runtime to call open_user_database(). If we+ # close the DB first, a running job that already has the password+ # can re-create the engine. Removing the password first ensures+ # future job invocations can't authenticate.+ # Note: a narrow race remains — a job that already fetched the+ # password (but hasn't called open_user_database yet) can still+ # recreate an engine. This is benign: the dead-thread sweep will+ # clean it up within 60 seconds.+ # 2. Close database connection — disposes QueuePool engine and cleans+ # up thread engines for this user.+ # 3. Destroy Flask session — invalidates session token.+ # 4. Clear session password store — removes password from secondary store.+ # 5. Clear Flask session dict — removes all session data.+ try:+ from ...news.subscription_manager.scheduler import (+ get_news_scheduler,+ )++ sched = get_news_scheduler()+ if sched.is_running:+ sched.unregister_user(username)+ except Exception:+ logger.warning(+ "Could not unregister user from scheduler", exc_info=True+ )+# Close database connectiondb_manager.close_user_database(username)diff --git a/src/local_deep_research/web/queue/processor_v2.py b/src/local_deep_research/web/queue/processor_v2.pyindex 76782f9853..7ad236db6b 100644--- a/src/local_deep_research/web/queue/processor_v2.py+++ b/src/local_deep_research/web/queue/processor_v2.py@@ -51,6 +51,7 @@ class QueueProcessorV2:self.check_interval = check_intervalself.running = Falseself.thread = None+ self._loop_iteration = 0# Per-user settings will be retrieved from each user's database# when processing their queue using SettingsManager@@ -429,12 +430,27 @@ class QueueProcessorV2:try:from ...database.thread_local_session import (cleanup_current_thread,+ cleanup_dead_threads,)cleanup_current_thread()except Exception:pass+ # Periodic dead-thread sweep (every ~60 seconds).+ # See encrypted_db.cleanup_dead_thread_engines() for+ # detailed rationale. This is one of two sweep trigger+ # points; the other is in app_factory.py+ # teardown_appcontext. Having two ensures sweeps happen+ # even when no HTTP requests are coming in (queue+ # processor runs independently).+ self._loop_iteration += 1+ if self._loop_iteration % 6 == 0: # Every ~60s (10s × 6)+ try:+ cleanup_dead_threads()+ except Exception:+ pass+time.sleep(self.check_interval)def _process_user_queue(self, username: str, session_id: str) -> bool:diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.pyindex 9da2a0920b..4943b28174 100644--- a/src/local_deep_research/web/services/research_service.py+++ b/src/local_deep_research/web/services/research_service.py@@ -1651,6 +1651,39 @@ def run_research_process(research_id, query, mode, **kwargs):# Clean up resourcescleanup_research_resources(research_id, username)+ finally:+ # RESOURCE CLEANUP: Close search engine HTTP sessions.+ #+ # Search engines (created via get_search()) may hold HTTP connection+ # pools. Currently only SemanticScholarSearchEngine creates a+ # persistent SafeSession; other engines use stateless safe_get()/+ # safe_post() utility functions. However, BaseSearchEngine.close()+ # is safe to call on any engine — it checks for a 'session'+ # attribute and is fully idempotent (SemanticScholar sets+ # self.session = None after close).+ #+ # Neither @thread_cleanup nor cleanup_research_resources() close+ # the search engine — @thread_cleanup only handles database sessions+ # and context cleanup, and cleanup_research_resources() only handles+ # status updates, notifications, and tracking dict removal.+ #+ # Without this explicit close, search engine sessions rely on+ # Python's non-deterministic garbage collection (__del__) for+ # cleanup, which can cause file descriptor exhaustion under+ # sustained load.+ if "use_search" in locals() and use_search is not None:+ try:+ use_search.close()+ except Exception:+ pass+ # Close search system (cascades to strategy thread pools).+ # See AdvancedSearchSystem.close() for details.+ if "system" in locals() and system is not None:+ try:+ system.close()+ except Exception:+ pass+def cleanup_research_resources(research_id, username=None):"""diff --git a/tests/database/test_thread_engine_management.py b/tests/database/test_thread_engine_management.pyindex 0d5a585cea..31dc027c3f 100644--- a/tests/database/test_thread_engine_management.py+++ b/tests/database/test_thread_engine_management.py@@ -401,6 +401,207 @@ class TestCleanupAllThreadEngines: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."""@@ -923,3 +1124,137 @@ class TestThreadLocalSessionIntegration:# Cleanupdb_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)+ 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/research_library/downloaders/test_generic_downloader.py b/tests/research_library/downloaders/test_generic_downloader.pyindex f95711db2e..4dc6fb9b0e 100644--- a/tests/research_library/downloaders/test_generic_downloader.py+++ b/tests/research_library/downloaders/test_generic_downloader.py@@ -149,14 +149,18 @@ class TestGenericDownloadWithResult:mock_pdf_response.headers = {}# Diagnostic call also returns 404+ # Note: diagnostic block uses context manager (with ... as response),+ # so mock must support __enter__/__exit__call_count = [0]def mock_get(url, **kwargs):call_count[0] += 1- mock_resp = mocker.Mock()+ mock_resp = mocker.MagicMock()mock_resp.status_code = 404mock_resp.content = b""mock_resp.headers = {}+ mock_resp.__enter__ = mocker.Mock(return_value=mock_resp)+ mock_resp.__exit__ = mocker.Mock(return_value=False)return mock_respmocker.patch.object(downloader.session, "get", side_effect=mock_get)@@ -176,10 +180,12 @@ class TestGenericDownloadWithResult:def test_download_with_result_403(self, downloader, mocker):"""Returns skip reason for 403 error."""- mock_response = mocker.Mock()+ mock_response = mocker.MagicMock()mock_response.status_code = 403mock_response.content = b""mock_response.headers = {}+ mock_response.__enter__ = mocker.Mock(return_value=mock_response)+ mock_response.__exit__ = mocker.Mock(return_value=False)mocker.patch.object(downloader.session, "get", return_value=mock_response@@ -200,10 +206,12 @@ class TestGenericDownloadWithResult:def test_download_with_result_html_response(self, downloader, mocker):"""Returns skip reason when HTML is returned instead of PDF."""- mock_response = mocker.Mock()+ mock_response = mocker.MagicMock()mock_response.status_code = 200mock_response.content = b"<html><body>Login page</body></html>"mock_response.headers = {"content-type": "text/html"}+ mock_response.__enter__ = mocker.Mock(return_value=mock_response)+ mock_response.__exit__ = mocker.Mock(return_value=False)mocker.patch.object(downloader.session, "get", return_value=mock_responsediff --git a/tests/web/auth/test_auth_routes.py b/tests/web/auth/test_auth_routes.pyindex cd543afeab..8d5f6e72ca 100644--- a/tests/web/auth/test_auth_routes.py+++ b/tests/web/auth/test_auth_routes.py@@ -432,6 +432,40 @@ class TestLogout:assert response.status_code == 302assert "login" in response.location+ def test_unregisters_user_from_scheduler_on_logout(self):+ """Should call scheduler.unregister_user() during logout."""+ app = Flask(__name__)+ app.secret_key = "test"+ app.config["WTF_CSRF_ENABLED"] = False++ mock_scheduler = MagicMock()+ mock_scheduler.is_running = True++ with (+ patch("local_deep_research.web.auth.routes.db_manager"),+ patch("local_deep_research.web.auth.routes.session_manager"),+ patch(+ "local_deep_research.database.session_passwords.session_password_store"+ ),+ patch(+ "local_deep_research.news.subscription_manager.scheduler.get_news_scheduler",+ return_value=mock_scheduler,+ ),+ ):+ from local_deep_research.web.auth.routes import auth_bp++ app.register_blueprint(auth_bp)++ with app.test_client() as client:+ with client.session_transaction() as sess:+ sess["username"] = "testuser"+ sess["session_id"] = "session_123"++ client.get("/auth/logout")+ mock_scheduler.unregister_user.assert_called_once_with(+ "testuser"+ )+class TestCheckAuth:"""Tests for /check endpoint."""