Skip to content

~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.

fix: clean up thread-local DB engines in search strategy worker threads (#2502)

LearningCircuit141184500da2
diff --git a/src/local_deep_research/advanced_search_system/candidate_exploration/parallel_explorer.py b/src/local_deep_research/advanced_search_system/candidate_exploration/parallel_explorer.py
index c58f9ad065..af6e235f0b 100644
--- a/src/local_deep_research/advanced_search_system/candidate_exploration/parallel_explorer.py
+++ b/src/local_deep_research/advanced_search_system/candidate_exploration/parallel_explorer.py
@@ -11,6 +11,7 @@ from typing import List, Optional
from loguru import logger
+from ...database.thread_local_session import thread_cleanup
from ..candidates.base_candidate import Candidate
from ..constraints.base_constraint import Constraint
from .base_explorer import (
@@ -84,7 +85,9 @@ class ParallelExplorer(BaseCandidateExplorer):
# Submit all queries for parallel execution
future_to_query = {
- executor.submit(self._execute_search, query): query
+ executor.submit(
+ thread_cleanup(self._execute_search), query
+ ): query
for query in current_queries
}
diff --git a/src/local_deep_research/advanced_search_system/strategies/browsecomp_entity_strategy.py b/src/local_deep_research/advanced_search_system/strategies/browsecomp_entity_strategy.py
index 78975c238a..20a3693245 100644
--- a/src/local_deep_research/advanced_search_system/strategies/browsecomp_entity_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/browsecomp_entity_strategy.py
@@ -20,6 +20,7 @@ from typing import Dict, List, Tuple
from loguru import logger
+from ...database.thread_local_session import thread_cleanup
from ...utilities.json_utils import extract_json, get_llm_response_text
from ...utilities.search_cache import get_search_cache
from ..candidate_exploration import ConstraintGuidedExplorer
@@ -919,7 +920,11 @@ Provide a helpful response explaining what was found and why no definitive answe
with concurrent.futures.ThreadPoolExecutor() as executor:
future = executor.submit(
- asyncio.run, self._analyze_topic_async(query)
+ thread_cleanup(
+ lambda: asyncio.run(
+ self._analyze_topic_async(query)
+ )
+ )
)
return future.result()
else:
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.py
index c9cebd6ee7..fa24786dce 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
@@ -17,6 +17,7 @@ from typing import List, Optional, Tuple
from loguru import logger
+from ...database.thread_local_session import thread_cleanup
from ..candidates.base_candidate import Candidate
from ..constraints.base_constraint import Constraint, ConstraintType
from .dual_confidence_with_rejection import DualConfidenceWithRejectionStrategy
@@ -284,6 +285,7 @@ class ConcurrentDualConfidenceStrategy(DualConfidenceWithRejectionStrategy):
terms
) # Use space instead of AND for more natural queries
+ @thread_cleanup
def _evaluate_candidate_thread(
self, candidate: Candidate
) -> Tuple[Candidate, float]:
diff --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.py
index b5b4a28f1a..b17e0049cc 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
@@ -17,6 +17,7 @@ from typing import Dict, List, Optional, Tuple
from loguru import logger
+from ...database.thread_local_session import thread_cleanup
from ..candidates.base_candidate import Candidate
from ..constraints.base_constraint import Constraint
from .dual_confidence_with_rejection import DualConfidenceWithRejectionStrategy
@@ -233,6 +234,7 @@ class ConstraintParallelStrategy(DualConfidenceWithRejectionStrategy):
# Wait for evaluations to complete
self._finalize_evaluations()
+ @thread_cleanup
def _run_constraint_search(
self, constraint: Constraint, index: int, total: int
) -> List[Candidate]:
@@ -320,6 +322,7 @@ class ConstraintParallelStrategy(DualConfidenceWithRejectionStrategy):
self.state.evaluation_futures.append(future)
self.state.total_evaluated += 1
+ @thread_cleanup
def _evaluate_candidate_thread(
self, candidate: Candidate
) -> Tuple[Candidate, float]:
diff --git a/src/local_deep_research/advanced_search_system/strategies/early_stop_constrained_strategy.py b/src/local_deep_research/advanced_search_system/strategies/early_stop_constrained_strategy.py
index 46de2fc30c..8bb789d72a 100644
--- a/src/local_deep_research/advanced_search_system/strategies/early_stop_constrained_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/early_stop_constrained_strategy.py
@@ -9,6 +9,7 @@ from typing import Dict, List
from loguru import logger
+from ...database.thread_local_session import thread_cleanup
from ..candidates.base_candidate import Candidate
from ..constraints.base_constraint import Constraint
from .parallel_constrained_strategy import ParallelConstrainedStrategy
@@ -77,7 +78,9 @@ class EarlyStopConstrainedStrategy(ParallelConstrainedStrategy):
if candidate.name not in self.evaluating_candidates:
self.evaluating_candidates.add(candidate.name)
eval_future = executor.submit(
- self._evaluate_candidate_immediately,
+ thread_cleanup(
+ self._evaluate_candidate_immediately
+ ),
candidate,
)
evaluation_futures.append(eval_future)
diff --git a/src/local_deep_research/advanced_search_system/strategies/llm_driven_modular_strategy.py b/src/local_deep_research/advanced_search_system/strategies/llm_driven_modular_strategy.py
index 6a424e8609..1b495cea1a 100644
--- a/src/local_deep_research/advanced_search_system/strategies/llm_driven_modular_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/llm_driven_modular_strategy.py
@@ -9,6 +9,7 @@ from typing import Dict, List, Optional, Tuple
from loguru import logger
+from ...database.thread_local_session import thread_cleanup
from ...utilities.json_utils import extract_json
from ..candidate_exploration import AdaptiveExplorer
@@ -411,7 +412,9 @@ class LLMDrivenModularStrategy(BaseSearchStrategy):
with concurrent.futures.ThreadPoolExecutor() as executor:
future = executor.submit(
- lambda: asyncio.run(self.search(query))
+ thread_cleanup(
+ lambda: asyncio.run(self.search(query))
+ )
)
answer, metadata = future.result()
else:
diff --git a/src/local_deep_research/advanced_search_system/strategies/modular_strategy.py b/src/local_deep_research/advanced_search_system/strategies/modular_strategy.py
index 1f7e56b0fb..d2032e9dc4 100644
--- a/src/local_deep_research/advanced_search_system/strategies/modular_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/modular_strategy.py
@@ -10,6 +10,7 @@ from typing import Dict, List, Optional, Tuple
from loguru import logger
+from ...database.thread_local_session import thread_cleanup
from ...utilities.json_utils import extract_json
from ...utilities.search_cache import get_search_cache, normalize_entity_query
from ..candidate_exploration import (
@@ -525,7 +526,10 @@ class ModularStrategy(BaseSearchStrategy):
# Submit all searches in the batch concurrently
future_to_query = {
executor.submit(
- self.candidate_explorer._execute_search, query
+ thread_cleanup(
+ self.candidate_explorer._execute_search
+ ),
+ query,
): query
for query in batch
}
@@ -1091,7 +1095,9 @@ Provide a clear, factual answer that addresses the original question and explain
with concurrent.futures.ThreadPoolExecutor() as executor:
future = executor.submit(
- lambda: asyncio.run(self.search(query))
+ thread_cleanup(
+ lambda: asyncio.run(self.search(query))
+ )
)
answer, metadata = future.result()
else:
diff --git a/src/local_deep_research/advanced_search_system/strategies/news_strategy.py b/src/local_deep_research/advanced_search_system/strategies/news_strategy.py
index dcbd231765..f31be28857 100644
--- a/src/local_deep_research/advanced_search_system/strategies/news_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/news_strategy.py
@@ -9,6 +9,7 @@ from loguru import logger
from .base_strategy import BaseSearchStrategy
from ..questions.news_question import NewsQuestionGenerator
+from ...database.thread_local_session import thread_cleanup
from ...utilities.json_utils import extract_json
@@ -249,7 +250,11 @@ Ensure variety across different categories when possible.
with concurrent.futures.ThreadPoolExecutor() as executor:
future = executor.submit(
- asyncio.run, self.analyze_findings(all_findings)
+ thread_cleanup(
+ lambda: asyncio.run(
+ self.analyze_findings(all_findings)
+ )
+ )
)
analysis = future.result()
else:
diff --git a/src/local_deep_research/advanced_search_system/strategies/parallel_constrained_strategy.py b/src/local_deep_research/advanced_search_system/strategies/parallel_constrained_strategy.py
index e81f22ec47..03a0c21003 100644
--- a/src/local_deep_research/advanced_search_system/strategies/parallel_constrained_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/parallel_constrained_strategy.py
@@ -14,6 +14,7 @@ from typing import List
from loguru import logger
+from ...database.thread_local_session import thread_cleanup
from ..candidates.base_candidate import Candidate
from ..constraints.base_constraint import Constraint, ConstraintType
from .constrained_search_strategy import ConstrainedSearchStrategy
@@ -355,6 +356,7 @@ class ParallelConstrainedStrategy(ConstrainedSearchStrategy):
return all_candidates
+ @thread_cleanup
def _execute_combination_search(
self, combination: SearchCombination
) -> List[Candidate]:
diff --git a/src/local_deep_research/advanced_search_system/strategies/parallel_search_strategy.py b/src/local_deep_research/advanced_search_system/strategies/parallel_search_strategy.py
index 2065ccae46..125f93c2de 100644
--- a/src/local_deep_research/advanced_search_system/strategies/parallel_search_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/parallel_search_strategy.py
@@ -10,6 +10,7 @@ from loguru import logger
from ...citation_handler import CitationHandler
# Model and search should be provided by AdvancedSearchSystem
+from ...database.thread_local_session import thread_cleanup
from ...utilities.search_utilities import extract_links_from_search_results
from ..filters.cross_engine_filter import CrossEngineFilter
from ..findings.repository import FindingsRepository
@@ -229,6 +230,7 @@ class ParallelSearchStrategy(BaseSearchStrategy):
)
# Function for thread pool
+ @thread_cleanup
def search_question(q):
try:
result = self.search.run(q)
diff --git a/src/local_deep_research/advanced_search_system/strategies/smart_query_strategy.py b/src/local_deep_research/advanced_search_system/strategies/smart_query_strategy.py
index f92ff42068..756068b626 100644
--- a/src/local_deep_research/advanced_search_system/strategies/smart_query_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/smart_query_strategy.py
@@ -7,6 +7,7 @@ from typing import Dict, List
from loguru import logger
+from ...database.thread_local_session import thread_cleanup
from ..constraints.base_constraint import Constraint
from ..constraints.constraint_analyzer import ConstraintType
from .early_stop_constrained_strategy import EarlyStopConstrainedStrategy
@@ -143,6 +144,7 @@ Return only the search query, nothing else.
return " ".join(query_parts)
+ @thread_cleanup
def _execute_combination_search(self, combo) -> List:
"""Override to generate multiple query variations per combination."""
all_candidates = []
@@ -164,7 +166,9 @@ Return only the search query, nothing else.
continue
self.searched_queries.add(normalized_query)
- future = executor.submit(self._execute_search, query)
+ future = executor.submit(
+ thread_cleanup(self._execute_search), query
+ )
futures.append((query, future))
for query, future in futures:
@@ -358,7 +362,9 @@ Provide one name per line. Be specific with actual character/entity names.
query = f'"{seed}"'
if query.lower() not in self.searched_queries:
self.searched_queries.add(query.lower())
- future = executor.submit(self._execute_search, query)
+ future = executor.submit(
+ thread_cleanup(self._execute_search), query
+ )
futures.append((seed, future))
for seed, future in futures:
@@ -427,7 +433,9 @@ Provide one name per line. Be specific with actual character/entity names.
]: # Limit to avoid too many searches
if query.lower() not in self.searched_queries:
self.searched_queries.add(query.lower())
- future = executor.submit(self._execute_search, query)
+ future = executor.submit(
+ thread_cleanup(self._execute_search), query
+ )
futures.append(future)
for future in futures:
diff --git a/src/local_deep_research/database/thread_local_session.py b/src/local_deep_research/database/thread_local_session.py
index 8ced41547e..5e0c2c83f5 100644
--- a/src/local_deep_research/database/thread_local_session.py
+++ b/src/local_deep_research/database/thread_local_session.py
@@ -5,6 +5,7 @@ Each thread gets its own database session that persists for the thread's lifetim
import functools
import threading
+from contextlib import ContextDecorator
from typing import Optional, Dict, Tuple
from sqlalchemy import text
from sqlalchemy.exc import PendingRollbackError
@@ -187,36 +188,66 @@ def cleanup_current_thread():
thread_session_manager.cleanup_thread()
-def thread_cleanup(func):
- """Decorator ensuring all thread-local resources are cleaned up when func exits.
+class _ThreadCleanup(ContextDecorator):
+ """Context manager / decorator for thread-local resource cleanup."""
- Use on any function that runs in a background thread, ThreadPoolExecutor,
- or APScheduler job.
- """
+ def __enter__(self):
+ return self
- @functools.wraps(func)
- def wrapper(*args, **kwargs):
+ def __exit__(self, exc_type, exc_val, exc_tb):
try:
- return func(*args, **kwargs)
- finally:
- try:
- cleanup_current_thread()
- except Exception:
- pass
- try:
- from ..config.thread_settings import clear_settings_context
+ cleanup_current_thread()
+ except Exception:
+ logger.debug(
+ "thread_cleanup: error during DB session cleanup",
+ exc_info=True,
+ )
+ try:
+ from ..config.thread_settings import clear_settings_context
- clear_settings_context()
- except Exception:
- pass
- try:
- from ..utilities.thread_context import clear_search_context
+ clear_settings_context()
+ except Exception:
+ logger.debug(
+ "thread_cleanup: error clearing settings context",
+ exc_info=True,
+ )
+ try:
+ from ..utilities.thread_context import clear_search_context
- clear_search_context()
- except Exception:
- pass
+ clear_search_context()
+ except Exception:
+ logger.debug(
+ "thread_cleanup: error clearing search context",
+ exc_info=True,
+ )
+ return False
+
+
+def thread_cleanup(func=None):
+ """Ensure all thread-local resources are cleaned up when a function or block exits.
+
+ Works as a bare decorator, a decorator factory, or a context manager::
+
+ @thread_cleanup
+ def worker(): ...
+
+ @thread_cleanup()
+ def worker(): ...
+
+ with thread_cleanup():
+ ...
+
+ executor.submit(thread_cleanup(func), arg)
+ """
+ if func is not None:
+
+ @functools.wraps(func)
+ def wrapper(*args, **kwargs):
+ with _ThreadCleanup():
+ return func(*args, **kwargs)
- return wrapper
+ return wrapper
+ return _ThreadCleanup()
# Context manager for automatic cleanup
diff --git a/src/local_deep_research/news/subscription_manager/scheduler.py b/src/local_deep_research/news/subscription_manager/scheduler.py
index 9f9183059d..b0cc6d7973 100644
--- a/src/local_deep_research/news/subscription_manager/scheduler.py
+++ b/src/local_deep_research/news/subscription_manager/scheduler.py
@@ -1212,6 +1212,7 @@ class NewsScheduler:
except Exception:
logger.exception(f"Error checking subscription {subscription_id}")
+ @thread_cleanup
def _trigger_subscription_research_sync(
self, username: str, subscription: Dict[str, Any]
):
diff --git a/src/local_deep_research/utilities/thread_context.py b/src/local_deep_research/utilities/thread_context.py
index 461b507b2b..820f5b0285 100644
--- a/src/local_deep_research/utilities/thread_context.py
+++ b/src/local_deep_research/utilities/thread_context.py
@@ -130,5 +130,17 @@ def preserve_research_context(func: Callable) -> Callable:
finally:
if context is not None:
clear_search_context()
+ # Clean up thread-local DB engines created by metrics recording
+ try:
+ from ..database.thread_local_session import (
+ cleanup_current_thread,
+ )
+
+ cleanup_current_thread()
+ except Exception:
+ logger.debug(
+ "preserve_research_context: error during cleanup_current_thread",
+ exc_info=True,
+ )
return wrapper
diff --git a/tests/database/test_thread_local_session.py b/tests/database/test_thread_local_session.py
index 65b850f1b6..d6a18e4df7 100644
--- a/tests/database/test_thread_local_session.py
+++ b/tests/database/test_thread_local_session.py
@@ -404,3 +404,164 @@ class TestGlobalInstance:
)
assert isinstance(thread_session_manager, ThreadLocalSessionManager)
+
+
+class TestThreadCleanup:
+ """Tests for thread_cleanup decorator / context manager."""
+
+ def _patch_all_cleanup(self):
+ """Return a stack of patches for the three cleanup functions."""
+ return (
+ patch(
+ "local_deep_research.database.thread_local_session.cleanup_current_thread"
+ ),
+ patch(
+ "local_deep_research.database.thread_local_session._ThreadCleanup.__exit__",
+ wraps=None,
+ ),
+ )
+
+ def test_bare_decorator_runs_cleanup(self):
+ """@thread_cleanup runs cleanup on exit and returns result."""
+ from local_deep_research.database.thread_local_session import (
+ thread_cleanup,
+ )
+
+ mock_cleanup = Mock()
+
+ with patch(
+ "local_deep_research.database.thread_local_session.cleanup_current_thread",
+ mock_cleanup,
+ ):
+
+ @thread_cleanup
+ def worker():
+ return 42
+
+ result = worker()
+
+ assert result == 42
+ mock_cleanup.assert_called_once()
+
+ def test_factory_decorator_runs_cleanup(self):
+ """@thread_cleanup() (with parens) runs cleanup on exit and returns result."""
+ from local_deep_research.database.thread_local_session import (
+ thread_cleanup,
+ )
+
+ mock_cleanup = Mock()
+
+ with patch(
+ "local_deep_research.database.thread_local_session.cleanup_current_thread",
+ mock_cleanup,
+ ):
+
+ @thread_cleanup()
+ def worker():
+ return 99
+
+ result = worker()
+
+ assert result == 99
+ mock_cleanup.assert_called_once()
+
+ def test_context_manager_runs_cleanup(self):
+ """with thread_cleanup(): runs cleanup on exit."""
+ from local_deep_research.database.thread_local_session import (
+ thread_cleanup,
+ )
+
+ mock_cleanup = Mock()
+
+ with patch(
+ "local_deep_research.database.thread_local_session.cleanup_current_thread",
+ mock_cleanup,
+ ):
+ with thread_cleanup():
+ pass
+
+ mock_cleanup.assert_called_once()
+
+ def test_inline_wrapper_runs_cleanup(self):
+ """thread_cleanup(func) as inline wrapper runs cleanup on exit."""
+ from local_deep_research.database.thread_local_session import (
+ thread_cleanup,
+ )
+
+ mock_cleanup = Mock()
+
+ def worker(x):
+ return x * 2
+
+ with patch(
+ "local_deep_research.database.thread_local_session.cleanup_current_thread",
+ mock_cleanup,
+ ):
+ wrapped = thread_cleanup(worker)
+ result = wrapped(5)
+
+ assert result == 10
+ mock_cleanup.assert_called_once()
+
+ def test_cleanup_exception_logged_not_raised(self):
+ """Cleanup exceptions are logged at debug level, not raised."""
+ from local_deep_research.database.thread_local_session import (
+ thread_cleanup,
+ )
+
+ with (
+ patch(
+ "local_deep_research.database.thread_local_session.cleanup_current_thread",
+ side_effect=RuntimeError("cleanup boom"),
+ ),
+ patch(
+ "local_deep_research.database.thread_local_session.logger"
+ ) as mock_logger,
+ ):
+
+ @thread_cleanup
+ def worker():
+ return "ok"
+
+ result = worker()
+
+ assert result == "ok"
+ mock_logger.debug.assert_called()
+
+ def test_original_exception_propagates_when_cleanup_fails(self):
+ """Original exceptions propagate even when cleanup fails."""
+ from local_deep_research.database.thread_local_session import (
+ thread_cleanup,
+ )
+
+ with (
+ patch(
+ "local_deep_research.database.thread_local_session.cleanup_current_thread",
+ side_effect=RuntimeError("cleanup boom"),
+ ),
+ patch("local_deep_research.database.thread_local_session.logger"),
+ ):
+
+ @thread_cleanup
+ def worker():
+ raise ValueError("original error")
+
+ try:
+ worker()
+ assert False, "Should have raised ValueError"
+ except ValueError as e:
+ assert str(e) == "original error"
+
+ def test_functools_wraps_metadata_preserved(self):
+ """functools.wraps metadata preserved on decorated functions."""
+ from local_deep_research.database.thread_local_session import (
+ thread_cleanup,
+ )
+
+ @thread_cleanup
+ def my_worker():
+ """My docstring."""
+ pass
+
+ assert my_worker.__name__ == "my_worker"
+ assert my_worker.__doc__ == "My docstring."