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): propagate progress callback to topic-organization delegates (#4871 follow-up) (#5114)

LearningCircuit9ba45e81d7f5
diff --git a/changelog.d/+topic-organization-delegate-cancellation.bugfix.md b/changelog.d/+topic-organization-delegate-cancellation.bugfix.md
new file mode 100644
index 0000000000..75ca40f09a
--- /dev/null
+++ b/changelog.d/+topic-organization-delegate-cancellation.bugfix.md
@@ -0,0 +1 @@
+Fixed Stop requests being ignored for the entire source-gathering phase of a topic-organization research. `TopicOrganizationStrategy` never passed its progress callback on to the source-gathering strategy it delegates to, so all of the delegate's termination checks were silent no-ops and a click on **Stop** was only honoured once the delegate had completely finished (often minutes later). The callback is now propagated to both the main source-gathering delegate and the per-iteration refinement strategies.
diff --git a/src/local_deep_research/advanced_search_system/strategies/topic_organization_strategy.py b/src/local_deep_research/advanced_search_system/strategies/topic_organization_strategy.py
index 10fa8e1808..9a59c8ecbd 100644
--- a/src/local_deep_research/advanced_search_system/strategies/topic_organization_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/topic_organization_strategy.py
@@ -152,6 +152,44 @@ class TopicOrganizationStrategy(BaseSearchStrategy):
# Topic graph to store organized topics
self.topic_graph = TopicGraph()
+ def set_progress_callback(self, callback) -> None:
+ """Set progress callback for both this strategy and its delegate.
+
+ Without this propagation the delegate's ``check_termination()``
+ calls are silent no-ops (``BaseSearchStrategy.check_termination``
+ returns immediately when ``progress_callback`` is None), so a
+ Stop click during the multi-minute source-gathering phase would
+ not be detected until the delegate finished (#4871).
+
+ Only termination-check callbacks are forwarded to the delegate;
+ ordinary progress events (phase transitions, percentages) emitted
+ by the delegate are suppressed so they don't leak into the outer
+ strategy's event stream (#5114).
+ """
+ super().set_progress_callback(callback)
+ if hasattr(self, "source_strategy"):
+ self.source_strategy.set_progress_callback(
+ self._make_termination_only_callback(callback)
+ if callback
+ else None
+ )
+
+ @staticmethod
+ def _make_termination_only_callback(callback):
+ """Wrap *callback* so only termination-check calls propagate.
+
+ ``BaseSearchStrategy.check_termination`` invokes the callback
+ with ``metadata['phase'] == 'termination_check'``; all other
+ calls (ordinary ``_update_progress`` emissions) are silently
+ dropped so delegate progress events don't reach the outer stream.
+ """
+
+ def _filtered(message, progress_percent, metadata):
+ if metadata and metadata.get("phase") == "termination_check":
+ callback(message, progress_percent, metadata)
+
+ return _filtered
+
def _extract_topics_from_sources(
self,
sources: List[Dict[str, Any]],
@@ -939,9 +977,9 @@ Otherwise, respond with only the follow-up question, nothing else.
logger.info(f"Starting topic organization for: {query}")
# Check cancellation before delegating to the source-gathering
- # strategy. The delegate has its own checks, but the LLM topic-
- # extraction call below this point can also take 10-30 s, so we
- # want to give the user a chance to bail before we pay that cost.
+ # strategy. The delegate's own checks are live because
+ # set_progress_callback propagates our callback to it; this check
+ # catches a Stop click that arrives before any work starts.
self.check_termination(CHECK_CONTEXT_ENTRY)
strategy_name = (
@@ -1193,6 +1231,15 @@ Otherwise, respond with only the follow-up question, nothing else.
search_original_query=self.search_original_query,
)
+ # Keep the refinement delegate's termination checks live —
+ # without the callback they are silent no-ops (see
+ # set_progress_callback). Only termination checks are
+ # forwarded so delegate progress events don't leak (#5114).
+ if self.progress_callback is not None:
+ refinement_source_strategy.set_progress_callback(
+ self._make_termination_only_callback(self.progress_callback)
+ )
+
# Wrap in preserve_research_context to maintain context
@preserve_research_context
def _call_refinement_search(q):
diff --git a/tests/advanced_search_system/strategies/test_strategy_cancellation_regression.py b/tests/advanced_search_system/strategies/test_strategy_cancellation_regression.py
index 7dc2cc6271..928fcab69f 100644
--- a/tests/advanced_search_system/strategies/test_strategy_cancellation_regression.py
+++ b/tests/advanced_search_system/strategies/test_strategy_cancellation_regression.py
@@ -275,6 +275,126 @@ class TestTopicOrganizationCancellation:
assert fired["n"] == 1
assert refinement_gen_mock.call_count == 0
+ def test_progress_callback_propagates_to_delegate(self):
+ """Pins the set_progress_callback override: without propagation the
+ delegate's check_termination() calls are silent no-ops and a Stop
+ during source gathering is not detected until the delegate ends."""
+ strategy = _make_topic_org_strategy()
+
+ received = []
+
+ def callback(message, progress_percent, metadata):
+ received.append((message, progress_percent, metadata))
+
+ strategy.set_progress_callback(callback)
+ # The delegate receives a filtered callback, not the raw one.
+ delegate_cb = strategy.source_strategy.progress_callback
+ assert delegate_cb is not callback
+ assert callable(delegate_cb)
+
+ # Termination checks propagate through the filter.
+ delegate_cb("Checking", None, {"phase": "termination_check"})
+ assert len(received) == 1
+ assert received[0][2]["phase"] == "termination_check"
+
+ # Ordinary progress events are suppressed.
+ delegate_cb("Searching", 50, {"phase": "parallel_search"})
+ delegate_cb("Synthesizing", 90, {"phase": "synthesis"})
+ assert len(received) == 1 # still only the termination check
+
+ def test_cancel_during_delegate_gathering_stops_delegate(self):
+ """End-to-end: with the callback propagated, the delegate's own
+ iteration_start check fires — the delegate stops before generating
+ any questions. The outer strategy never emits iteration_start, so
+ this cancels inside the delegate or not at all."""
+ from local_deep_research.exceptions import ResearchTerminatedException
+
+ strategy = _make_topic_org_strategy()
+ callback, fired = _cancel_on_context(CHECK_CONTEXT_ITERATION_START)
+ strategy.set_progress_callback(callback)
+ delegate_gen_mock = MagicMock(return_value=["Q1"])
+ with (
+ patch.object(
+ strategy.source_strategy.question_generator,
+ "generate_questions",
+ delegate_gen_mock,
+ ),
+ patch(
+ "local_deep_research.advanced_search_system.strategies.source_based_strategy.run_parallel_searches",
+ return_value=[],
+ ),
+ ):
+ with pytest.raises(ResearchTerminatedException):
+ strategy.analyze_topic("topic query")
+ assert fired["n"] == 1
+ assert delegate_gen_mock.call_count == 0
+
+ def test_cancel_during_refinement_gathering_stops_refinement_delegate(
+ self,
+ ):
+ """Pins the callback propagation to the per-iteration refinement
+ strategy: the refinement delegate's own iteration_start check
+ fires, so it stops before its question-generation LLM call. The
+ main delegate is a mock here, so the refinement delegate is the
+ only possible source of an iteration_start check."""
+ from local_deep_research.exceptions import ResearchTerminatedException
+
+ strategy = _make_topic_org_strategy()
+ strategy.enable_refinement = True
+ strategy.max_refinement_iterations = 2
+ strategy.refinement_questions = []
+ strategy.topic_graph = MagicMock()
+ strategy.source_strategy = MagicMock()
+ strategy.source_strategy.analyze_topic = MagicMock(
+ return_value={
+ "all_links_of_system": [
+ {"title": "T", "snippet": "S", "link": "http://x"}
+ ],
+ "iterations": 1,
+ "questions_by_iteration": {},
+ }
+ )
+ callback, fired = _cancel_on_context(CHECK_CONTEXT_ITERATION_START)
+ strategy.set_progress_callback(callback)
+ topic_mock = MagicMock()
+ topic_mock.title = "Stub topic"
+ topic_mock.get_all_sources = MagicMock(
+ return_value=[{"link": "http://x"}]
+ )
+ # Finite side_effect ending in None so the loop can never spin
+ # forever, whatever happens to the checks under test.
+ refinement_gen_mock = MagicMock(side_effect=["another question", None])
+ # The refinement strategy is constructed inside the loop, so its
+ # question generator can only be intercepted at the class level.
+ refinement_question_gen = MagicMock(return_value=["Q1"])
+ with (
+ patch.object(
+ strategy,
+ "_extract_topics_from_sources",
+ return_value=[topic_mock],
+ ),
+ patch.object(
+ strategy, "_generate_refinement_question", refinement_gen_mock
+ ),
+ patch.object(strategy, "_find_topic_relationships"),
+ patch(
+ "local_deep_research.advanced_search_system.questions.standard_question.StandardQuestionGenerator.generate_questions",
+ refinement_question_gen,
+ ),
+ patch(
+ "local_deep_research.advanced_search_system.strategies.source_based_strategy.run_parallel_searches",
+ return_value=[],
+ ),
+ ):
+ with pytest.raises(ResearchTerminatedException):
+ strategy.analyze_topic("topic query")
+ assert fired["n"] == 1
+ # A refinement question was generated (the loop genuinely started) …
+ assert refinement_gen_mock.call_count == 1
+ # … and the refinement delegate stopped at its own loop-entry
+ # check, before its question-generation LLM call.
+ assert refinement_question_gen.call_count == 0
+
# EnhancedContextualFollowupStrategy
def _make_followup_strategy():
diff --git a/tests/strategies/test_cancellation_checks.py b/tests/strategies/test_cancellation_checks.py
index 0b9561053c..143511981f 100644
--- a/tests/strategies/test_cancellation_checks.py
+++ b/tests/strategies/test_cancellation_checks.py
@@ -1,4 +1,4 @@
-"""Tests for strategy cancellation checks (PR #2452).
+"""Tests for strategy cancellation checks (PRs #4872, #5092).
Verifies:
- BaseSearchStrategy.check_termination() calls progress_callback