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(spawn-failure): complete cleanup in direct + benchmark paths (#3501)

LearningCircuit68b0371d7db8
diff --git a/src/local_deep_research/benchmarks/web_api/benchmark_service.py b/src/local_deep_research/benchmarks/web_api/benchmark_service.py
index 1348bd139a..634e19b4dc 100644
--- a/src/local_deep_research/benchmarks/web_api/benchmark_service.py
+++ b/src/local_deep_research/benchmarks/web_api/benchmark_service.py
@@ -365,6 +365,10 @@ class BenchmarkService:
except Exception as e:
logger.exception(f"Error starting benchmark {benchmark_run_id}")
+ # If we populated active_runs before the spawn failed, drop the
+ # stale entry — it has no thread and would mislead subsequent
+ # cancel_benchmark / get_run_status calls.
+ self.active_runs.pop(benchmark_run_id, None)
# Update status using user database
with get_user_db_session(username, user_password) as session:
benchmark_run = (
diff --git a/src/local_deep_research/web/queue/processor_v2.py b/src/local_deep_research/web/queue/processor_v2.py
index 535725c33f..c381886453 100644
--- a/src/local_deep_research/web/queue/processor_v2.py
+++ b/src/local_deep_research/web/queue/processor_v2.py
@@ -329,7 +329,10 @@ class QueueProcessorV2:
except Exception:
logger.exception(f"Failed to start research {research_id} directly")
- # Clean up the active record
+ # Clean up the active record AND mark the research terminal
+ # FAILED so the user-visible state matches reality (no running
+ # thread, not IN_PROGRESS). Same contract as the queue
+ # processor's terminal-failure branch (#3481).
try:
with get_user_db_session(username) as db_session:
active_record = (
@@ -339,7 +342,14 @@ class QueueProcessorV2:
)
if active_record:
db_session.delete(active_record)
- db_session.commit()
+ research_row = (
+ db_session.query(ResearchHistory)
+ .filter_by(id=research_id)
+ .first()
+ )
+ if research_row:
+ research_row.status = ResearchStatus.FAILED
+ db_session.commit()
except Exception:
logger.exception(
f"Failed to clean up active research record for {research_id}"
diff --git a/tests/benchmarks/test_benchmark_service.py b/tests/benchmarks/test_benchmark_service.py
index ad3368ff05..f0c0170c41 100644
--- a/tests/benchmarks/test_benchmark_service.py
+++ b/tests/benchmarks/test_benchmark_service.py
@@ -908,6 +908,59 @@ class TestBenchmarkServiceStartBenchmark:
assert result is False
+ def test_start_benchmark_cleans_up_active_runs_on_spawn_failure(self):
+ """If Thread.start raises after active_runs was populated, the stale
+ entry must be removed so later cancel/status calls don't see a
+ thread-less zombie run."""
+ from local_deep_research.benchmarks.web_api.benchmark_service import (
+ BenchmarkService,
+ )
+ from local_deep_research.database.models import BenchmarkStatus
+
+ mock_socket = Mock()
+ service = BenchmarkService(socket_service=mock_socket)
+
+ with patch(
+ "local_deep_research.database.session_context.get_user_db_session"
+ ) as mock_get_session:
+ mock_session = Mock()
+ mock_session.__enter__ = Mock(return_value=mock_session)
+ mock_session.__exit__ = Mock(return_value=False)
+ mock_get_session.return_value = mock_session
+
+ mock_run = Mock()
+ mock_run.id = 42
+ mock_run.config_hash = "hash42"
+ mock_run.datasets_config = {}
+ mock_run.search_config = {}
+ mock_run.evaluation_config = {}
+ mock_session.query.return_value.filter.return_value.first.return_value = mock_run
+
+ with patch("local_deep_research.settings.SettingsManager") as sm:
+ sm.return_value.get_all_settings.return_value = {}
+ with (
+ patch("flask.session", {"session_id": "sid"}),
+ patch(
+ "local_deep_research.database.session_passwords.session_password_store"
+ ),
+ patch("threading.Thread") as mock_thread_cls,
+ ):
+ mock_thread = Mock()
+ mock_thread.start.side_effect = RuntimeError(
+ "thread spawn failed"
+ )
+ mock_thread_cls.return_value = mock_thread
+
+ result = service.start_benchmark(
+ 42, username="testuser", user_password="pw"
+ )
+
+ assert result is False
+ # active_runs must not retain the zombie entry.
+ assert 42 not in service.active_runs
+ # BenchmarkRun.status was flipped to FAILED by the error handler.
+ assert mock_run.status == BenchmarkStatus.FAILED
+
class TestBenchmarkServiceProcessTask:
"""Tests for _process_benchmark_task functionality."""
diff --git a/tests/web/queue/test_processor_v2_concurrency.py b/tests/web/queue/test_processor_v2_concurrency.py
index a6dbc58cef..c6585f68cf 100644
--- a/tests/web/queue/test_processor_v2_concurrency.py
+++ b/tests/web/queue/test_processor_v2_concurrency.py
@@ -267,17 +267,33 @@ class TestStartResearchDirectlyCleanup:
def test_cleanup_on_start_failure(
self, mock_start, mock_get_session, mock_qs, processor
):
- """When start_research_process raises, active record is deleted (line 305)."""
- # Session 1: create record (success)
- # Session 2: cleanup after start_research_process failure — query, find, delete
+ """When start_research_process raises, the active record must be
+ deleted AND the ResearchHistory row marked FAILED."""
+ from local_deep_research.constants import ResearchStatus
+ from local_deep_research.database.models import (
+ ResearchHistory,
+ UserActiveResearch,
+ )
+
active_record = Mock()
+ research_row = Mock()
session1 = Mock() # Create record session
session2 = Mock() # Cleanup session
- q2 = Mock()
- q2.filter_by.return_value = q2
- q2.first.return_value = active_record
- session2.query.return_value = q2
+
+ def _query(model):
+ q = Mock()
+ 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
+
+ session2.query.side_effect = _query
sessions = [session1, session2]
call_count = [0]
@@ -299,8 +315,10 @@ class TestStartResearchDirectlyCleanup:
mode="quick",
)
- # The cleanup session should delete the active record
+ # Cleanup session deletes the active record AND marks FAILED.
session2.delete.assert_called_once_with(active_record)
+ assert research_row.status == ResearchStatus.FAILED
+ session2.commit.assert_called()
@patch("local_deep_research.web.queue.processor_v2.get_user_db_session")
@patch("local_deep_research.web.queue.processor_v2.start_research_process")
diff --git a/tests/web/queue/test_processor_v2_coverage.py b/tests/web/queue/test_processor_v2_coverage.py
index b51c4b3322..3a81156144 100644
--- a/tests/web/queue/test_processor_v2_coverage.py
+++ b/tests/web/queue/test_processor_v2_coverage.py
@@ -169,17 +169,36 @@ class TestStartResearchDirectlyErrors:
proc._start_research_directly("alice", "r1", "secret", query="q")
def test_start_research_process_exception_cleans_up_active_record(self):
- """When start_research_process raises the active record should be deleted."""
+ """When start_research_process raises the active record should be
+ deleted AND the ResearchHistory row marked FAILED."""
+ from local_deep_research.constants import ResearchStatus
+ from local_deep_research.database.models import (
+ ResearchHistory,
+ UserActiveResearch,
+ )
+
proc = _make_processor()
- mock_session = MagicMock()
active_record = MagicMock()
- mock_session.query.return_value.filter_by.return_value.first.return_value = active_record
+ research_row = MagicMock()
- call_count = {"n": 0}
+ 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):
- call_count["n"] += 1
cm = MagicMock()
cm.__enter__ = MagicMock(return_value=mock_session)
cm.__exit__ = MagicMock(return_value=False)
@@ -192,13 +211,14 @@ class TestStartResearchDirectlyErrors:
side_effect=RuntimeError("thread error"),
),
patch(f"{MODULE}.UserQueueService"),
- patch(f"{MODULE}.UserActiveResearch"),
patch(f"{MODULE}.logger"),
):
proc._start_research_directly("alice", "r1", "secret", query="q")
- # Cleanup path: delete the active record
+ # Cleanup path: delete active record AND mark research FAILED.
mock_session.delete.assert_called_once_with(active_record)
+ assert research_row.status == ResearchStatus.FAILED
+ mock_session.commit.assert_called()
# ---------------------------------------------------------------------------