~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(threads): clear per-worker password cache + remove no-op decorator (#3519)
LearningCircuit53ea72dad172
diff --git a/src/local_deep_research/database/thread_local_session.py b/src/local_deep_research/database/thread_local_session.pyindex 88b07a1f29..8de7c53b2e 100644--- a/src/local_deep_research/database/thread_local_session.py+++ b/src/local_deep_research/database/thread_local_session.py@@ -223,8 +223,21 @@ def get_current_thread_session() -> Optional[Session]:def cleanup_current_thread():- """Clean up the current thread's database session."""+ """Clean up the current thread's database session and cached credentials.++ Also clears any passwords cached by ``metrics_writer`` on this thread —+ pooled worker threads must not retain plaintext credentials across tasks.+ """thread_session_manager.cleanup_thread()+ try:+ from .thread_metrics import metrics_writer++ metrics_writer.clear_passwords()+ except Exception:+ logger.debug(+ "cleanup_current_thread: error clearing metrics_writer passwords",+ exc_info=True,+ )def cleanup_dead_threads():diff --git a/src/local_deep_research/database/thread_metrics.py b/src/local_deep_research/database/thread_metrics.pyindex 1bcc2d8c62..8b6a96742a 100644--- a/src/local_deep_research/database/thread_metrics.py+++ b/src/local_deep_research/database/thread_metrics.py@@ -33,13 +33,24 @@ class ThreadSafeMetricsWriter:IMPORTANT: This is safe because:1. Password is already in memory (user is logged in)2. It's only stored thread-locally- 3. It's cleared when the thread ends+ 3. It's explicitly cleared by `clear_passwords()` (invoked from+ `cleanup_current_thread()`) so pooled worker threads do not+ retain credentials between tasks."""if not hasattr(self._thread_local, "passwords"):self._thread_local.passwords = {}self._thread_local.passwords[username] = password+ def clear_passwords(self):+ """Remove all passwords cached on the current thread's local store.++ Called by `cleanup_current_thread()` so that pooled worker threads+ don't retain plaintext credentials between tasks.+ """+ if hasattr(self._thread_local, "passwords"):+ self._thread_local.passwords.clear()+@contextmanagerdef get_session(self, username: str = None) -> Session:"""diff --git a/src/local_deep_research/web_search_engines/engines/parallel_search_engine.py b/src/local_deep_research/web_search_engines/engines/parallel_search_engine.pyindex ad5abb310f..7dc817786f 100644--- a/src/local_deep_research/web_search_engines/engines/parallel_search_engine.py+++ b/src/local_deep_research/web_search_engines/engines/parallel_search_engine.py@@ -7,9 +7,14 @@ import atexitfrom loguru import loggerfrom ...config.search_config import get_setting_from_snapshot+from ...database.thread_local_session import cleanup_current_threadfrom ...utilities.enums import SearchModefrom ...utilities.json_utils import extract_json, get_llm_response_text-from ...utilities.thread_context import preserve_research_context+from ...utilities.thread_context import (+ clear_search_context,+ get_search_context,+ set_search_context,+)from ...web.services.socket_service import SocketIOServicefrom ..search_engine_base import BaseSearchEnginefrom ..search_engine_factory import create_search_engine@@ -435,15 +440,15 @@ Select up to {self.max_engines_to_select} engines that would best answer this qureturn engine- @preserve_research_contextdef _execute_single_engine(self, engine_name: str, query: str) -> Dict[str, Any]:"""Execute a single search engine and return results.- Note: This method is decorated with @preserve_research_context to ensure- rate limiting context is properly propagated to child threads.+ Context propagation and thread-local cleanup are handled by+ ``_run_with_context`` at the submit site in ``_get_previews``,+ which captures the submitter's context once per request.Args:engine_name: Name of the engine to execute@@ -534,10 +539,36 @@ Select up to {self.max_engines_to_select} engines that would best answer this qu)return []+ # Capture submitter's research context ONCE (in the request thread,+ # where it is populated by the strategy's caller). Workers in the+ # global pool do not inherit thread-local state, so we must re-apply+ # it per task and clear it (+ clean up thread-local DB/session/password+ # state) in a finally block so nothing leaks to the next task that+ # lands on the same worker.+ submitter_ctx = get_search_context()++ def _run_with_context(fn, *fargs):+ if submitter_ctx is not None:+ set_search_context(submitter_ctx)+ try:+ return fn(*fargs)+ finally:+ clear_search_context()+ try:+ cleanup_current_thread()+ except Exception:+ logger.debug(+ "parallel_search submit wrapper: cleanup_current_thread failed",+ exc_info=True,+ )+# Submit all tasks to the global executorfuture_to_engine = {executor.submit(- self._execute_single_engine, engine_name, query+ _run_with_context,+ self._execute_single_engine,+ engine_name,+ query,): engine_namefor engine_name in selected_engines}diff --git a/tests/database/test_thread_metrics.py b/tests/database/test_thread_metrics.pyindex 8b4881377c..44985f0a0b 100644--- a/tests/database/test_thread_metrics.py+++ b/tests/database/test_thread_metrics.py@@ -232,6 +232,55 @@ class TestGlobalInstance:assert isinstance(metrics_writer, ThreadSafeMetricsWriter)+class TestClearPasswords:+ """Tests for clear_passwords() and its integration with cleanup_current_thread()."""++ def test_clear_passwords_empties_dict(self):+ from local_deep_research.database.thread_metrics import (+ ThreadSafeMetricsWriter,+ )++ writer = ThreadSafeMetricsWriter()+ writer.set_user_password("userA", "passA")+ writer.set_user_password("userB", "passB")+ assert writer._thread_local.passwords == {+ "userA": "passA",+ "userB": "passB",+ }++ writer.clear_passwords()++ assert writer._thread_local.passwords == {}++ def test_clear_passwords_is_noop_when_no_passwords_set(self):+ from local_deep_research.database.thread_metrics import (+ ThreadSafeMetricsWriter,+ )++ writer = ThreadSafeMetricsWriter()+ # No passwords dict exists; clear_passwords should not raise.+ writer.clear_passwords()+ assert not hasattr(writer._thread_local, "passwords")++ def test_cleanup_current_thread_clears_passwords(self):+ """Regression test — cleanup_current_thread() must clear the passwords dict+ on the module-level metrics_writer so pooled workers don't retain creds."""+ from local_deep_research.database.thread_metrics import metrics_writer+ from local_deep_research.database.thread_local_session import (+ cleanup_current_thread,+ )++ metrics_writer.set_user_password("leaked_user", "leaked_pass")+ assert (+ metrics_writer._thread_local.passwords.get("leaked_user")+ == "leaked_pass"+ )++ cleanup_current_thread()++ assert metrics_writer._thread_local.passwords == {}++class TestThreadIsolation:"""Tests for thread isolation of password storage."""diff --git a/tests/web_search_engines/engines/test_parallel_search_engine_concurrency.py b/tests/web_search_engines/engines/test_parallel_search_engine_concurrency.pynew file mode 100644index 0000000000..62bf838dec--- /dev/null+++ b/tests/web_search_engines/engines/test_parallel_search_engine_concurrency.py@@ -0,0 +1,140 @@+"""Regression tests for thread-local leak prevention in ParallelSearchEngine.++These tests pin the executor to ``max_workers=1`` so two back-to-back+submissions are guaranteed to land on the same worker thread, which is+the scenario where leaks would be observable.+"""++import concurrent.futures+from unittest.mock import Mock, patch++from local_deep_research.database.thread_metrics import metrics_writer+from local_deep_research.utilities.thread_context import (+ get_search_context,+ set_search_context,+ clear_search_context,+)+++class TestParallelSearchEngineThreadLocalIsolation:+ """Verify the submit-site wrapper in ``_get_previews`` cleans up+ thread-local state (search_context + metrics_writer passwords) so that+ the next task on the same worker starts with a clean slate."""++ def _make_pinned_executor(self):+ return concurrent.futures.ThreadPoolExecutor(+ max_workers=1, thread_name_prefix="test_pinned_"+ )++ def _make_engine(self):+ from local_deep_research.web_search_engines.engines.parallel_search_engine import (+ ParallelSearchEngine,+ )++ mock_llm = Mock()+ settings = {"search.max_results": {"value": 10}}+ return ParallelSearchEngine(+ llm=mock_llm,+ settings_snapshot=settings,+ programmatic_mode=True,+ )++ def test_worker_thread_has_no_stale_context_between_tasks(self):+ """First task contaminates the worker's thread-local state; the+ second task's pre-run snapshot must show that state cleared."""+ from local_deep_research.web_search_engines.engines import (+ parallel_search_engine as pse_mod,+ )++ engine = self._make_engine()++ # Record what the worker thread sees at task entry.+ entry_snapshots: list[dict] = []+ dirty_writes = {"userA_pw": "secret_A"}++ def fake_execute(self_engine, engine_name, query):+ entry_snapshots.append(+ {+ "engine_name": engine_name,+ "search_context": get_search_context(),+ "passwords_copy": dict(+ getattr(metrics_writer._thread_local, "passwords", {})+ ),+ }+ )+ # Simulate a metrics call on the worker thread that writes a+ # password into thread-local storage mid-task. The submit-site+ # wrapper's finally must clear this before the next task runs.+ metrics_writer.set_user_password("userA", dirty_writes["userA_pw"])+ return {+ "engine": engine_name,+ "success": True,+ "results": [{"title": f"r-{engine_name}"}],+ "count": 1,+ }++ pinned = self._make_pinned_executor()+ try:+ with (+ patch.object(+ pse_mod, "_get_global_executor", return_value=pinned+ ),+ patch.object(+ engine,+ "select_engines",+ side_effect=[["engine_first"], ["engine_second"]],+ ),+ patch.object(+ pse_mod.ParallelSearchEngine,+ "_execute_single_engine",+ new=fake_execute,+ ),+ ):+ # First "request": submitter has a research context.+ set_search_context({"username": "userA", "research_id": "r-1"})+ try:+ engine._get_previews("q1")+ finally:+ clear_search_context()++ # Second "request": submitter has NO context (simulating a+ # different user whose code path didn't populate one, or a+ # background call).+ assert get_search_context() is None+ engine._get_previews("q2")+ finally:+ pinned.shutdown(wait=True)++ assert len(entry_snapshots) == 2, entry_snapshots++ # First task saw the submitter's context applied by _run_with_context.+ assert entry_snapshots[0]["search_context"] == {+ "username": "userA",+ "research_id": "r-1",+ }++ # Second task entered with a CLEAN worker thread: no context and no+ # lingering password from the first task's mid-run write.+ assert entry_snapshots[1]["search_context"] is None, (+ "Worker thread leaked search_context across tasks: "+ f"{entry_snapshots[1]['search_context']!r}"+ )+ assert entry_snapshots[1]["passwords_copy"] == {}, (+ "Worker thread leaked metrics_writer passwords across tasks: "+ f"{entry_snapshots[1]['passwords_copy']!r}"+ )++ def test_class_level_preserve_research_context_is_removed(self):+ """The class-def-time @preserve_research_context wrap was a no-op+ and has been removed. Its import should also be gone."""+ import inspect++ from local_deep_research.web_search_engines.engines import (+ parallel_search_engine as pse_mod,+ )++ source = inspect.getsource(pse_mod)+ assert "preserve_research_context" not in source, (+ "preserve_research_context should no longer be referenced in "+ "parallel_search_engine.py — the class-def usage was a no-op."+ )