~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
feat: add cancellation checks to search strategy main loops (#2452)
LearningCircuita2614b3dffdb
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 86d6335148..6f856a8349 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@@ -62,6 +62,29 @@ class BaseSearchStrategy(ABC):"""Set a callback function to receive progress updates."""self.progress_callback = callback+ def check_termination(self) -> None:+ """Check if the research has been cancelled.++ Reuses the existing ``progress_callback`` rather than a dedicated+ termination-check callable. This avoids duplicating the ~15 wiring+ points across the codebase (search_system, research_service,+ research_functions, and every nested strategy) where+ ``set_progress_callback`` is already propagated. A dedicated+ ``set_termination_check`` method could be introduced later if the+ callback-based approach becomes a maintenance burden.++ The callback in ``research_service.py`` recognises the+ ``"termination_check"`` phase and returns immediately after the+ flag check -- no UI logging or socket emission occurs.+ """+ if self.progress_callback:+ logger.debug("Checking termination status")+ self.progress_callback(+ "Checking termination status",+ None,+ {"phase": "termination_check"},+ )+def _update_progress(self,message: str,diff --git a/src/local_deep_research/advanced_search_system/strategies/iterative_reasoning_strategy.py b/src/local_deep_research/advanced_search_system/strategies/iterative_reasoning_strategy.pyindex 7f17c84480..111733ff18 100644--- a/src/local_deep_research/advanced_search_system/strategies/iterative_reasoning_strategy.py+++ b/src/local_deep_research/advanced_search_system/strategies/iterative_reasoning_strategy.py@@ -156,6 +156,7 @@ class IterativeReasoningStrategy(BaseSearchStrategy):self.knowledge_state.iteration < self.max_iterationsand self.knowledge_state.confidence < self.confidence_threshold):+ self.check_termination()self.knowledge_state.iteration += 1logger.info(f"Iteration {self.knowledge_state.iteration}/{self.max_iterations}, Current confidence: {self.knowledge_state.confidence:.1%}"diff --git a/src/local_deep_research/advanced_search_system/strategies/iterative_refinement_strategy.py b/src/local_deep_research/advanced_search_system/strategies/iterative_refinement_strategy.pyindex 7797f4d56b..adf5a4c197 100644--- a/src/local_deep_research/advanced_search_system/strategies/iterative_refinement_strategy.py+++ b/src/local_deep_research/advanced_search_system/strategies/iterative_refinement_strategy.py@@ -155,6 +155,7 @@ class IterativeRefinementStrategy(BaseSearchStrategy):# Main refinement loopwhile refinement_count < self.max_refinements:+ self.check_termination()rounds_since_evaluation += 1# Evaluate if it's time (based on frequency)@@ -237,32 +238,23 @@ class IterativeRefinementStrategy(BaseSearchStrategy):self.progress_callback)- # Step 5: Run follow-up research with error handling- try:- followup_results = followup_strategy.analyze_topic(- followup_query- )+ # Step 5: Run follow-up research+ followup_results = followup_strategy.analyze_topic(+ followup_query+ )- # Check if follow-up produced useful results- new_sources = followup_results.get(- "all_links_of_system", []- )- if len(new_sources) < 2:- logger.info(- f"Refinement yielded only {len(new_sources)} new sources, stopping refinement"- )- break-- # Step 6: Merge results- results = self._merge_results(- results, followup_results, followup_query- )- except Exception:- logger.exception(- f"Follow-up research failed for query: {followup_query[:100]}..."+ # Check if follow-up produced useful results+ new_sources = followup_results.get("all_links_of_system", [])+ if len(new_sources) < 2:+ logger.info(+ f"Refinement yielded only {len(new_sources)} new sources, stopping refinement")- # Re-raise to see the actual error- raise+ break++ # Step 6: Merge results+ results = self._merge_results(+ results, followup_results, followup_query+ )# Update accumulated sources (O(1) lookup with set)existing_urls = {s.get("url") for s in all_accumulated_sources}diff --git a/src/local_deep_research/advanced_search_system/strategies/source_based_strategy.py b/src/local_deep_research/advanced_search_system/strategies/source_based_strategy.pyindex 07286c39e3..8ea18d5399 100644--- a/src/local_deep_research/advanced_search_system/strategies/source_based_strategy.py+++ b/src/local_deep_research/advanced_search_system/strategies/source_based_strategy.py@@ -221,6 +221,7 @@ class SourceBasedSearchStrategy(BaseSearchStrategy):)# Run each iterationfor iteration in range(1, iterations_to_run + 1):+ self.check_termination()iteration_progress_base = 5 + (iteration - 1) * (70 / iterations_to_run)diff --git a/src/local_deep_research/exceptions.py b/src/local_deep_research/exceptions.pynew file mode 100644index 0000000000..a64dffaba5--- /dev/null+++ b/src/local_deep_research/exceptions.py@@ -0,0 +1,13 @@+"""Project-wide exception classes."""+++class ResearchTerminatedException(BaseException):+ """Raised when a user cancels an in-progress research process.++ Inherits from BaseException (not Exception) so that ``except Exception``+ blocks throughout the strategy code naturally let it propagate -- the same+ pattern Python's stdlib uses for asyncio.CancelledError (since 3.9),+ KeyboardInterrupt, and SystemExit.+ """++ passdiff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.pyindex 6425db629d..0bd668197b 100644--- a/src/local_deep_research/web/services/research_service.py+++ b/src/local_deep_research/web/services/research_service.py@@ -6,6 +6,7 @@ from pathlib import Pathfrom loguru import logger+from ...exceptions import ResearchTerminatedExceptionfrom ...config.llm_config import get_llm# Output directory for research results@@ -413,7 +414,13 @@ def run_research_process(handle_termination(research_id, active_research, termination_flags, username)- raise Exception("Research was terminated by user")+ raise ResearchTerminatedException(+ "Research was terminated by user"+ )++ # Silent phase — no UI logging or socket emission needed+ if metadata.get("phase") == "termination_check":+ return# Bind research_id to logger for this specific logbound_logger = logger.bind(research_id=research_id)@@ -513,7 +520,7 @@ def run_research_process(handle_termination(research_id, active_research, termination_flags, username)- raise Exception(+ raise ResearchTerminatedException("Research was terminated by user during long-running operation")return False # Not terminated@@ -662,7 +669,9 @@ def run_research_process(error_type = "connection_error"# Raise with improved error message- raise Exception(f"{error_message} (Error type: {error_type})")+ raise Exception(+ f"{error_message} (Error type: {error_type})"+ ) from search_error# Generate output based on modeif mode == "quick":@@ -1377,6 +1386,14 @@ def run_research_process(research_id, active_research, termination_flags, username)+ except ResearchTerminatedException:+ logger.info(f"Research {research_id} terminated by user")+ # handle_termination() was already called by progress_callback+ # before raising, which:+ # 1. Queued SUSPENDED status update via queue_processor+ # 2. Called cleanup_research_resources()+ # No additional cleanup needed here.+except Exception as e:# Handle errorerror_message = f"Research failed: {e!s}"@@ -1516,7 +1533,7 @@ def run_research_process(# If termination was requested, mark as suspended instead of failedstatus = (ResearchStatus.SUSPENDED- if (termination_flags.get(research_id))+ if termination_flags.get(research_id)else ResearchStatus.FAILED)message = (diff --git a/tests/strategies/test_cancellation_checks.py b/tests/strategies/test_cancellation_checks.pynew file mode 100644index 0000000000..135f1af48a--- /dev/null+++ b/tests/strategies/test_cancellation_checks.py@@ -0,0 +1,134 @@+"""Tests for strategy cancellation checks (PR #2452).++Verifies:+- BaseSearchStrategy.check_termination() calls progress_callback+- check_termination() is called in each strategy's main loop+- ResearchTerminatedException inherits from BaseException (not Exception)+ so that ``except Exception`` blocks naturally let it propagate+"""++import inspect+import pytest+from unittest.mock import MagicMock++from local_deep_research.advanced_search_system.strategies.base_strategy import (+ BaseSearchStrategy,+)+from local_deep_research.exceptions import ResearchTerminatedException+++class TestCheckTerminationMethod:+ """Verify check_termination() on BaseSearchStrategy."""++ def test_calls_progress_callback(self):+ """check_termination should call progress_callback with termination_check phase."""++ class ConcreteStrategy(BaseSearchStrategy):+ def analyze_topic(self, query):+ pass++ strategy = ConcreteStrategy.__new__(ConcreteStrategy)+ strategy.progress_callback = MagicMock()++ strategy.check_termination()++ strategy.progress_callback.assert_called_once()+ args = strategy.progress_callback.call_args+ assert args[0][2]["phase"] == "termination_check"++ def test_no_callback_no_error(self):+ """check_termination should not error if no callback set."""++ class ConcreteStrategy(BaseSearchStrategy):+ def analyze_topic(self, query):+ pass++ strategy = ConcreteStrategy.__new__(ConcreteStrategy)+ strategy.progress_callback = None++ # Should not raise+ strategy.check_termination()++ def test_propagates_callback_exception(self):+ """If callback raises ResearchTerminatedException, it should propagate."""++ class ConcreteStrategy(BaseSearchStrategy):+ def analyze_topic(self, query):+ pass++ strategy = ConcreteStrategy.__new__(ConcreteStrategy)+ strategy.progress_callback = MagicMock(+ side_effect=ResearchTerminatedException("Research terminated")+ )++ with pytest.raises(+ ResearchTerminatedException, match="Research terminated"+ ):+ strategy.check_termination()+++class TestStrategiesCallCheckTermination:+ """Verify each strategy calls check_termination() in its main loop."""++ def test_iterative_reasoning_calls_check(self):+ from local_deep_research.advanced_search_system.strategies.iterative_reasoning_strategy import (+ IterativeReasoningStrategy,+ )++ source = inspect.getsource(IterativeReasoningStrategy.analyze_topic)+ assert "self.check_termination()" in source++ def test_iterative_refinement_calls_check(self):+ from local_deep_research.advanced_search_system.strategies.iterative_refinement_strategy import (+ IterativeRefinementStrategy,+ )++ source = inspect.getsource(IterativeRefinementStrategy.analyze_topic)+ assert "self.check_termination()" in source++ def test_source_based_calls_check(self):+ from local_deep_research.advanced_search_system.strategies.source_based_strategy import (+ SourceBasedSearchStrategy,+ )++ source = inspect.getsource(SourceBasedSearchStrategy.analyze_topic)+ assert "self.check_termination()" in source+++class TestResearchTerminatedException:+ """Verify ResearchTerminatedException class properties."""++ def test_is_base_exception_subclass(self):+ """ResearchTerminatedException should be a subclass of BaseException, not Exception."""+ assert issubclass(ResearchTerminatedException, BaseException)+ assert not issubclass(ResearchTerminatedException, Exception)++ def test_distinguishable_from_generic(self):+ """isinstance should distinguish ResearchTerminatedException from generic Exception."""+ termination_exc = ResearchTerminatedException("cancelled")+ generic_exc = Exception("some error")++ assert isinstance(termination_exc, ResearchTerminatedException)+ assert isinstance(termination_exc, BaseException)+ assert not isinstance(termination_exc, Exception)+ assert not isinstance(generic_exc, ResearchTerminatedException)++ def test_except_exception_does_not_catch(self):+ """The core guarantee: except Exception blocks can't swallow termination."""+ with pytest.raises(ResearchTerminatedException):+ try:+ raise ResearchTerminatedException("cancelled")+ except Exception:+ pass # Must NOT catch it+++class TestTerminationCheckPhaseSkipsLogging:+ """Verify that termination_check phase is handled silently in research_service."""++ def test_research_service_handles_termination_check_phase(self):+ """research_service progress_callback should early-return for termination_check phase."""+ from local_deep_research.web.services import research_service++ source = inspect.getsource(research_service)+ # Verify the early return for termination_check phase exists+ assert 'metadata.get("phase") == "termination_check"' in sourcediff --git a/tests/strategies/test_edge_cases.py b/tests/strategies/test_edge_cases.pyindex 1bdb4dd0f7..7f2ecdd154 100644--- a/tests/strategies/test_edge_cases.py+++ b/tests/strategies/test_edge_cases.py@@ -468,12 +468,12 @@ class TestProgressCallback:strategy.set_progress_callback(track_progress)strategy.analyze_topic("Test query")- # Progress values should be non-negative+ # Progress values should be non-negative (None is valid for optional updates)for p in progress_values:- assert p >= 0, f"Negative progress value: {p}"+ assert p is None or p >= 0, f"Negative progress value: {p}"# Document any values exceeding 100 as warnings for later analysis- over_100 = [p for p in progress_values if p > 100]+ over_100 = [p for p in progress_values if p is not None and p > 100]if over_100:logger.warning(f"{strategy_name} reported progress > 100: {over_100}. "