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(strategies): cancel focused-iteration research within current iteration (#4872)

S57a31f97bd91
diff --git a/changelog.d/+focused-iteration-cancellation-lag.bugfix.md b/changelog.d/+focused-iteration-cancellation-lag.bugfix.md
new file mode 100644
index 0000000000..8aea988f2f
--- /dev/null
+++ b/changelog.d/+focused-iteration-cancellation-lag.bugfix.md
@@ -0,0 +1 @@
+Fixed a 30–50 second visible lag between clicking **Stop** and a focused-iteration research actually stopping. `FocusedIterationStrategy.analyze_topic` now calls `self.check_termination()` at the start of every iteration, after the parallel search (before optional verification searches), and just before the final synthesis LLM call, so a cancellation request is detected within the current iteration rather than only at the next iteration's progress emit.
diff --git a/src/local_deep_research/advanced_search_system/strategies/focused_iteration_strategy.py b/src/local_deep_research/advanced_search_system/strategies/focused_iteration_strategy.py
index 4952f5ecd6..477f67a6ef 100644
--- a/src/local_deep_research/advanced_search_system/strategies/focused_iteration_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/focused_iteration_strategy.py
@@ -27,8 +27,8 @@ from ...citation_handler import CitationHandler
# Model and search should be provided by AdvancedSearchSystem
from ...utilities.thread_context import (
- preserve_research_context,
get_search_context,
+ preserve_research_context,
)
from ..candidate_exploration import ProgressiveExplorer
from ..findings.repository import FindingsRepository
@@ -166,6 +166,8 @@ class FocusedIterationStrategy(BaseSearchStrategy):
try:
# Main iteration loop
for iteration in range(1, self.max_iterations + 1):
+ # Check cancellation before each iteration to avoid 30-50s lag between Stop click and actual halt.
+ self.check_termination()
iteration_progress = 10 + (iteration - 1) * (
80 / self.max_iterations
)
@@ -237,6 +239,9 @@ class FocusedIterationStrategy(BaseSearchStrategy):
extracted_entities=extracted_entities,
)
+ # Check cancellation to prevent verification searches adding 10-30s after Stop.
+ self.check_termination()
+
# Log results but don't send progress update to avoid jumps
logger.info(
f"Found {len(search_progress.found_candidates)} candidates, "
@@ -310,6 +315,9 @@ class FocusedIterationStrategy(BaseSearchStrategy):
# to the shared list automatically.
self.all_links_of_system.extend(self.all_search_results)
+ # Check cancellation before final synthesis to prevent 10-30s delay after Stop.
+ self.check_termination()
+
# Final synthesis (like source-based - trust the LLM!)
self._update_progress(
f"Synthesizing {len(self.all_search_results)} sources from {len(self.questions_by_iteration)} iterations...",
diff --git a/tests/advanced_search_system/strategies/test_focused_iteration_high_value.py b/tests/advanced_search_system/strategies/test_focused_iteration_high_value.py
index 3096f249bb..e8fcfd71fd 100644
--- a/tests/advanced_search_system/strategies/test_focused_iteration_high_value.py
+++ b/tests/advanced_search_system/strategies/test_focused_iteration_high_value.py
@@ -8,6 +8,7 @@ LLM or network calls.
from unittest.mock import MagicMock, patch
+import pytest
# ---------------------------------------------------------------------------
# Helper: build a FocusedIterationStrategy with the constructor fully mocked
@@ -237,6 +238,249 @@ class TestCreateErrorResponse:
assert resp["formatted_findings"] == "Error: No search engine available"
+# =========================================================================
+# Cancellation regression — see test_cancellation_checks for the static
+# source-grep check; this is the behavioural counterpart that actually
+# runs analyze_topic and asserts the loop honours a mid-flight cancel.
+# =========================================================================
+
+
+class TestCancellationDuringIterations:
+ """Verify analyze_topic stops promptly when cancellation is requested.
+
+ Bug history: FocusedIterationStrategy.analyze_topic() used to never
+ call ``self.check_termination()`` inside its main loop. The only
+ progress emits during the strategy were at the *start* of each
+ iteration, so a user clicking Stop mid-iteration had to wait for
+ the in-flight LLM question-generation call and parallel search to
+ finish before the next iteration's progress emit re-checked the
+ flag. With default settings (8 iterations × ~5 questions + a final
+ LLM synthesis) that produced a visible 30-50 second lag between the
+ UI confirming cancellation and the research actually stopping.
+ """
+
+ def _make_strategy_with_callback(self, cancel_on_call: int):
+ """Build a strategy whose callback raises ``ResearchTerminatedException``
+ on the Nth invocation (matching the progress_callback wired up in
+ ``research_service.run_research_process``).
+ """
+ from local_deep_research.exceptions import (
+ ResearchTerminatedException,
+ )
+
+ call_counter = {"n": 0}
+
+ def callback(message, progress_percent, metadata):
+ call_counter["n"] += 1
+ if call_counter["n"] == cancel_on_call:
+ raise ResearchTerminatedException("cancelled")
+
+ return _make_strategy(), callback, call_counter
+
+ def test_cancel_during_first_iteration_stops_loop(self):
+ """When the cancel fires on the first termination_check, no
+ iteration of question generation should run."""
+ from local_deep_research.exceptions import (
+ ResearchTerminatedException,
+ )
+
+ strategy, callback, counter = self._make_strategy_with_callback(
+ cancel_on_call=1
+ )
+ strategy.set_progress_callback(callback)
+
+ # Spy on question generation — if cancellation works, this MUST
+ # NOT be called because the loop bails before question generation.
+ with patch.object(
+ strategy.question_generator,
+ "generate_questions",
+ return_value=["Q1"],
+ ) as gen_mock:
+ with patch.object(
+ strategy.citation_handler,
+ "analyze_followup",
+ return_value={"content": "Done", "documents": []},
+ ):
+ with pytest.raises(ResearchTerminatedException):
+ strategy.analyze_topic("test query")
+
+ assert gen_mock.call_count == 0, (
+ "check_termination() should fire BEFORE the first question-"
+ "generation call so a cancel during the early 'init' "
+ "progress emit stops the loop with zero iterations."
+ )
+
+ def test_cancel_after_initialization_runs_no_iterations(self):
+ """Even if cancel fires a couple of progress emits in (e.g. after
+ the 'initializing' milestone), the loop must stop without
+ completing any full iteration's question generation."""
+ from local_deep_research.exceptions import (
+ ResearchTerminatedException,
+ )
+
+ # Cancel fires on the 3rd callback call. The first call is the
+ # "Initializing" milestone, the second is the first
+ # _emit_question_generation_progress emit — cancel there means
+ # the very first iteration must not run any question generation.
+ strategy, callback, counter = self._make_strategy_with_callback(
+ cancel_on_call=3
+ )
+ strategy.set_progress_callback(callback)
+
+ with patch.object(
+ strategy.question_generator,
+ "generate_questions",
+ return_value=["Q1"],
+ ) as gen_mock:
+ with patch.object(
+ strategy.citation_handler,
+ "analyze_followup",
+ return_value={"content": "Done", "documents": []},
+ ):
+ with pytest.raises(ResearchTerminatedException):
+ strategy.analyze_topic("test query")
+
+ assert gen_mock.call_count == 0
+
+ def test_cancel_between_iterations_stops_loop(self):
+ """A cancel that fires after iteration 1 completes must stop the
+ loop before iteration 2 starts its question generation.
+
+ Walk-through of the callback sequence with the fix in place
+ (default max_iterations=8, use_browsecomp_optimization=True):
+
+ iter 1:
+ cb 1: termination_check (loop entry check)
+ cb 2: question_generation (progress milestone)
+ (LLM question-generation runs)
+ (explorer.explore() runs, no callbacks)
+ cb 3: termination_check (after-explore check)
+ iter 2:
+ cb 4: termination_check (loop entry check — CANCEL HERE)
+
+ So cancelling on the 4th callback (start of iteration 2's loop
+ body) is the correct expression of "cancel detected between
+ iterations". Before the fix, ``analyze_topic`` had no
+ ``check_termination()`` call in the loop at all, so the test
+ would NOT raise — proving the bug.
+ """
+ from local_deep_research.exceptions import (
+ ResearchTerminatedException,
+ )
+
+ strategy = _make_strategy()
+ call_counter = {"n": 0}
+
+ def callback(message, progress_percent, metadata):
+ call_counter["n"] += 1
+ # Cancel at the start of iteration 2's loop body (cb 4),
+ # i.e. after iteration 1 has fully completed.
+ if call_counter["n"] == 4:
+ raise ResearchTerminatedException("cancelled")
+
+ strategy.set_progress_callback(callback)
+
+ gen_call_count = {"n": 0}
+
+ def gen_questions(**kwargs):
+ gen_call_count["n"] += 1
+ return ["Q1"]
+
+ # The strategy does ``all_search_results.extend(iteration_results)``
+ # so iteration_results must be iterable. Returning a plain list
+ # is enough — we only care about the cancel being honoured.
+ class _FakeSearchProgress:
+ found_candidates = []
+ entity_coverage = {}
+
+ with (
+ patch.object(
+ strategy.question_generator,
+ "generate_questions",
+ side_effect=gen_questions,
+ ),
+ patch.object(
+ strategy.explorer,
+ "explore",
+ return_value=([], _FakeSearchProgress()),
+ ),
+ patch.object(
+ strategy.explorer,
+ "suggest_next_searches",
+ return_value=[],
+ ),
+ patch.object(
+ strategy.citation_handler,
+ "analyze_followup",
+ return_value={"content": "Done", "documents": []},
+ ),
+ ):
+ with pytest.raises(ResearchTerminatedException):
+ strategy.analyze_topic("test query")
+
+ # Iteration 1 ran its question generation, but iteration 2 must
+ # NOT have. Before the fix there was no check_termination() in
+ # the loop at all, so this would have been 8 (default
+ # max_iterations).
+ assert gen_call_count["n"] == 1, (
+ "Cancel between iteration 1 and iteration 2 must stop the "
+ "loop before iteration 2's question-generation call. Got "
+ f"{gen_call_count['n']} generation calls; expected exactly 1 "
+ "(one for iteration 1, zero for iteration 2)."
+ )
+
+ def test_cancel_during_synthesis_aborts_before_llm_call(self):
+ """A cancel that arrives while the synthesis LLM call would
+ otherwise run must abort the strategy before that LLM call."""
+ from local_deep_research.exceptions import (
+ ResearchTerminatedException,
+ )
+
+ strategy = _make_strategy(max_iterations=1)
+
+ # The pre-synthesis check_termination() is the LAST
+ # termination_check callback before _update_progress("Synthesizing…").
+ # Cancel on that termination_check so we assert the synthesis LLM
+ # call (analyze_followup) is never reached.
+ call_counter = {"n": 0, "saw_termination_before_synthesis": False}
+
+ def callback(message, progress_percent, metadata):
+ call_counter["n"] += 1
+ # The pre-synthesis check fires with phase=termination_check
+ # and message="Checking termination status" *before* the
+ # "Synthesizing …" milestone.
+ if metadata.get(
+ "phase"
+ ) == "termination_check" and "Synthesizing" not in (message or ""):
+ call_counter["saw_termination_before_synthesis"] = True
+ raise ResearchTerminatedException("cancelled")
+
+ strategy.set_progress_callback(callback)
+
+ with (
+ patch.object(
+ strategy.question_generator,
+ "generate_questions",
+ return_value=["Q1"],
+ ),
+ patch.object(
+ strategy.citation_handler,
+ "analyze_followup",
+ return_value={"content": "Done", "documents": []},
+ ) as synth_mock,
+ ):
+ with pytest.raises(ResearchTerminatedException):
+ strategy.analyze_topic("test query")
+
+ assert call_counter["saw_termination_before_synthesis"] is True, (
+ "Expected a termination_check callback before synthesis"
+ )
+ assert synth_mock.call_count == 0, (
+ "Pre-synthesis check_termination() must abort before the "
+ "synthesis LLM call (analyze_followup) is invoked"
+ )
+
+
# =========================================================================
# _get_current_knowledge_summary
# =========================================================================
diff --git a/tests/strategies/test_cancellation_checks.py b/tests/strategies/test_cancellation_checks.py
index e2d40be280..8bc39126a9 100644
--- a/tests/strategies/test_cancellation_checks.py
+++ b/tests/strategies/test_cancellation_checks.py
@@ -8,9 +8,10 @@ Verifies:
"""
import inspect
-import pytest
from unittest.mock import MagicMock
+import pytest
+
from local_deep_research.advanced_search_system.strategies.base_strategy import (
BaseSearchStrategy,
)
@@ -78,6 +79,24 @@ class TestStrategiesCallCheckTermination:
source = inspect.getsource(SourceBasedSearchStrategy.analyze_topic)
assert "self.check_termination()" in source
+ def test_focused_iteration_calls_check(self):
+ """FocusedIterationStrategy.analyze_topic must call check_termination().
+
+ Regression test for the bug where cancelling a focused-iteration
+ research would take 30-50 seconds to actually stop because the
+ strategy's main loop never re-checked the termination flag — it
+ only fired progress emits at the START of each iteration, so a
+ cancel clicked mid-iteration had to wait for the in-flight LLM
+ question-generation call and parallel search to finish before
+ the next iteration's progress emit re-checked the flag.
+ """
+ from local_deep_research.advanced_search_system.strategies.focused_iteration_strategy import (
+ FocusedIterationStrategy,
+ )
+
+ source = inspect.getsource(FocusedIterationStrategy.analyze_topic)
+ assert "self.check_termination()" in source
+
class TestResearchTerminatedException:
"""Verify ResearchTerminatedException class properties."""