~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
fix(queue): handle DuplicateResearchError on direct-mode spawn paths (#3522)
LearningCircuit1487f5c4330f
diff --git a/src/local_deep_research/exceptions.py b/src/local_deep_research/exceptions.pyindex b5feb7ec5b..d3941d2f2a 100644--- a/src/local_deep_research/exceptions.py+++ b/src/local_deep_research/exceptions.py@@ -17,9 +17,12 @@ class DuplicateResearchError(Exception):"""Raised when ``start_research_process`` is called with a research_idthat 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.+ Callers that wrap the spawn in ``except Exception`` to clean up orphan+ state on spawn failure MUST catch ``DuplicateResearchError`` separately+ *before* that generic branch and re-raise / return without mutating the+ research's status or deleting the ``UserActiveResearch`` row — those+ rows belong to the live thread, and marking them FAILED terminates a+ running thread from the user's perspective while it keeps executing."""passdiff --git a/src/local_deep_research/web/queue/processor_v2.py b/src/local_deep_research/web/queue/processor_v2.pyindex d3da0312d3..e6db9546e1 100644--- a/src/local_deep_research/web/queue/processor_v2.py+++ b/src/local_deep_research/web/queue/processor_v2.py@@ -343,6 +343,18 @@ class QueueProcessorV2:f"in thread {research_thread.ident}")+ except DuplicateResearchError:+ # A live thread already owns this research_id. Do NOT delete+ # the UserActiveResearch row or mark ResearchHistory FAILED —+ # that state belongs to the live thread, and mutating it+ # would terminate a running research from the user's+ # perspective while it keeps executing. Same contract as the+ # queue processor's dedicated dup branch (#3506).+ logger.warning(+ f"Duplicate live thread detected for {research_id} "+ "in direct mode; leaving state intact"+ )+ returnexcept Exception:logger.exception(f"Failed to start research {research_id} directly")# Clean up the active record AND mark the research terminaldiff --git a/src/local_deep_research/web/routes/research_routes.py b/src/local_deep_research/web/routes/research_routes.pyindex 766eddd697..90325ac7d6 100644--- a/src/local_deep_research/web/routes/research_routes.py+++ b/src/local_deep_research/web/routes/research_routes.py@@ -18,6 +18,7 @@ from sqlalchemy import func# Security importsfrom ...config.constants import DEFAULT_OLLAMA_URL+from ...exceptions import DuplicateResearchErrorfrom ...llm.providers.base import normalize_providerfrom ...constants import ResearchStatusfrom ...security import (@@ -723,6 +724,23 @@ def start_research():strategy=strategy,settings_snapshot=snapshot_data, # Pass complete settings)+ except DuplicateResearchError:+ # A live thread already owns this research_id. Do NOT delete+ # the UserActiveResearch row or mark ResearchHistory FAILED —+ # that state belongs to the live thread, and mutating it+ # would terminate a running research from the user's+ # perspective while it keeps executing. Same contract as the+ # queue processor's dedicated dup branch (#3506).+ logger.warning(+ f"Duplicate live thread detected for {research_id} "+ "on direct submission; leaving state intact"+ )+ return jsonify(+ {+ "status": "error",+ "message": "Research is already running.",+ }+ ), 409except Exception:logger.exception(f"Failed to spawn research thread for {research_id}"diff --git a/tests/web/queue/test_processor_v2_coverage.py b/tests/web/queue/test_processor_v2_coverage.pyindex 3a81156144..d8022b7009 100644--- a/tests/web/queue/test_processor_v2_coverage.py+++ b/tests/web/queue/test_processor_v2_coverage.py@@ -168,6 +168,65 @@ class TestStartResearchDirectlyErrors:# Should complete without raising even though thread-id update failedproc._start_research_directly("alice", "r1", "secret", query="q")+ def test_duplicate_research_error_leaves_state_intact(self):+ """When start_research_process raises DuplicateResearchError, the+ active record must NOT be deleted and the ResearchHistory row must+ NOT be marked FAILED — that state belongs to the live thread that+ already owns this research_id. Mutating it would terminate a+ running thread from the user's perspective."""+ from local_deep_research.database.models import (+ ResearchHistory,+ UserActiveResearch,+ )+ from local_deep_research.exceptions import DuplicateResearchError++ proc = _make_processor()++ active_record = MagicMock()+ research_row = MagicMock()+ initial_status = MagicMock()+ research_row.status = initial_status++ mock_session = MagicMock()++ def _query(model):+ q = MagicMock()+ q.filter_by.return_value = q+ q.filter.return_value = q+ if model is UserActiveResearch:+ q.first.return_value = active_record+ elif model is ResearchHistory:+ q.first.return_value = research_row+ else:+ q.first.return_value = None+ return q++ mock_session.query.side_effect = _query++ def ctx_side_effect(*args, **kwargs):+ cm = MagicMock()+ cm.__enter__ = MagicMock(return_value=mock_session)+ cm.__exit__ = MagicMock(return_value=False)+ return cm++ with (+ patch(f"{MODULE}.get_user_db_session", side_effect=ctx_side_effect),+ patch(+ f"{MODULE}.start_research_process",+ side_effect=DuplicateResearchError(+ "research r1 already has a live thread"+ ),+ ),+ patch(f"{MODULE}.UserQueueService"),+ patch(f"{MODULE}.logger"),+ ):+ proc._start_research_directly("alice", "r1", "secret", query="q")++ # Critical invariants: no delete of active record, no status+ # mutation on ResearchHistory. The live thread owns that state.+ mock_session.delete.assert_not_called()+ assert research_row.status is initial_status+def test_start_research_process_exception_cleans_up_active_record(self):"""When start_research_process raises the active record should bedeleted AND the ResearchHistory row marked FAILED."""diff --git a/tests/web/queue/test_processor_v2_real.py b/tests/web/queue/test_processor_v2_real.pyindex 3d15bd43a4..a9fcc91252 100644--- a/tests/web/queue/test_processor_v2_real.py+++ b/tests/web/queue/test_processor_v2_real.py@@ -885,6 +885,14 @@ class TestStartResearch:# that distinguishes this branch from the generic spawn-failure# branch (which DOES reset to QUEUED).assert mock_research.status == ResearchStatus.IN_PROGRESS+ # Regression guard: _start_research itself must not touch the+ # spawn-retry counter on the UAR-commit-failure path. The+ # counter is the caller's responsibility (the dup branch in+ # _start_queued_researches clears it); if anyone moves bump+ # logic into _start_research, this assertion catches it and+ # prevents a live thread from being marked terminal FAILED at+ # SPAWN_RETRY_LIMIT.+ assert "r-uar-fail" not in processor._spawn_retry_counts# ---------------------------------------------------------------------------diff --git a/tests/web/routes/test_research_routes_start_research_coverage.py b/tests/web/routes/test_research_routes_start_research_coverage.pyindex 4f61c5bf2e..aa92415c1b 100644--- a/tests/web/routes/test_research_routes_start_research_coverage.py+++ b/tests/web/routes/test_research_routes_start_research_coverage.py@@ -638,6 +638,68 @@ class TestStartResearchThreadSpawn:assert research_row.status == ResearchStatus.FAILEDcleanup_session.commit.assert_called()+ def test_start_research_duplicate_error_leaves_state_intact(+ self, client, app+ ):+ """If start_research_process raises DuplicateResearchError a live+ thread already owns this research_id. The route must return 409+ without deleting the UserActiveResearch row or marking+ ResearchHistory FAILED — that state belongs to the live thread."""+ from local_deep_research.exceptions import DuplicateResearchError++ ms = _mock_db_session()+ _configure_ms_for_active(ms, active_count=0)+ sm = _make_settings_manager(model="llama3")++ cleanup_session = MagicMock()++ def cleanup_ctx(*args, **kwargs):+ return _ctx(cleanup_session)++ @app.before_request+ def _inject_g():+ g.db_session = ms++ with (+ patch(_GET_USER_DB, side_effect=cleanup_ctx),+ patch(_SM_MANAGER, return_value=sm),+ patch(_SM_SETTINGS, return_value=sm),+ patch(+ f"{MODULE}.start_research_process",+ side_effect=DuplicateResearchError(+ "research already has a live thread"+ ),+ ),+ patch(_SAVE_STRATEGY),+ patch(f"{MODULE}.log_settings"),+ patch(_SESSION_PW_STORE) as mock_sps,+ patch(f"{MODULE}.ResearchHistory"),+ patch(f"{MODULE}.UserActiveResearch"),+ ):+ mock_sps.get_session_password.return_value = "pw"++ resp = client.post(+ "/api/start_research",+ json={+ "query": "Duplicate live thread test",+ "model": "llama3",+ "mode": "deep",+ },+ content_type="application/json",+ )++ # 409 Conflict — not 500, and no cleanup session opened for+ # the spawn-failure cleanup branch.+ assert resp.status_code == 409+ data = resp.get_json()+ assert data["status"] == "error"+ # Critical invariants: no delete call on any session, and the+ # cleanup session in particular must never be touched — if the+ # spawn-failure branch had run, it would have called+ # cleanup_session.delete + cleanup_session.commit.+ cleanup_session.delete.assert_not_called()+ cleanup_session.commit.assert_not_called()+def test_start_research_thread_spawn_success(self, client, app):ms = _mock_db_session()_configure_ms_for_active(ms, active_count=0)