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(followup): cleanup orphan ResearchHistory on spawn failure (#3503)

LearningCircuita241ae41e5a0
diff --git a/src/local_deep_research/followup_research/routes.py b/src/local_deep_research/followup_research/routes.py
index 0e256d8a82..739ee3fc1d 100644
--- a/src/local_deep_research/followup_research/routes.py
+++ b/src/local_deep_research/followup_research/routes.py
@@ -282,29 +282,63 @@ def start_followup():
"llm.openai_endpoint.url", {}
).get("value")
- start_research_process(
- research_id,
- research_params["query"],
- "quick", # Use 'quick' for quick summary mode
- run_research_process,
- username=username,
- user_password=user_password, # Pass password for metrics database access
- model_provider=model_provider, # Pass model provider
- model=model, # Pass model name
- search_engine=search_engine, # Pass search engine
- custom_endpoint=custom_endpoint, # Pass custom endpoint if any
- strategy="enhanced-contextual-followup", # Use enhanced contextual follow-up strategy
- iterations=research_params["max_iterations"],
- questions_per_iteration=research_params["questions_per_iteration"],
- delegate_strategy=research_params.get(
- "delegate_strategy", "source-based"
- ),
- research_context=research_params["research_context"],
- parent_research_id=research_params[
- "parent_research_id"
- ], # Pass parent research ID
- settings_snapshot=settings_snapshot,
- )
+ # Spawn the research thread. If the spawn fails, the
+ # ResearchHistory row committed above would otherwise be
+ # permanently orphaned with status=IN_PROGRESS. Catch any
+ # exception, flip the status to FAILED, and return a clear
+ # error — same contract as the queue processor's terminal-
+ # failure branch (#3481) and the direct-UI spawn-failure path.
+ try:
+ start_research_process(
+ research_id,
+ research_params["query"],
+ "quick", # Use 'quick' for quick summary mode
+ run_research_process,
+ username=username,
+ user_password=user_password, # gitleaks:allow
+ model_provider=model_provider, # Pass model provider
+ model=model, # Pass model name
+ search_engine=search_engine, # Pass search engine
+ custom_endpoint=custom_endpoint, # Pass custom endpoint if any
+ strategy="enhanced-contextual-followup", # Use enhanced contextual follow-up strategy
+ iterations=research_params["max_iterations"],
+ questions_per_iteration=research_params[
+ "questions_per_iteration"
+ ],
+ delegate_strategy=research_params.get(
+ "delegate_strategy", "source-based"
+ ),
+ research_context=research_params["research_context"],
+ parent_research_id=research_params[
+ "parent_research_id"
+ ], # Pass parent research ID
+ settings_snapshot=settings_snapshot,
+ )
+ except Exception:
+ logger.exception(
+ f"Failed to spawn follow-up research thread for {research_id}"
+ )
+ try:
+ from ..database.session_context import get_user_db_session
+ from ..database.models import ResearchHistory
+
+ with get_user_db_session(username) as cleanup_session:
+ 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 follow-up spawn failure raised")
+ return jsonify(
+ {
+ "success": False,
+ "error": "Failed to start follow-up research. Please try again.",
+ }
+ ), 500
return jsonify(
{
diff --git a/tests/followup_research/test_routes_coverage.py b/tests/followup_research/test_routes_coverage.py
index c935ac9da4..b4b4b18cc7 100644
--- a/tests/followup_research/test_routes_coverage.py
+++ b/tests/followup_research/test_routes_coverage.py
@@ -270,6 +270,66 @@ class TestPrepareFollowupException:
# ---------------------------------------------------------------------------
+class TestStartFollowupSpawnFailure:
+ """If start_research_process raises, flip ResearchHistory.status to FAILED
+ and return 500 — don't leave the row orphaned as IN_PROGRESS."""
+
+ def test_spawn_failure_marks_research_failed(self, app):
+ from local_deep_research.constants import ResearchStatus
+
+ mock_service = Mock()
+ mock_service.perform_followup.return_value = {
+ "query": "follow-up question",
+ "max_iterations": 2,
+ "questions_per_iteration": 4,
+ "delegate_strategy": "source-based",
+ "research_context": {"summary": "context"},
+ "parent_research_id": "parent-1",
+ }
+
+ research_row = Mock()
+ mock_db = MagicMock()
+ mock_db.query.return_value.filter_by.return_value.first.return_value = (
+ research_row
+ )
+
+ @contextmanager
+ def fake_get_user_db_session(username):
+ yield mock_db
+
+ with (
+ patch(AUTH_DB_MANAGER, _mock_auth()),
+ patch(SETTINGS_MANAGER, return_value=_make_settings_mock()),
+ patch(DB_SESSION_CTX, side_effect=fake_get_user_db_session),
+ patch(
+ f"{MODULE}.FollowUpResearchService", return_value=mock_service
+ ),
+ patch(START_RESEARCH, side_effect=RuntimeError("spawn failed")),
+ patch(RUN_RESEARCH),
+ patch(RESEARCH_HISTORY),
+ patch(
+ "uuid.uuid4",
+ return_value=Mock(__str__=lambda s: "failing-research-id"),
+ ),
+ patch(SESSION_PWD_STORE) as mock_pwd_store,
+ ):
+ mock_pwd_store.retrieve.return_value = "secret-password"
+ resp = _authed_post(
+ app,
+ "/api/followup/start",
+ {"parent_research_id": "parent-1", "question": "details?"},
+ extra_session={"session_id": "sess-123"},
+ )
+
+ assert resp.status_code == 500
+ data = resp.get_json()
+ assert data["success"] is False
+ # ResearchHistory row was flipped to FAILED by the cleanup handler.
+ assert research_row.status == ResearchStatus.FAILED
+ # Cleanup commit was issued.
+ mock_db.commit.assert_called()
+
+
class TestStartFollowupSuccess:
"""start_followup succeeds and retrieves password from session_password_store."""