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-routes): cleanup orphan state on spawn failure (#3500)

LearningCircuitf0e6133553a1
diff --git a/src/local_deep_research/web/routes/research_routes.py b/src/local_deep_research/web/routes/research_routes.py
index 6942b53e25..766eddd697 100644
--- a/src/local_deep_research/web/routes/research_routes.py
+++ b/src/local_deep_research/web/routes/research_routes.py
@@ -697,27 +697,66 @@ def start_research():
else:
logger.debug("search.tool NOT in snapshot")
- # Start the research process with the selected parameters
- research_thread = start_research_process(
- research_id,
- query,
- mode,
- run_research_process,
- username=username, # Pass username to the thread
- user_password=user_password, # Pass password for database access
- model_provider=model_provider,
- model=model,
- custom_endpoint=custom_endpoint,
- search_engine=search_engine,
- max_results=max_results,
- time_period=time_period,
- iterations=iterations,
- questions_per_iteration=questions_per_iteration,
- strategy=strategy,
- settings_snapshot=snapshot_data, # Pass complete settings
- )
+ # Start the research process with the selected parameters.
+ # If the spawn raises, the UserActiveResearch + IN_PROGRESS
+ # ResearchHistory rows persisted above would otherwise be
+ # permanently orphaned (no thread, no cleanup path). Catch any
+ # exception, mark the research FAILED, delete the active row,
+ # and return 500 — same contract as the queue processor's
+ # terminal-failure branch introduced in #3481.
+ try:
+ research_thread = start_research_process(
+ research_id,
+ query,
+ mode,
+ run_research_process,
+ username=username, # Pass username to the thread
+ user_password=user_password, # Pass password for database access
+ model_provider=model_provider,
+ model=model,
+ custom_endpoint=custom_endpoint,
+ search_engine=search_engine,
+ max_results=max_results,
+ time_period=time_period,
+ iterations=iterations,
+ questions_per_iteration=questions_per_iteration,
+ strategy=strategy,
+ settings_snapshot=snapshot_data, # Pass complete settings
+ )
+ except Exception:
+ logger.exception(
+ f"Failed to spawn research thread for {research_id}"
+ )
+ try:
+ with get_user_db_session(username) as cleanup_session:
+ stale_active = (
+ cleanup_session.query(UserActiveResearch)
+ .filter_by(username=username, research_id=research_id)
+ .first()
+ )
+ if stale_active:
+ cleanup_session.delete(stale_active)
+ research_row = (
+ cleanup_session.query(ResearchHistory)
+ .filter_by(id=research_id)
+ .first()
+ )
+ if research_row:
+ research_row.status = ResearchStatus.FAILED
+ cleanup_session.commit()
+ except Exception:
+ logger.exception(
+ "Cleanup after spawn failure raised; leaving "
+ "orphan rows for the reconciler to handle"
+ )
+ return jsonify(
+ {
+ "status": "error",
+ "message": "Failed to start research. Please try again.",
+ }
+ ), 500
- # Update the active research record with the actual thread ID
+ # Update the active research record with the actual thread ID.
try:
with get_user_db_session(username) as thread_session:
active_record = (
diff --git a/tests/web/routes/test_research_routes_start_research_coverage.py b/tests/web/routes/test_research_routes_start_research_coverage.py
index 720798d61b..4f61c5bf2e 100644
--- a/tests/web/routes/test_research_routes_start_research_coverage.py
+++ b/tests/web/routes/test_research_routes_start_research_coverage.py
@@ -558,7 +558,85 @@ class TestStartResearchPasswordFromTempAuth:
class TestStartResearchThreadSpawn:
- """Full happy path: start_research_process is called and returns 200."""
+ """Spawn path: success returns 200; failure cleans up and returns 500."""
+
+ def test_start_research_thread_spawn_failure_cleans_up(self, client, app):
+ """If start_research_process raises, the orphan UserActiveResearch row
+ must be deleted and ResearchHistory.status set to FAILED before we
+ respond with 500 — matches the queue processor's terminal-failure
+ contract added in #3481."""
+ ms = _mock_db_session()
+ _configure_ms_for_active(ms, active_count=0)
+ sm = _make_settings_manager(model="llama3")
+
+ stale_active = MagicMock()
+ research_row = MagicMock()
+ cleanup_session = MagicMock()
+
+ def cleanup_query_factory(model):
+ q = MagicMock()
+ q.filter_by.return_value = q
+
+ class _UAR:
+ pass
+
+ class _RH:
+ pass
+
+ if getattr(model, "__name__", "") == "UserActiveResearch":
+ q.first.return_value = stale_active
+ elif getattr(model, "__name__", "") == "ResearchHistory":
+ q.first.return_value = research_row
+ else:
+ q.first.return_value = MagicMock()
+ return q
+
+ cleanup_session.query.side_effect = cleanup_query_factory
+
+ 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=RuntimeError("boom"),
+ ),
+ patch(_SAVE_STRATEGY),
+ patch(f"{MODULE}.log_settings"),
+ patch(_SESSION_PW_STORE) as mock_sps,
+ patch(f"{MODULE}.ResearchHistory") as mock_rh_cls,
+ patch(f"{MODULE}.UserActiveResearch") as mock_uar_cls,
+ ):
+ mock_sps.get_session_password.return_value = "pw"
+ mock_rh_cls.__name__ = "ResearchHistory"
+ mock_uar_cls.__name__ = "UserActiveResearch"
+
+ resp = client.post(
+ "/api/start_research",
+ json={
+ "query": "Spawn failure test",
+ "model": "llama3",
+ "mode": "deep",
+ },
+ content_type="application/json",
+ )
+
+ assert resp.status_code == 500
+ data = resp.get_json()
+ assert data["status"] == "error"
+ # Orphan UserActiveResearch row deleted, ResearchHistory marked FAILED.
+ cleanup_session.delete.assert_called_with(stale_active)
+ from local_deep_research.constants import ResearchStatus
+
+ assert research_row.status == ResearchStatus.FAILED
+ cleanup_session.commit.assert_called()
def test_start_research_thread_spawn_success(self, client, app):
ms = _mock_db_session()