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.

refactor(search): extract run_parallel_searches helper (DRY) (#4717)

LearningCircuitab8820b8b6d7
diff --git a/src/local_deep_research/advanced_search_system/candidate_exploration/progressive_explorer.py b/src/local_deep_research/advanced_search_system/candidate_exploration/progressive_explorer.py
index d646921d72..5d27fc131e 100644
--- a/src/local_deep_research/advanced_search_system/candidate_exploration/progressive_explorer.py
+++ b/src/local_deep_research/advanced_search_system/candidate_exploration/progressive_explorer.py
@@ -2,13 +2,13 @@
Progressive explorer for BrowseComp-style systematic search exploration.
"""
-import concurrent.futures
from dataclasses import dataclass, field
from typing import Dict, List, Set, Tuple
from loguru import logger
from ...utilities.thread_context import preserve_research_context
+from ..parallel_search import run_parallel_searches
@dataclass
@@ -240,22 +240,18 @@ class ProgressiveExplorer:
def search_query(query):
try:
search_results = self.search_engine.run(query)
- return (query, search_results or [])
+ return search_results or []
except Exception:
logger.exception(f"Error searching '{query}'")
- return (query, [])
+ return []
# Create context-preserving wrapper for the search function
context_aware_search = preserve_research_context(search_query)
# Run searches in parallel
- with concurrent.futures.ThreadPoolExecutor(
- max_workers=max_workers
- ) as executor:
- futures = [
- executor.submit(context_aware_search, q) for q in queries
- ]
- for future in concurrent.futures.as_completed(futures):
- results.append(future.result())
+ completed = run_parallel_searches(
+ queries, context_aware_search, max_workers=max_workers
+ )
+ results.extend(completed)
return results
diff --git a/src/local_deep_research/advanced_search_system/parallel_search.py b/src/local_deep_research/advanced_search_system/parallel_search.py
new file mode 100644
index 0000000000..fae2de78c1
--- /dev/null
+++ b/src/local_deep_research/advanced_search_system/parallel_search.py
@@ -0,0 +1,109 @@
+"""Parallel search execution helper.
+
+Provides :func:`run_parallel_searches`, a small helper that runs a sequence
+of search queries concurrently using :class:`~concurrent.futures.ThreadPoolExecutor`
+while preserving the research/Flask contexts expected by worker threads.
+
+The helper is intentionally generic:
+
+* ``search_fn`` is a callable accepting the query string and returning
+ whatever per-query payload the caller needs (a list of results, a dict
+ with metadata, etc.). Callers wrap it with context-preserving
+ decorators (e.g. :func:`preserve_research_context`) before passing it
+ in; this helper stays focused on the concurrency concern.
+* ``context_factory`` is an optional zero-arg callable (e.g.
+ :func:`~local_deep_research.utilities.threading_utils.thread_context`)
+ that returns a **fresh** Flask :class:`~flask.ctx.AppContext` for one
+ worker thread. It is invoked once per query *on the calling thread* and
+ the resulting context is pushed into the matching worker via
+ :func:`~local_deep_research.utilities.threading_utils.thread_with_app_context`.
+ A single :class:`~flask.ctx.AppContext` instance must never be shared
+ across concurrent threads — Flask tracks the context-var token stack on
+ the instance, so concurrent push/pop from multiple threads raises
+ ``ValueError: <Token> was created in a different Context``. ``None``
+ disables context propagation, preserving the behavior of strategies that
+ never propagated a context (e.g. focused-iteration, progressive).
+
+Returns a list of ``(query, payload)`` tuples in completion order.
+Callers that need a question-keyed dict build it from this list; callers
+that only need a flat list of results flatten it directly.
+"""
+
+from __future__ import annotations
+
+import concurrent.futures
+from typing import Callable, List, Optional, Tuple, TypeVar
+
+from flask.ctx import AppContext
+from loguru import logger
+
+from ..utilities.threading_utils import thread_with_app_context
+
+T = TypeVar("T")
+
+
+def run_parallel_searches(
+ queries: List[str],
+ search_fn: Callable[[str], T],
+ max_workers: Optional[int] = None,
+ context_factory: Optional[Callable[[], Optional[AppContext]]] = None,
+) -> List[Tuple[str, T]]:
+ """Run ``search_fn`` for each query in parallel.
+
+ Args:
+ queries: Queries to search. If empty, returns an empty list
+ immediately (and logs a warning).
+ search_fn: Callable invoked as ``search_fn(query)`` inside a worker
+ thread. Callers are responsible for wrapping it with any
+ context-preserving decorators (e.g.
+ :func:`preserve_research_context`) before passing it in, and
+ for their own error handling (the callable should never raise
+ — return an empty payload on failure instead, matching the
+ pre-existing contract of the strategies this was extracted
+ from).
+ max_workers: Size of the thread pool. Defaults to ``len(queries)``
+ when ``None``, matching the historical behavior of the
+ source-based, focused-iteration, and progressive strategies.
+ context_factory: Optional zero-arg callable returning a **fresh**
+ Flask app context per call (e.g.
+ :func:`~local_deep_research.utilities.threading_utils.thread_context`).
+ Invoked once per query on the calling thread; each worker gets
+ its own context. Passing a single shared context instead would
+ crash under concurrency, so a factory (not a context) is
+ required. ``None`` disables context propagation, preserving the
+ behavior of strategies that never propagated a context.
+
+ Returns:
+ A list of ``(query, payload)`` tuples in completion order. Each
+ ``payload`` is whatever ``search_fn`` returned for that query.
+ """
+ if not queries:
+ logger.warning("No queries provided for parallel search")
+ return []
+
+ if max_workers is None:
+ max_workers = len(queries)
+
+ @thread_with_app_context
+ def _worker(query: str) -> Tuple[str, T]:
+ return (query, search_fn(query))
+
+ with concurrent.futures.ThreadPoolExecutor(
+ max_workers=max_workers
+ ) as executor:
+ # context_factory() is called here on the calling thread, once per
+ # query, so every worker receives its own fresh AppContext. Sharing
+ # one instance across workers is what raises "Token was created in a
+ # different Context".
+ futures = [
+ executor.submit(
+ _worker,
+ context_factory() if context_factory is not None else None,
+ q,
+ )
+ for q in queries
+ ]
+ return [
+ future.result()
+ for future in concurrent.futures.as_completed(futures)
+ ]
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 82466d87ae..63758e579e 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
@@ -19,7 +19,6 @@ should preserve the core approach that achieves 96.51% accuracy.
when use_browsecomp_optimization=True, but SimpleQA performance is the priority.
"""
-import concurrent.futures
from typing import Dict, List
from loguru import logger
@@ -33,6 +32,7 @@ from ...utilities.thread_context import (
)
from ..candidate_exploration import ProgressiveExplorer
from ..findings.repository import FindingsRepository
+from ..parallel_search import run_parallel_searches
from ..questions import BrowseCompQuestionGenerator
from .base_strategy import BaseSearchStrategy
@@ -370,8 +370,6 @@ class FocusedIterationStrategy(BaseSearchStrategy):
logger.warning("No queries provided for parallel search")
return []
- all_results = []
-
def search_question(q):
try:
# Get the current research context to pass explicitly
@@ -386,18 +384,14 @@ class FocusedIterationStrategy(BaseSearchStrategy):
# Create context-preserving wrapper for the search function
context_aware_search = preserve_research_context(search_question)
- # Run searches in parallel
- with concurrent.futures.ThreadPoolExecutor(
- max_workers=len(queries)
- ) as executor:
- futures = [
- executor.submit(context_aware_search, q) for q in queries
- ]
-
- for future in concurrent.futures.as_completed(futures):
- result_dict = future.result()
- all_results.extend(result_dict.get("results", []))
-
+ # Run searches in parallel. No Flask app_context is propagated here
+ # (pre-existing behavior) — this strategy does not push a context
+ # into the worker threads and relies only on the research-context
+ # preservation above.
+ completed = run_parallel_searches(queries, context_aware_search)
+ all_results: List[Dict] = []
+ for _, payload in completed:
+ all_results.extend(payload.get("results", []))
return all_results
def _get_current_knowledge_summary(self) -> str:
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.py
index 7d3fd57dfd..11d1658597 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
@@ -1,4 +1,3 @@
-import concurrent.futures
from typing import Dict
from loguru import logger
@@ -11,9 +10,10 @@ from ...utilities.thread_context import (
preserve_research_context,
get_search_context,
)
-from ...utilities.threading_utils import thread_context, thread_with_app_context
+from ...utilities.threading_utils import thread_context
from ..filters.cross_engine_filter import CrossEngineFilter
from ..findings.repository import FindingsRepository
+from ..parallel_search import run_parallel_searches
from ..questions.atomic_fact_question import AtomicFactQuestionGenerator
from ..questions.standard_question import StandardQuestionGenerator
from .base_strategy import BaseSearchStrategy
@@ -355,7 +355,6 @@ class SourceBasedSearchStrategy(BaseSearchStrategy):
# Each question becomes a separate search query executed concurrently.
# Results are collected into iteration_search_results, then extended
# into accumulated_search_results_across_all_iterations.
- @thread_with_app_context
@preserve_research_context
def search_question(q):
try:
@@ -372,24 +371,23 @@ class SourceBasedSearchStrategy(BaseSearchStrategy):
"error": "Search failed",
}
- # Run searches in parallel
- with concurrent.futures.ThreadPoolExecutor(
- max_workers=len(all_questions)
- ) as executor:
- futures = [
- executor.submit(search_question, thread_context(), q)
- for q in all_questions
+ # Run searches in parallel. thread_context (the factory, not
+ # a call) is invoked once per question so each worker thread
+ # gets its OWN fresh Flask app context — required so
+ # current_app / g are accessible inside self.search.run, and
+ # so concurrent workers never share one context instance.
+ completed = run_parallel_searches(
+ all_questions,
+ search_question,
+ context_factory=thread_context,
+ )
+ iteration_search_dict = {}
+ iteration_search_results = []
+ for _, payload in completed:
+ iteration_search_dict[payload["question"]] = payload[
+ "results"
]
- iteration_search_dict = {}
- iteration_search_results = []
-
- # Process results as they complete (no per-search progress to avoid jumps)
- for future in concurrent.futures.as_completed(futures):
- result_dict = future.result()
- question = result_dict["question"]
- search_results = result_dict["results"]
- iteration_search_dict[question] = search_results
- iteration_search_results.extend(search_results)
+ iteration_search_results.extend(payload["results"])
# Collect this iteration's results. Note: filtered_search_results is
# reassigned each iteration — it only holds the CURRENT iteration's results.
diff --git a/tests/advanced_search_system/test_parallel_search.py b/tests/advanced_search_system/test_parallel_search.py
new file mode 100644
index 0000000000..943c0da8a7
--- /dev/null
+++ b/tests/advanced_search_system/test_parallel_search.py
@@ -0,0 +1,91 @@
+"""Smoke tests for the run_parallel_searches helper.
+
+These verify the contract documented in the module:
+
+* empty input short-circuits to an empty list
+* non-empty input returns one ``(query, payload)`` tuple per query
+* ``search_fn`` may return any payload type (list, dict, etc.)
+* ``context_factory=None`` path works (no Flask context required)
+* ``context_factory`` is invoked once per query so each worker gets a
+ fresh Flask app context — sharing one context across concurrent workers
+ raises ``ValueError: <Token> was created in a different Context``
+"""
+
+import threading
+
+from flask import Flask
+
+from local_deep_research.advanced_search_system.parallel_search import (
+ run_parallel_searches,
+)
+
+
+def test_empty_queries_returns_empty_list():
+ assert run_parallel_searches([], lambda q: [q]) == []
+
+
+def test_returns_one_tuple_per_query():
+ results = run_parallel_searches(["a", "b", "c"], lambda q: [q.upper()])
+ assert sorted(results) == [("a", ["A"]), ("b", ["B"]), ("c", ["C"])]
+
+
+def test_payload_can_be_dict():
+ results = run_parallel_searches(
+ ["x", "y"], lambda q: {"question": q, "results": [q]}
+ )
+ assert sorted(results) == [
+ ("x", {"question": "x", "results": ["x"]}),
+ ("y", {"question": "y", "results": ["y"]}),
+ ]
+
+
+def test_max_workers_passed_through():
+ # Smoke test: helper accepts max_workers without error.
+ results = run_parallel_searches(["a", "b", "c"], lambda q: q, max_workers=2)
+ assert sorted(results) == [("a", "a"), ("b", "b"), ("c", "c")]
+
+
+def test_default_max_workers():
+ # When max_workers is None, defaults to len(queries). Smoke test only.
+ results = run_parallel_searches(["a"], lambda q: q)
+ assert results == [("a", "a")]
+
+
+def test_context_factory_called_once_per_query():
+ """The factory is invoked once per query (a fresh context per worker),
+ never a single shared instance."""
+ from unittest.mock import MagicMock
+
+ # side_effect returns a brand-new context-manager mock on every call.
+ factory = MagicMock(side_effect=lambda: MagicMock())
+ results = run_parallel_searches(
+ ["a", "b", "c"], lambda q: q, context_factory=factory
+ )
+ assert factory.call_count == 3
+ assert sorted(results) == [("a", "a"), ("b", "b"), ("c", "c")]
+
+
+def test_fresh_context_per_worker_survives_concurrency():
+ """Regression for the shared-AppContext crash.
+
+ Each worker must receive its OWN Flask app context. We force every
+ worker to sit inside its pushed context simultaneously (via a barrier);
+ with a per-call factory this completes cleanly. The previous design
+ shared one AppContext across all workers, which raised
+ ``ValueError: <Token ...> was created in a different Context`` once two
+ workers entered/left it concurrently.
+ """
+ app = Flask(__name__)
+ queries = ["a", "b", "c", "d"]
+ barrier = threading.Barrier(len(queries), timeout=10)
+
+ def search_fn(q):
+ # Block until ALL workers are inside their context at once, forcing
+ # the concurrent push/pop that crashed the shared-context design.
+ barrier.wait()
+ return q
+
+ results = run_parallel_searches(
+ queries, search_fn, context_factory=app.app_context
+ )
+ assert sorted(results) == [("a", "a"), ("b", "b"), ("c", "c"), ("d", "d")]