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(research): dedup guard in start_research_process (#3499)

LearningCircuit4f77d784cf55
diff --git a/src/local_deep_research/exceptions.py b/src/local_deep_research/exceptions.py
index a64dffaba5..b5feb7ec5b 100644
--- a/src/local_deep_research/exceptions.py
+++ b/src/local_deep_research/exceptions.py
@@ -11,3 +11,15 @@ class ResearchTerminatedException(BaseException):
"""
pass
+
+
+class DuplicateResearchError(Exception):
+ """Raised when ``start_research_process`` is called with a research_id
+ that already has a live thread registered.
+
+ Inherits from Exception so existing ``except Exception`` wrappers around
+ spawn calls catch it naturally and route it through the standard
+ spawn-failure error path.
+ """
+
+ pass
diff --git a/src/local_deep_research/web/routes/globals.py b/src/local_deep_research/web/routes/globals.py
index d752601fe3..e0c663db47 100644
--- a/src/local_deep_research/web/routes/globals.py
+++ b/src/local_deep_research/web/routes/globals.py
@@ -88,6 +88,32 @@ def set_active_research(research_id, data):
_active_research[research_id] = data
+def check_and_start_research(research_id, data) -> bool:
+ """Atomically register a research entry iff no live thread exists.
+
+ If ``_active_research[research_id]`` already holds an entry whose
+ ``thread`` is alive, returns ``False`` without mutating state and
+ without calling ``.start()``. Otherwise, starts ``data['thread']``
+ and writes *data* into the active-research dict, then returns ``True``.
+
+ The entire check-and-start is done under the single shared lock, so
+ two concurrent callers with the same *research_id* cannot both pass
+ the liveness check and end up with two live threads for the same ID.
+ """
+ thread = data.get("thread") if isinstance(data, dict) else None
+ if thread is None:
+ raise ValueError("data must contain a 'thread' entry")
+ with _lock:
+ entry = _active_research.get(research_id)
+ if entry is not None:
+ existing = entry.get("thread")
+ if existing is not None and existing.is_alive():
+ return False
+ thread.start()
+ _active_research[research_id] = data
+ return True
+
+
def update_active_research(research_id, **fields):
"""Update one or more fields on an existing entry.
diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.py
index 2d8271abd4..af088ab24e 100644
--- a/src/local_deep_research/web/services/research_service.py
+++ b/src/local_deep_research/web/services/research_service.py
@@ -7,7 +7,7 @@ from pathlib import Path
from loguru import logger
-from ...exceptions import ResearchTerminatedException
+from ...exceptions import DuplicateResearchError, ResearchTerminatedException
from ...config.llm_config import get_llm
from ...settings.manager import SnapshotSettingsContext
@@ -218,7 +218,7 @@ def start_research_process(
Returns:
threading.Thread: The thread running the research
"""
- from ..routes.globals import set_active_research
+ from ..routes.globals import check_and_start_research
# Pass the app context to the thread.
run_research_callback = thread_with_app_context(run_research_callback)
@@ -233,7 +233,7 @@ def start_research_process(
finally:
_global_research_semaphore.release()
- # Start research process in a background thread
+ # Prepare (but do not start) the background thread.
thread = threading.Thread(
target=_rate_limited_callback,
args=(
@@ -245,18 +245,25 @@ def start_research_process(
kwargs=kwargs,
)
thread.daemon = True
- thread.start()
- set_active_research(
+ # Atomic check-and-start: refuses to spawn a second live thread
+ # for the same research_id. Guards against the double-spawn window
+ # where a post-spawn commit failure in the queue processor could
+ # otherwise cause the retry loop to dispatch the same research twice.
+ started = check_and_start_research(
research_id,
{
"thread": thread,
"progress": 0,
"status": ResearchStatus.IN_PROGRESS,
"log": [],
- "settings": kwargs, # Store settings for reference
+ "settings": kwargs,
},
)
+ if not started:
+ raise DuplicateResearchError(
+ f"Research {research_id} already has a live thread"
+ )
return thread
diff --git a/tests/web/routes/test_globals_gaps.py b/tests/web/routes/test_globals_gaps.py
index f43f793651..bc9d60480f 100644
--- a/tests/web/routes/test_globals_gaps.py
+++ b/tests/web/routes/test_globals_gaps.py
@@ -123,3 +123,70 @@ class TestUpdateProgressAndCheckActive:
result = g.update_progress_and_check_active("r1", 10)
assert result == (10, True)
assert g.get_research_field("r1", "progress") == 10
+
+
+# ===================================================================
+# check_and_start_research
+# ===================================================================
+
+
+class TestCheckAndStartResearch:
+ def _make_data(self, alive=True):
+ thread = Mock()
+ thread.is_alive.return_value = alive
+ return thread, {
+ "thread": thread,
+ "progress": 0,
+ "status": "in_progress",
+ "log": [],
+ "settings": {},
+ }
+
+ def test_registers_when_no_prior_entry(self):
+ thread, data = self._make_data()
+ result = g.check_and_start_research("r1", data)
+ assert result is True
+ thread.start.assert_called_once()
+ assert g.is_research_thread_alive("r1")
+
+ def test_refuses_when_existing_thread_alive(self):
+ existing_thread = Mock()
+ existing_thread.is_alive.return_value = True
+ g.set_active_research("r1", {"thread": existing_thread})
+
+ new_thread, new_data = self._make_data()
+ result = g.check_and_start_research("r1", new_data)
+
+ assert result is False
+ new_thread.start.assert_not_called()
+ # Existing entry is untouched.
+ assert g.get_research_field("r1", "thread") is existing_thread
+
+ def test_overwrites_when_existing_thread_finished(self):
+ finished_thread = Mock()
+ finished_thread.is_alive.return_value = False
+ g.set_active_research("r1", {"thread": finished_thread})
+
+ new_thread, new_data = self._make_data()
+ result = g.check_and_start_research("r1", new_data)
+
+ assert result is True
+ new_thread.start.assert_called_once()
+ assert g.get_research_field("r1", "thread") is new_thread
+
+ def test_overwrites_when_existing_has_no_thread(self):
+ g.set_active_research("r1", {"progress": 50})
+
+ new_thread, new_data = self._make_data()
+ result = g.check_and_start_research("r1", new_data)
+
+ assert result is True
+ new_thread.start.assert_called_once()
+
+ def test_rejects_data_without_thread(self):
+ with pytest.raises(ValueError):
+ g.check_and_start_research("r1", {"progress": 0})
+
+ def test_rejects_data_with_thread_none(self):
+ with pytest.raises(ValueError):
+ g.check_and_start_research("r1", {"thread": None})
diff --git a/tests/web/services/test_research_service.py b/tests/web/services/test_research_service.py
index eb7bbd6672..8b697b196e 100644
--- a/tests/web/services/test_research_service.py
+++ b/tests/web/services/test_research_service.py
@@ -288,11 +288,11 @@ class TestStartResearchProcess:
"local_deep_research.web.services.research_service.thread_with_app_context"
)
@patch("local_deep_research.web.services.research_service.thread_context")
- @patch("local_deep_research.web.routes.globals.set_active_research")
+ @patch("local_deep_research.web.routes.globals.check_and_start_research")
def test_start_research_process_creates_thread(
- self, mock_set_active, mock_thread_context, mock_thread_with_context
+ self, mock_check_start, mock_thread_context, mock_thread_with_context
):
- """start_research_process creates and starts a thread."""
+ """start_research_process creates a thread and atomically registers it."""
from local_deep_research.web.services.research_service import (
start_research_process,
)
@@ -300,8 +300,8 @@ class TestStartResearchProcess:
mock_callback = Mock()
mock_thread_with_context.return_value = mock_callback
mock_thread_context.return_value = {}
+ mock_check_start.return_value = True # dedup passes
- # Mock threading.Thread to not actually start
with patch(
"local_deep_research.web.services.research_service.threading.Thread"
) as mock_thread_class:
@@ -315,19 +315,21 @@ class TestStartResearchProcess:
run_research_callback=mock_callback,
)
- mock_thread.start.assert_called_once()
- mock_set_active.assert_called_once()
- call_args = mock_set_active.call_args
+ # The dedup helper owns starting the thread — not the caller.
+ mock_thread.start.assert_not_called()
+ mock_check_start.assert_called_once()
+ call_args = mock_check_start.call_args
assert call_args[0][0] == 123
assert call_args[0][1]["status"] == "in_progress"
+ assert call_args[0][1]["thread"] is mock_thread
@patch(
"local_deep_research.web.services.research_service.thread_with_app_context"
)
@patch("local_deep_research.web.services.research_service.thread_context")
- @patch("local_deep_research.web.routes.globals.set_active_research")
+ @patch("local_deep_research.web.routes.globals.check_and_start_research")
def test_start_research_process_stores_settings(
- self, mock_set_active, mock_thread_context, mock_thread_with_context
+ self, mock_check_start, mock_thread_context, mock_thread_with_context
):
"""start_research_process stores settings in active_research."""
from local_deep_research.web.services.research_service import (
@@ -337,6 +339,7 @@ class TestStartResearchProcess:
mock_callback = Mock()
mock_thread_with_context.return_value = mock_callback
mock_thread_context.return_value = {}
+ mock_check_start.return_value = True
with patch(
"local_deep_research.web.services.research_service.threading.Thread"
@@ -353,11 +356,50 @@ class TestStartResearchProcess:
search_engine="google",
)
- call_args = mock_set_active.call_args
+ call_args = mock_check_start.call_args
settings = call_args[0][1]["settings"]
assert settings["model"] == "gpt-4"
assert settings["search_engine"] == "google"
+ @patch(
+ "local_deep_research.web.services.research_service.thread_with_app_context"
+ )
+ @patch("local_deep_research.web.services.research_service.thread_context")
+ @patch("local_deep_research.web.routes.globals.check_and_start_research")
+ def test_start_research_process_raises_on_duplicate(
+ self, mock_check_start, mock_thread_context, mock_thread_with_context
+ ):
+ """If a live thread already exists for research_id, raises
+ DuplicateResearchError without spawning a second thread."""
+ import pytest
+ from local_deep_research.exceptions import DuplicateResearchError
+ from local_deep_research.web.services.research_service import (
+ start_research_process,
+ )
+
+ mock_callback = Mock()
+ mock_thread_with_context.return_value = mock_callback
+ mock_thread_context.return_value = {}
+ mock_check_start.return_value = False # dedup refuses
+
+ with patch(
+ "local_deep_research.web.services.research_service.threading.Thread"
+ ) as mock_thread_class:
+ mock_thread = Mock()
+ mock_thread_class.return_value = mock_thread
+
+ with pytest.raises(DuplicateResearchError):
+ start_research_process(
+ research_id=123,
+ query="test query",
+ mode="quick",
+ run_research_callback=mock_callback,
+ )
+
+ # Thread prepared but never started — check_and_start_research
+ # owns the .start() call and refused to make it.
+ mock_thread.start.assert_not_called()
+
class TestCleanupResearchResources:
"""Tests for cleanup_research_resources function."""
@@ -616,9 +658,9 @@ class TestStartResearchProcessWithOptions:
"local_deep_research.web.services.research_service.thread_with_app_context"
)
@patch("local_deep_research.web.services.research_service.thread_context")
- @patch("local_deep_research.web.routes.globals.set_active_research")
+ @patch("local_deep_research.web.routes.globals.check_and_start_research")
def test_start_research_with_local_collections(
- self, mock_set_active, mock_thread_context, mock_thread_with_context
+ self, mock_check_start, mock_thread_context, mock_thread_with_context
):
"""start_research_process handles local_collections option."""
from local_deep_research.web.services.research_service import (
@@ -628,6 +670,7 @@ class TestStartResearchProcessWithOptions:
mock_callback = Mock()
mock_thread_with_context.return_value = mock_callback
mock_thread_context.return_value = {}
+ mock_check_start.return_value = True
with patch(
"local_deep_research.web.services.research_service.threading.Thread"
@@ -643,7 +686,7 @@ class TestStartResearchProcessWithOptions:
local_collections=["collection1", "collection2"],
)
- call_args = mock_set_active.call_args
+ call_args = mock_check_start.call_args
settings = call_args[0][1]["settings"]
assert settings["local_collections"] == [
"collection1",
@@ -654,9 +697,9 @@ class TestStartResearchProcessWithOptions:
"local_deep_research.web.services.research_service.thread_with_app_context"
)
@patch("local_deep_research.web.services.research_service.thread_context")
- @patch("local_deep_research.web.routes.globals.set_active_research")
+ @patch("local_deep_research.web.routes.globals.check_and_start_research")
def test_start_research_stores_knowledge_graph_option(
- self, mock_set_active, mock_thread_context, mock_thread_with_context
+ self, mock_check_start, mock_thread_context, mock_thread_with_context
):
"""start_research_process stores knowledge_graph option."""
from local_deep_research.web.services.research_service import (
@@ -666,6 +709,7 @@ class TestStartResearchProcessWithOptions:
mock_callback = Mock()
mock_thread_with_context.return_value = mock_callback
mock_thread_context.return_value = {}
+ mock_check_start.return_value = True
with patch(
"local_deep_research.web.services.research_service.threading.Thread"
@@ -681,7 +725,7 @@ class TestStartResearchProcessWithOptions:
enable_knowledge_graph=True,
)
- call_args = mock_set_active.call_args
+ call_args = mock_check_start.call_args
settings = call_args[0][1]["settings"]
assert settings["enable_knowledge_graph"] is True
diff --git a/tests/web/services/test_research_service_coverage.py b/tests/web/services/test_research_service_coverage.py
index 06a1b28682..85503d48ef 100644
--- a/tests/web/services/test_research_service_coverage.py
+++ b/tests/web/services/test_research_service_coverage.py
@@ -294,8 +294,9 @@ class TestStartResearchProcess:
self, mock_sem, mock_app_ctx, mock_tctx
):
with patch(
- "local_deep_research.web.routes.globals.set_active_research"
- ) as mock_set:
+ "local_deep_research.web.routes.globals.check_and_start_research",
+ return_value=True,
+ ) as mock_check_start:
from local_deep_research.web.services.research_service import (
start_research_process,
)
@@ -309,8 +310,8 @@ class TestStartResearchProcess:
)
assert isinstance(thread, threading.Thread)
assert thread.daemon is True
- mock_set.assert_called_once()
- args = mock_set.call_args
+ mock_check_start.assert_called_once()
+ args = mock_check_start.call_args
assert args[0][0] == "r1"
info = args[0][1]
assert info["progress"] == 0
diff --git a/tests/web/services/test_research_service_deep_coverage.py b/tests/web/services/test_research_service_deep_coverage.py
index 8e1a6debda..d578fc8a2d 100644
--- a/tests/web/services/test_research_service_deep_coverage.py
+++ b/tests/web/services/test_research_service_deep_coverage.py
@@ -412,6 +412,11 @@ class TestStartResearchProcessDeep:
mock_thread = MagicMock()
mock_thread_cls = MagicMock(return_value=mock_thread)
+ # Dedup stub: starts the thread and returns True.
+ def fake_check_and_start(rid, data):
+ data["thread"].start()
+ return True
+
with patch(
f"{MODULE}.thread_with_app_context", side_effect=lambda f: f
):
@@ -420,8 +425,10 @@ class TestStartResearchProcessDeep:
with patch(
f"{MODULE}._global_research_semaphore", real_sem
):
- # set_active_research is lazily imported from globals
- with patch(f"{GLOBALS_MOD}.set_active_research"):
+ with patch(
+ f"{GLOBALS_MOD}.check_and_start_research",
+ side_effect=fake_check_and_start,
+ ):
start_research_process(
research_id=1,
query="test",
@@ -429,19 +436,20 @@ class TestStartResearchProcessDeep:
run_research_callback=fake_callback,
)
- # Thread was started
+ # Thread was started (by the dedup helper stub)
mock_thread.start.assert_called_once()
- def test_set_active_research_called_with_correct_keys(self):
+ def test_check_and_start_research_called_with_correct_keys(self):
from local_deep_research.web.services.research_service import (
start_research_process,
)
from local_deep_research.constants import ResearchStatus
- set_active_calls = []
+ captured = []
- def capture_set(rid, data):
- set_active_calls.append((rid, data))
+ def capture(rid, data):
+ captured.append((rid, data))
+ return True
with patch(
f"{MODULE}.thread_with_app_context", side_effect=lambda f: f
@@ -449,10 +457,9 @@ class TestStartResearchProcessDeep:
with patch(f"{MODULE}.threading.Thread") as mock_thread_cls:
mock_thread_cls.return_value.start = MagicMock()
with patch(f"{MODULE}.thread_context", return_value={}):
- # set_active_research is lazily imported inside start_research_process
with patch(
- f"{GLOBALS_MOD}.set_active_research",
- side_effect=capture_set,
+ f"{GLOBALS_MOD}.check_and_start_research",
+ side_effect=capture,
):
start_research_process(
research_id=123,
@@ -461,8 +468,8 @@ class TestStartResearchProcessDeep:
run_research_callback=MagicMock(),
)
- assert len(set_active_calls) == 1
- rid, data = set_active_calls[0]
+ assert len(captured) == 1
+ rid, data = captured[0]
assert rid == 123
assert data["status"] == ResearchStatus.IN_PROGRESS
assert data["progress"] == 0
diff --git a/tests/web/services/test_research_service_extra_coverage.py b/tests/web/services/test_research_service_extra_coverage.py
index 88e09846a4..66b9afd2c1 100644
--- a/tests/web/services/test_research_service_extra_coverage.py
+++ b/tests/web/services/test_research_service_extra_coverage.py
@@ -592,13 +592,20 @@ class TestStartResearchProcess:
callback = MagicMock()
+ def fake_check_and_start(rid, data):
+ data["thread"].start()
+ return True
+
with (
patch(
f"{MODULE}.thread_with_app_context",
side_effect=lambda f: f,
),
patch(f"{MODULE}.thread_context", return_value={}),
- patch("local_deep_research.web.routes.globals.set_active_research"),
+ patch(
+ "local_deep_research.web.routes.globals.check_and_start_research",
+ side_effect=fake_check_and_start,
+ ),
patch("threading.Thread") as mock_thread_cls,
):
mock_thread = MagicMock()