~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 context leaks in decorator, scheduler, and services (#2281)
LearningCircuitb156207100a3
diff --git a/src/local_deep_research/benchmarks/web_api/benchmark_service.py b/src/local_deep_research/benchmarks/web_api/benchmark_service.pyindex bbd131fc5f..d809750d46 100644--- a/src/local_deep_research/benchmarks/web_api/benchmark_service.py+++ b/src/local_deep_research/benchmarks/web_api/benchmark_service.py@@ -420,7 +420,10 @@ class BenchmarkService:settings_context = SettingsContext(settings_snapshot, username)# Set the context in thread-local storage- from ...config.thread_settings import set_settings_context+ from ...config.thread_settings import (+ clear_settings_context,+ set_settings_context,+ )set_settings_context(settings_context)@@ -599,6 +602,9 @@ class BenchmarkService:"error_message": str(e),}finally:+ # Clear thread-local settings context to prevent leaks+ clear_settings_context()+# Clean up active run trackingif benchmark_run_id in self.active_runs:# Mark that thread is done but keep data for database updatediff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.pyindex b218a02190..ce2c8f55e6 100644--- a/src/local_deep_research/web/services/research_service.py+++ b/src/local_deep_research/web/services/research_service.py@@ -371,7 +371,10 @@ def run_research_process()# Set the settings context for this thread- from ...config.thread_settings import set_settings_context+ from ...config.thread_settings import (+ clear_settings_context,+ set_settings_context,+ )set_settings_context(settings_context)@@ -1577,6 +1580,14 @@ def run_research_process(research_id, active_research, termination_flags, username)+ finally:+ # Clear thread-local contexts to prevent leaks when threads are reused+ from ...utilities.thread_context import clear_search_context+ from ...config.thread_settings import clear_settings_context++ clear_search_context()+ clear_settings_context()+def cleanup_research_resources(research_id, active_research, termination_flags, username=Nonediff --git a/tests/utilities/test_thread_context.py b/tests/utilities/test_thread_context.pyindex c4ecdb0b54..19910d5582 100644--- a/tests/utilities/test_thread_context.py+++ b/tests/utilities/test_thread_context.py@@ -7,6 +7,7 @@ from unittest.mock import patchfrom local_deep_research.utilities.thread_context import (_g_thread_data,+ clear_search_context,get_search_context,preserve_research_context,set_search_context,@@ -41,14 +42,14 @@ class TestSetSearchContext:set_search_context({"new": "context"})assert _g_thread_data.context == {"new": "context"}- def test_logs_warning_on_overwrite(self):- """Should log warning when overwriting existing context."""+ def test_logs_debug_on_overwrite(self):+ """Should log debug message when overwriting existing context."""set_search_context({"first": "context"})with patch("local_deep_research.utilities.thread_context.logger") as mock_logger:set_search_context({"second": "context"})- mock_logger.warning.assert_called_once()+ mock_logger.debug.assert_called_once()def test_handles_empty_context(self):"""Should handle empty context dictionary."""@@ -56,6 +57,33 @@ class TestSetSearchContext:assert _g_thread_data.context == {}+class TestClearSearchContext:+ """Tests for clear_search_context function."""++ def setup_method(self):+ """Clear thread-local data before each test."""+ if hasattr(_g_thread_data, "context"):+ delattr(_g_thread_data, "context")++ def test_clears_existing_context(self):+ """Should clear context when set."""+ set_search_context({"research_id": "123"})+ clear_search_context()+ assert not hasattr(_g_thread_data, "context")+ assert get_search_context() is None++ def test_noop_when_no_context(self):+ """Should not raise when no context is set."""+ clear_search_context() # Should not raise++ def test_clear_then_set(self):+ """Should allow setting new context after clearing."""+ set_search_context({"first": "context"})+ clear_search_context()+ set_search_context({"second": "context"})+ assert get_search_context() == {"second": "context"}++class TestGetSearchContext:"""Tests for get_search_context function."""@@ -231,6 +259,54 @@ class TestPreserveResearchContext:assert result == {"result": "success"}+ def test_clears_context_after_execution(self):+ """Should clear context after wrapped function completes to prevent leaks."""+ context = {"research_id": "cleanup-test"}+ set_search_context(context)++ @preserve_research_context+ def worker():+ # Context should be set during execution+ return get_search_context()++ context_after = []++ def run_and_check():+ worker()+ context_after.append(get_search_context())++ with ThreadPoolExecutor(max_workers=1) as executor:+ future = executor.submit(run_and_check)+ future.result()++ # After worker completes, context should be cleared on the worker thread+ assert context_after[0] is None++ def test_clears_context_on_exception(self):+ """Should clear context even when wrapped function raises."""+ context = {"research_id": "exception-test"}+ set_search_context(context)++ @preserve_research_context+ def failing_worker():+ raise ValueError("test error")++ context_after = []++ def run_and_check():+ try:+ failing_worker()+ except ValueError:+ pass+ context_after.append(get_search_context())++ with ThreadPoolExecutor(max_workers=1) as executor:+ future = executor.submit(run_and_check)+ future.result()++ # Context should be cleared even after exception+ assert context_after[0] is None+def test_preserves_context_across_multiple_calls(self):"""Should preserve context for multiple calls."""context = {"research_id": "multi-call"}