~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): close race + thread-safety gaps in _start_research (#3506)
LearningCircuit919c91aa1a0d
diff --git a/src/local_deep_research/web/queue/processor_v2.py b/src/local_deep_research/web/queue/processor_v2.pyindex c381886453..d3da0312d3 100644--- a/src/local_deep_research/web/queue/processor_v2.py+++ b/src/local_deep_research/web/queue/processor_v2.py@@ -20,6 +20,7 @@ from ...database.models import (from ...database.queue_service import UserQueueServicefrom ...database.session_context import get_user_db_sessionfrom ...database.session_passwords import session_password_store+from ...exceptions import DuplicateResearchErrorfrom ...notifications.queue_helpers import (send_research_completed_notification_from_session,send_research_failed_notification_from_session,@@ -85,7 +86,11 @@ class QueueProcessorV2:# resets the counter and the research gets a fresh N retries,# which is the desired behavior if the underlying system issue# (thread pool, memory) cleared.+ # Access is guarded by _spawn_retry_counts_lock because the+ # increment path is a read-modify-write and the loop and direct+ # request paths can interleave.self._spawn_retry_counts: dict[str, int] = {}+ self._spawn_retry_counts_lock = threading.Lock()def _get_user_critical_lock(self, username: str) -> threading.Lock:"""Get (or lazily create) the per-user lock used to serialise the@@ -98,6 +103,17 @@ class QueueProcessorV2:self._user_critical_locks[username] = lockreturn lock+ def _bump_spawn_retry_count(self, research_id: str) -> int:+ """Atomically increment and return the spawn-retry counter for+ ``research_id``. Extracted so tests can exercise the real+ locked increment path instead of duplicating the lock in the+ test worker (which would be a tautology).+ """+ with self._spawn_retry_counts_lock:+ attempts = self._spawn_retry_counts.get(research_id, 0) + 1+ self._spawn_retry_counts[research_id] = attempts+ return attempts+def start(self):"""Start the queue processor thread."""if self.running:@@ -598,6 +614,70 @@ class QueueProcessorV2:logger.exception(f"Error processing queue for user {username}")return False # Keep checking - errors might be temporary+ def _reclaim_stranded_queue_rows(self, db_session, username: str) -> int:+ """Reclaim queue rows stranded by a crash or restart.++ A row is stranded when ``is_processing=True`` but no live thread+ exists in ``_active_research`` for its ``research_id``. This can+ happen after a crash/restart between the pre-spawn IN_PROGRESS+ commit and the queue-row deletion in ``_start_queued_researches``+ — the row is invisible to the normal ``is_processing=False``+ query and would never be retried.++ Reverts ``QueuedResearch.is_processing`` to False and — if+ ``ResearchHistory.status`` is still IN_PROGRESS with no live+ thread — reverts that to QUEUED so the next tick can freshly+ spawn. Returns the number of rows reclaimed.+ """+ from ..routes.globals import is_research_active++ stranded = (+ db_session.query(QueuedResearch)+ .filter_by(username=username, is_processing=True)+ .all()+ )+ reclaimed = 0+ for row in stranded:+ if is_research_active(row.research_id):+ # A legitimate in-flight claim; don't touch.+ continue+ row.is_processing = False+ research = (+ db_session.query(ResearchHistory)+ .filter_by(id=row.research_id)+ .first()+ )+ status_changed = (+ research is not None+ and research.status == ResearchStatus.IN_PROGRESS+ )+ if status_changed:+ research.status = ResearchStatus.QUEUED+ reclaimed += 1+ logger.warning(+ f"Reclaimed stranded queue row for research "+ f"{row.research_id} (user {username}): no live thread, "+ "resetting is_processing=False"+ + (" and status=QUEUED" if status_changed else "")+ )+ if reclaimed:+ try:+ db_session.commit()+ except Exception:+ logger.exception(+ "Failed to commit reclaim of stranded rows for "+ f"user {username}"+ )+ try:+ db_session.rollback()+ except Exception:+ logger.debug(+ "Rollback after reclaim failure",+ exc_info=True,+ )+ return 0+ return reclaimed+def _start_queued_researches(self,db_session,@@ -607,6 +687,11 @@ class QueueProcessorV2:available_slots: int,):"""Start queued researches up to available slots."""+ # Before picking work, reclaim any rows stranded by a prior+ # crash — otherwise they are invisible to the is_processing=False+ # filter below and would never retry.+ self._reclaim_stranded_queue_rows(db_session, username)+# Get queued researchesqueued = (db_session.query(QueuedResearch)@@ -659,7 +744,8 @@ class QueueProcessorV2:# Success — clear any prior spawn-failure count and# remove the queue row.- self._spawn_retry_counts.pop(research_id, None)+ with self._spawn_retry_counts_lock:+ self._spawn_retry_counts.pop(research_id, None)db_session.delete(queued_research)db_session.commit()@@ -667,6 +753,51 @@ class QueueProcessorV2:f"Started queued research {research_id} for user {username}")+ except DuplicateResearchError:+ # A live thread already exists for this research_id — a+ # previous attempt spawned successfully but its post-spawn+ # commit (UserActiveResearch row) failed, so the queue row+ # is still here asking us to retry. Treat as started: clear+ # the queue row and the retry counter, and do NOT increment+ # the counter or fall through to the FAILED/notify path,+ # which would terminate-status a live thread.+ logger.warning(+ f"Research {research_id} already has a live thread "+ "(prior attempt's post-spawn commit likely failed); "+ "treating as started and clearing queue row"+ )+ with self._spawn_retry_counts_lock:+ self._spawn_retry_counts.pop(research_id, None)+ try:+ db_session.rollback()+ except Exception:+ logger.debug(+ "Rollback before dup cleanup",+ exc_info=True,+ )+ try:+ fresh_queued = (+ db_session.query(QueuedResearch)+ .filter_by(username=username, research_id=research_id)+ .first()+ )+ if fresh_queued:+ db_session.delete(fresh_queued)+ db_session.commit()+ except Exception:+ logger.exception(+ "Failed to delete queue row after "+ f"DuplicateResearchError for research {research_id}"+ )+ try:+ db_session.rollback()+ except Exception:+ logger.debug(+ "Rollback after dup cleanup failure",+ exc_info=True,+ )+ continue+except Exception:logger.exception(f"Error starting queued research {research_id}"@@ -681,8 +812,7 @@ class QueueProcessorV2:exc_info=True,)- attempts = self._spawn_retry_counts.get(research_id, 0) + 1- self._spawn_retry_counts[research_id] = attempts+ attempts = self._bump_spawn_retry_count(research_id)# Re-query in case rollback expired the ORM object.fresh_queued = (@@ -693,9 +823,9 @@ class QueueProcessorV2:if attempts < SPAWN_RETRY_LIMIT:# Transient failure — allow the next loop tick to- # retry. _start_research now mutates no DB state- # before the spawn succeeds, so the only fix-up- # needed is resetting is_processing.+ # retry. _start_research rolls back its own+ # IN_PROGRESS write on spawn failure, so the only+ # fix-up needed here is resetting is_processing.logger.warning(f"Spawn failed for research {research_id} "f"(attempt {attempts}/{SPAWN_RETRY_LIMIT}), "@@ -721,11 +851,16 @@ class QueueProcessorV2:# Exhausted retries — mark terminal FAILED, delete the# queue row to stop re-dispatch, and notify the user.- logger.exception(+ # Use logger.warning (not logger.exception) because the+ # spawn traceback was already logged at the top of this+ # except block; re-logging with exc_info emits a second+ # full traceback.+ logger.warning(f"Spawn failed for research {research_id} "f"after {attempts} attempts; marking FAILED")- self._spawn_retry_counts.pop(research_id, None)+ with self._spawn_retry_counts_lock:+ self._spawn_retry_counts.pop(research_id, None)try:research = (db_session.query(ResearchHistory)@@ -771,23 +906,50 @@ class QueueProcessorV2:):"""Start a queued research.- Spawns the background thread first, then persists state. If- ``start_research_process`` raises, no DB mutation has happened- yet, so the caller's error handler can safely retry without- having to roll back IN_PROGRESS status or a pending active- record.+ Commits ``ResearchHistory.status = IN_PROGRESS`` BEFORE spawning+ the thread. If we did this after, a fast-completing thread+ (which opens its own DB session) could write ``COMPLETED`` and+ then our post-spawn commit would overwrite that with+ ``IN_PROGRESS``, stranding the research as stuck IN_PROGRESS+ after it had already finished.++ If ``start_research_process`` raises, reset status back to+ ``QUEUED`` and re-raise so the caller's 3-strike retry logic+ handles it. ``DuplicateResearchError`` is re-raised as-is+ because a thread is already running for this research; mutating+ status further would be wrong."""+ research_id = queued_research.research_idresearch = (- db_session.query(ResearchHistory)- .filter_by(id=queued_research.research_id)- .first()+ db_session.query(ResearchHistory).filter_by(id=research_id).first())if not research:- raise ValueError(- f"Research {queued_research.research_id} not found"+ raise ValueError(f"Research {research_id} not found")++ # Guard against re-entering _start_research on a retry when a+ # prior attempt's post-spawn UserActiveResearch commit failed:+ # - IN_PROGRESS means the prior thread is (or was) running.+ # - COMPLETED/FAILED means the prior thread already finished+ # and cleaned itself up out of _active_research, so a bare+ # retry would both overwrite the terminal status with+ # IN_PROGRESS and then spawn a *second* thread (because+ # check_and_start_research sees no live entry), re-running+ # the whole research.+ # In all three cases the correct behavior is the same: raise+ # DuplicateResearchError so the caller's existing dup branch+ # deletes the queue row without mutating status or notifying.+ if research.status != ResearchStatus.QUEUED:+ raise DuplicateResearchError(+ f"Research {research_id} has non-QUEUED status "+ f"{research.status}; not re-spawning")+ # Claim IN_PROGRESS before spawn to close the+ # thread-completes-before-parent-commits race.+ research.status = ResearchStatus.IN_PROGRESS+ db_session.commit()+# Extract settingssettings_snapshot = queued_research.settings_snapshot or {}@@ -802,42 +964,88 @@ class QueueProcessorV2:submission_params = settings_snapshotcomplete_settings = {}- # Spawn first. If this raises, caller retries with no leftover- # DB state to clean up.- research_thread = start_research_process(- queued_research.research_id,- queued_research.query,- queued_research.mode,- run_research_process,- username=username,- user_password=password, # Pass password for metrics- model_provider=submission_params.get("model_provider"),- model=submission_params.get("model"),- custom_endpoint=submission_params.get("custom_endpoint"),- search_engine=submission_params.get("search_engine"),- max_results=submission_params.get("max_results"),- time_period=submission_params.get("time_period"),- iterations=submission_params.get("iterations"),- questions_per_iteration=submission_params.get(- "questions_per_iteration"- ),- strategy=submission_params.get("strategy", "source-based"),- settings_snapshot=complete_settings,- )-- # Thread is running. Persist state. If this commit fails the- # thread still runs and writes its own terminal status via- # queue_error_update; logging is sufficient.- research.status = ResearchStatus.IN_PROGRESS+ try:+ research_thread = start_research_process(+ research_id,+ queued_research.query,+ queued_research.mode,+ run_research_process,+ username=username,+ user_password=password, # Pass password for metrics+ model_provider=submission_params.get("model_provider"),+ model=submission_params.get("model"),+ custom_endpoint=submission_params.get("custom_endpoint"),+ search_engine=submission_params.get("search_engine"),+ max_results=submission_params.get("max_results"),+ time_period=submission_params.get("time_period"),+ iterations=submission_params.get("iterations"),+ questions_per_iteration=submission_params.get(+ "questions_per_iteration"+ ),+ strategy=submission_params.get("strategy", "source-based"),+ settings_snapshot=complete_settings,+ )+ except DuplicateResearchError:+ # A live thread already exists for this research_id (e.g.+ # previous attempt's post-spawn commit failed). Do NOT+ # reset status — that would contradict the running thread.+ raise+ except Exception:+ # Genuine spawn failure: no thread exists. Roll back the+ # IN_PROGRESS claim so the retry sees a clean QUEUED row.+ try:+ research.status = ResearchStatus.QUEUED+ db_session.commit()+ except Exception:+ logger.exception(+ "Failed to reset ResearchHistory.status to QUEUED "+ f"after spawn failure for research {research_id}"+ )+ try:+ db_session.rollback()+ except Exception:+ logger.debug(+ "Rollback after status-reset failure",+ exc_info=True,+ )+ raise++ # Thread is running. Record the active-research row. If this+ # commit fails the live thread is unrecorded but still running.+ # Raise DuplicateResearchError instead of letting a generic+ # exception propagate, so the caller's dup branch cleans up the+ # queue row without bumping the retry counter — if we let this+ # count as a spawn failure, three consecutive post-spawn commit+ # failures (or one at LIMIT-1) would push the counter to+ # SPAWN_RETRY_LIMIT and mark a LIVE thread as terminal FAILED.active_record = UserActiveResearch(username=username,- research_id=queued_research.research_id,+ research_id=research_id,status=ResearchStatus.IN_PROGRESS,thread_id=str(research_thread.ident),settings_snapshot=queued_research.settings_snapshot,)- db_session.add(active_record)- db_session.commit()+ try:+ db_session.add(active_record)+ db_session.commit()+ except Exception as e:+ logger.exception(+ "Failed to persist UserActiveResearch after successful "+ f"spawn for research {research_id}; thread is live. "+ "Raising DuplicateResearchError so the caller's dup "+ "branch deletes the queue row without penalising retries."+ )+ try:+ db_session.rollback()+ except Exception:+ logger.debug(+ "Rollback after UserActiveResearch commit failure",+ exc_info=True,+ )+ raise DuplicateResearchError(+ f"Research {research_id} thread is live; "+ "UserActiveResearch commit failed"+ ) from edef process_user_request(self, username: str, session_id: str) -> int:"""diff --git a/tests/web/queue/test_processor_v2_concurrency.py b/tests/web/queue/test_processor_v2_concurrency.pyindex 4fceffc133..2a52971cc5 100644--- a/tests/web/queue/test_processor_v2_concurrency.py+++ b/tests/web/queue/test_processor_v2_concurrency.py@@ -264,6 +264,376 @@ class TestStartQueuedResearchesErrorRecovery:mock_session.refresh.assert_not_called()mock_queue_service.update_task_status.assert_not_called()+ def test_duplicate_research_error_deletes_queue_row_and_does_not_retry(+ self, processor+ ):+ """DuplicateResearchError means a live thread already exists (prior+ attempt's post-spawn commit failed). The queue row must be deleted,+ the retry counter cleared, and the failure-notification path must+ NOT run — that would terminate-status a research that is actually+ running."""+ from local_deep_research.exceptions import DuplicateResearchError++ queued = Mock()+ queued.is_processing = False+ queued.research_id = "res-dup"++ mock_session = Mock()+ mock_query = Mock()+ mock_query.filter_by.return_value = mock_query+ mock_query.order_by.return_value = mock_query+ mock_query.limit.return_value = mock_query+ mock_query.all.return_value = [queued]+ # The dup-cleanup path re-queries the queued row before deleting.+ mock_query.first.return_value = queued+ mock_session.query.return_value = mock_query++ mock_queue_service = Mock()+ processor._start_research = Mock(+ side_effect=DuplicateResearchError("thread already live")+ )+ processor.notify_research_failed = Mock()++ processor._start_queued_researches(+ mock_session, mock_queue_service, "alice", "pw", 1+ )++ # Queue row deleted, counter cleared, no failure notification.+ mock_session.delete.assert_called_with(queued)+ assert "res-dup" not in processor._spawn_retry_counts+ processor.notify_research_failed.assert_not_called()++ def test_duplicate_research_error_does_not_mark_failed_at_retry_limit(+ self, processor+ ):+ """Even when the retry counter is already at SPAWN_RETRY_LIMIT - 1+ (i.e. one more bump would trigger the terminal FAILED path),+ DuplicateResearchError must NOT increment the counter or mark+ ResearchHistory.status = FAILED. A live thread is running and+ will write its own terminal status."""+ from local_deep_research.database.models import (+ QueuedResearch,+ ResearchHistory,+ )+ from local_deep_research.exceptions import DuplicateResearchError+ from local_deep_research.web.queue.processor_v2 import (+ SPAWN_RETRY_LIMIT,+ )++ queued = Mock()+ queued.is_processing = False+ queued.research_id = "res-dup-limit"++ research_row = Mock()+ # Distinct status sentinel we can check was not overwritten.+ research_row.status = "NOT-FAILED-SENTINEL"++ def _make_query(model):+ q = Mock()+ q.filter_by.return_value = q+ q.order_by.return_value = q+ q.limit.return_value = q+ if model is QueuedResearch:+ q.all.return_value = [queued]+ q.first.return_value = queued+ elif model is ResearchHistory:+ q.first.return_value = research_row+ else:+ q.all.return_value = []+ q.first.return_value = None+ return q++ mock_session = Mock()+ mock_session.query.side_effect = _make_query++ mock_queue_service = Mock()+ processor._spawn_retry_counts["res-dup-limit"] = SPAWN_RETRY_LIMIT - 1+ processor._start_research = Mock(+ side_effect=DuplicateResearchError("thread already live")+ )+ processor.notify_research_failed = Mock()++ processor._start_queued_researches(+ mock_session, mock_queue_service, "alice", "pw", 1+ )++ # Counter cleared, not incremented to SPAWN_RETRY_LIMIT.+ assert "res-dup-limit" not in processor._spawn_retry_counts+ # ResearchHistory.status untouched — live thread owns it.+ assert research_row.status == "NOT-FAILED-SENTINEL"+ # No failure notification sent to the user.+ processor.notify_research_failed.assert_not_called()++ def test_transient_failure_then_duplicate_recovers_cleanly(self, processor):+ """End-to-end of the CRITICAL scenario this PR fixes: first tick's+ spawn succeeds but the post-spawn commit fails (simulated as a+ RuntimeError from _start_research); second tick finds the live+ thread and gets DuplicateResearchError. The dup branch must+ delete the queue row, clear the counter, and NOT mark FAILED —+ exactly what the original retry loop failed to do."""+ from local_deep_research.database.models import (+ QueuedResearch,+ ResearchHistory,+ )+ from local_deep_research.exceptions import DuplicateResearchError++ queued = Mock()+ queued.is_processing = False+ queued.research_id = "res-recover"++ research_row = Mock()+ # Sentinel so we can prove status was never overwritten to FAILED.+ research_row.status = "LIVE-THREAD-OWNED-SENTINEL"++ def _make_query(model):+ q = Mock()+ q.filter_by.return_value = q+ q.order_by.return_value = q+ q.limit.return_value = q+ if model is QueuedResearch:+ q.all.return_value = [queued]+ q.first.return_value = queued+ elif model is ResearchHistory:+ q.first.return_value = research_row+ else:+ q.all.return_value = []+ q.first.return_value = None+ return q++ mock_session = Mock()+ mock_session.query.side_effect = _make_query++ mock_queue_service = Mock()+ processor.notify_research_failed = Mock()++ # Tick 1: simulate post-spawn commit failure — _start_research+ # raised after the thread was already live. The generic except+ # path bumps the counter and leaves the row for retry.+ processor._start_research = Mock(+ side_effect=RuntimeError("post-spawn commit failed")+ )+ processor._start_queued_researches(+ mock_session, mock_queue_service, "alice", "pw", 1+ )+ assert processor._spawn_retry_counts["res-recover"] == 1+ processor.notify_research_failed.assert_not_called()++ # Tick 2: the live thread from tick 1 is still running, so+ # start_research_process raises DuplicateResearchError.+ processor._start_research = Mock(+ side_effect=DuplicateResearchError("thread already live")+ )+ processor._start_queued_researches(+ mock_session, mock_queue_service, "alice", "pw", 1+ )++ # Dup branch: counter cleared, queue row deleted, FAILED never+ # written, user never notified of a failure that didn't happen.+ assert "res-recover" not in processor._spawn_retry_counts+ assert research_row.status == "LIVE-THREAD-OWNED-SENTINEL"+ processor.notify_research_failed.assert_not_called()+ # Queue row was deleted (any call with the queued row counts).+ assert any(+ call.args and call.args[0] is queued+ for call in mock_session.delete.call_args_list+ )+++# ---------------------------------------------------------------------------+# _reclaim_stranded_queue_rows — crash/restart recovery+# ---------------------------------------------------------------------------+++class TestReclaimStrandedQueueRows:+ """Verify the reclaim pass recovers queue rows stranded by a crash+ between pre-spawn commit and queue-row deletion."""++ def _make_session_with_stranded_rows(self, stranded_rows, research_rows):+ """Build a mock session that returns ``stranded_rows`` for the+ QueuedResearch is_processing=True query and per-id lookups for+ ResearchHistory."""+ from local_deep_research.database.models import (+ QueuedResearch,+ ResearchHistory,+ )++ def _make_query(model):+ q = Mock()+ q.filter_by.return_value = q+ q.order_by.return_value = q+ q.limit.return_value = q+ if model is QueuedResearch:+ q.all.return_value = stranded_rows+ q.first.return_value = None+ elif model is ResearchHistory:++ def _first():+ last_filter = q.filter_by.call_args+ rid = last_filter.kwargs.get("id") if last_filter else None+ return research_rows.get(rid)++ q.first.side_effect = _first+ else:+ q.all.return_value = []+ q.first.return_value = None+ return q++ session = Mock()+ session.query.side_effect = _make_query+ return session++ def test_reclaims_row_with_no_live_thread_and_in_progress_status(+ self, processor+ ):+ """After a crash, a row with is_processing=True + status=IN_PROGRESS+ + no live thread must be reverted to is_processing=False ++ status=QUEUED."""+ from local_deep_research.constants import ResearchStatus++ stranded = Mock()+ stranded.research_id = "res-stranded"+ stranded.is_processing = True++ research_row = Mock()+ research_row.status = ResearchStatus.IN_PROGRESS++ mock_session = self._make_session_with_stranded_rows(+ [stranded], {"res-stranded": research_row}+ )++ with patch(+ "local_deep_research.web.routes.globals.is_research_active",+ return_value=False,+ ):+ reclaimed = processor._reclaim_stranded_queue_rows(+ mock_session, "alice"+ )++ assert reclaimed == 1+ assert stranded.is_processing is False+ assert research_row.status == ResearchStatus.QUEUED+ assert mock_session.commit.called++ def test_does_not_reclaim_row_with_live_thread(self, processor):+ """A row whose research_id is in _active_research (live thread)+ must NOT be reclaimed — it's legitimately in-flight."""+ from local_deep_research.constants import ResearchStatus++ stranded = Mock()+ stranded.research_id = "res-live"+ stranded.is_processing = True++ research_row = Mock()+ research_row.status = ResearchStatus.IN_PROGRESS++ mock_session = self._make_session_with_stranded_rows(+ [stranded], {"res-live": research_row}+ )++ with patch(+ "local_deep_research.web.routes.globals.is_research_active",+ return_value=True,+ ):+ reclaimed = processor._reclaim_stranded_queue_rows(+ mock_session, "alice"+ )++ assert reclaimed == 0+ assert stranded.is_processing is True+ assert research_row.status == ResearchStatus.IN_PROGRESS+ # No commit needed when nothing was reclaimed.+ assert not mock_session.commit.called++ def test_reclaims_row_without_touching_terminal_status(self, processor):+ """If a stranded row's ResearchHistory is already COMPLETED/FAILED+ (thread finished cleanly before the crash), only reset+ is_processing; do NOT overwrite the terminal status."""+ from local_deep_research.constants import ResearchStatus++ stranded = Mock()+ stranded.research_id = "res-done"+ stranded.is_processing = True++ research_row = Mock()+ research_row.status = ResearchStatus.COMPLETED++ mock_session = self._make_session_with_stranded_rows(+ [stranded], {"res-done": research_row}+ )++ with patch(+ "local_deep_research.web.routes.globals.is_research_active",+ return_value=False,+ ):+ reclaimed = processor._reclaim_stranded_queue_rows(+ mock_session, "alice"+ )++ assert reclaimed == 1+ assert stranded.is_processing is False+ # Terminal status untouched.+ assert research_row.status == ResearchStatus.COMPLETED++ def test_no_stranded_rows_is_cheap_noop(self, processor):+ """With zero stranded rows, no commit should fire."""+ mock_session = self._make_session_with_stranded_rows([], {})++ with patch(+ "local_deep_research.web.routes.globals.is_research_active",+ return_value=False,+ ):+ reclaimed = processor._reclaim_stranded_queue_rows(+ mock_session, "alice"+ )++ assert reclaimed == 0+ assert not mock_session.commit.called++ def test_start_queued_researches_calls_reclaim_before_select(+ self, processor+ ):+ """_start_queued_researches must invoke _reclaim_stranded_queue_rows+ BEFORE the main QueuedResearch SELECT. If the order were swapped,+ rows just reclaimed (is_processing flipped to False) would still+ be invisible to the SELECT in the same tick — which is the entire+ point of the feature. Use a shared ``call_order`` list to assert+ the ordering, not just that both calls happened."""+ call_order = []++ mock_session = Mock()+ mock_query = Mock()+ mock_query.filter_by.return_value = mock_query+ mock_query.order_by.return_value = mock_query+ mock_query.limit.return_value = mock_query+ mock_query.all.return_value = []++ def _query_side_effect(*args, **kwargs):+ call_order.append("query")+ return mock_query++ mock_session.query.side_effect = _query_side_effect++ def _reclaim_side_effect(*args, **kwargs):+ call_order.append("reclaim")+ return 0++ mock_queue_service = Mock()+ processor._reclaim_stranded_queue_rows = Mock(+ side_effect=_reclaim_side_effect+ )++ processor._start_queued_researches(+ mock_session, mock_queue_service, "alice", "pw", 1+ )++ processor._reclaim_stranded_queue_rows.assert_called_once_with(+ mock_session, "alice"+ )+ # Ordering invariant: reclaim must land before the first query.+ assert call_order[0] == "reclaim", (+ f"Expected 'reclaim' first, got order: {call_order}"+ )+# ---------------------------------------------------------------------------# _start_research_directly cleanup@@ -500,6 +870,49 @@ class TestNotifyUserActivityConcurrency:assert ("alice", "sess-1") in processor._users_to_check+# ---------------------------------------------------------------------------+# _spawn_retry_counts concurrent access+# ---------------------------------------------------------------------------+++class TestSpawnRetryCountsConcurrency:+ """Verify _spawn_retry_counts increments are atomic under contention."""++ def test_concurrent_increments_do_not_lose_updates(self, processor):+ """Calls the production ``_bump_spawn_retry_count`` helper from+ many threads. Without the lock inside that helper, the+ read-modify-write loses increments under contention and the+ final count is less than ``n_threads``. With the lock, the final+ count must equal ``n_threads``. This is a real mutation test of+ the production lock — removing ``with self._spawn_retry_counts_lock:``+ from the helper makes this test fail."""+ n_threads = 50+ research_id = "contended-id"+ barrier = threading.Barrier(n_threads)+ returned_values = []+ returned_lock = threading.Lock()++ def worker():+ barrier.wait(timeout=5)+ # Call the production increment path, not the lock directly.+ attempts = processor._bump_spawn_retry_count(research_id)+ with returned_lock:+ returned_values.append(attempts)++ threads = [threading.Thread(target=worker) for _ in range(n_threads)]+ for t in threads:+ t.start()+ for t in threads:+ t.join(timeout=10)++ # Final stored count must equal the number of incrementers.+ assert processor._spawn_retry_counts[research_id] == n_threads+ # Returned values must be 1..n_threads with no duplicates — any+ # duplicate would mean two callers observed the same prior count,+ # i.e. a lost update.+ assert sorted(returned_values) == list(range(1, n_threads + 1))++# ---------------------------------------------------------------------------# Start/stop lifecycle# ---------------------------------------------------------------------------diff --git a/tests/web/queue/test_processor_v2_real.py b/tests/web/queue/test_processor_v2_real.pyindex 6b22ea3340..3d15bd43a4 100644--- a/tests/web/queue/test_processor_v2_real.py+++ b/tests/web/queue/test_processor_v2_real.py@@ -603,6 +603,8 @@ class TestStartResearch:@patch(f"{MODULE}.start_research_process")def test_legacy_format_uses_flat_dict(self, mock_start_research):"""Legacy format: flat dict used as submission_params."""+ from local_deep_research.constants import ResearchStatus+processor = _make_processor()mock_thread = Mock()@@ -611,6 +613,7 @@ class TestStartResearch:mock_session = MagicMock()mock_research = Mock()+ mock_research.status = ResearchStatus.QUEUEDmock_session.query.return_value.filter_by.return_value.first.return_value = mock_researchqueued = Mock()@@ -633,6 +636,8 @@ class TestStartResearch:@patch(f"{MODULE}.start_research_process")def test_none_settings_snapshot_handled(self, mock_start_research):"""None settings_snapshot treated as empty dict."""+ from local_deep_research.constants import ResearchStatus+processor = _make_processor()mock_thread = Mock()@@ -641,6 +646,7 @@ class TestStartResearch:mock_session = MagicMock()mock_research = Mock()+ mock_research.status = ResearchStatus.QUEUEDmock_session.query.return_value.filter_by.return_value.first.return_value = mock_researchqueued = Mock()@@ -669,6 +675,217 @@ class TestStartResearch:with pytest.raises(ValueError, match="not found"):processor._start_research(mock_session, "alice", "pw", queued)+ @patch(f"{MODULE}.start_research_process")+ def test_status_set_in_progress_before_spawn(self, mock_start_research):+ """IN_PROGRESS must be committed BEFORE start_research_process is+ called, so a fast thread cannot race ahead and have its terminal+ status overwritten by our post-spawn commit."""+ from local_deep_research.constants import ResearchStatus++ processor = _make_processor()++ mock_thread = Mock()+ mock_thread.ident = 999+ mock_start_research.return_value = mock_thread++ mock_session = MagicMock()+ mock_research = Mock()+ mock_research.status = ResearchStatus.QUEUED+ mock_session.query.return_value.filter_by.return_value.first.return_value = mock_research++ # Record the status at the moment start_research_process is called.+ status_at_spawn = {}++ def _capture_status(*args, **kwargs):+ status_at_spawn["value"] = mock_research.status+ # Capture the commit count at the moment of spawn so we can+ # assert the IN_PROGRESS commit already happened, not merely+ # that some commit happened at some point in the method.+ status_at_spawn["commit_count"] = mock_session.commit.call_count+ return mock_thread++ mock_start_research.side_effect = _capture_status++ queued = Mock()+ queued.research_id = "r-race"+ queued.query = "q"+ queued.mode = "standard"+ queued.settings_snapshot = {}++ with patch(f"{MODULE}.UserActiveResearch"):+ processor._start_research(mock_session, "alice", "pw", queued)++ assert status_at_spawn["value"] == ResearchStatus.IN_PROGRESS+ # Exactly one commit (the IN_PROGRESS write) must have already+ # run by the time start_research_process is called.+ assert status_at_spawn["commit_count"] == 1++ @patch(f"{MODULE}.start_research_process")+ def test_spawn_failure_resets_status_to_queued(self, mock_start_research):+ """On genuine spawn failure (non-duplicate), status must be rolled+ back to QUEUED so the next retry sees a clean row and the+ research is not stuck IN_PROGRESS if the retry budget is+ eventually exhausted."""+ from local_deep_research.constants import ResearchStatus++ processor = _make_processor()++ mock_start_research.side_effect = RuntimeError("spawn failed")++ mock_session = MagicMock()+ mock_research = Mock()+ mock_research.status = ResearchStatus.QUEUED+ mock_session.query.return_value.filter_by.return_value.first.return_value = mock_research++ queued = Mock()+ queued.research_id = "r-fail"+ queued.query = "q"+ queued.mode = "standard"+ queued.settings_snapshot = {}++ with pytest.raises(RuntimeError, match="spawn failed"):+ processor._start_research(mock_session, "alice", "pw", queued)++ assert mock_research.status == ResearchStatus.QUEUED+ # One commit for IN_PROGRESS before spawn, a second for the QUEUED+ # reset after spawn failed. Without the second commit the in-memory+ # attribute is rolled back but the DB still shows IN_PROGRESS, so+ # assert that both commits actually ran.+ assert mock_session.commit.call_count >= 2++ @patch(f"{MODULE}.start_research_process")+ def test_duplicate_research_error_does_not_reset_status(+ self, mock_start_research+ ):+ """DuplicateResearchError means a live thread already exists for+ this research_id (typically a retry after a post-spawn commit+ failure). Mutating status in that case would contradict the+ running thread — it must be left IN_PROGRESS."""+ from local_deep_research.constants import ResearchStatus+ from local_deep_research.exceptions import DuplicateResearchError++ processor = _make_processor()++ mock_start_research.side_effect = DuplicateResearchError(+ "thread already live"+ )++ mock_session = MagicMock()+ mock_research = Mock()+ mock_research.status = ResearchStatus.QUEUED+ mock_session.query.return_value.filter_by.return_value.first.return_value = mock_research++ queued = Mock()+ queued.research_id = "r-dup"+ queued.query = "q"+ queued.mode = "standard"+ queued.settings_snapshot = {}++ with pytest.raises(DuplicateResearchError):+ processor._start_research(mock_session, "alice", "pw", queued)++ # Status must remain IN_PROGRESS (set before spawn, never reset).+ assert mock_research.status == ResearchStatus.IN_PROGRESS++ @patch(f"{MODULE}.start_research_process")+ def test_non_queued_status_raises_duplicate_without_spawning(+ self, mock_start_research+ ):+ """If _start_research is re-entered on a retry and finds the row+ already in a non-QUEUED state (IN_PROGRESS from a prior attempt+ whose post-spawn commit failed, or terminal COMPLETED/FAILED+ because the prior thread already finished and cleaned up), it+ must raise DuplicateResearchError *without* mutating status and+ *without* calling start_research_process. Otherwise we would+ overwrite a terminal status with IN_PROGRESS and spawn a second+ thread that re-runs the whole research."""+ from local_deep_research.constants import ResearchStatus+ from local_deep_research.exceptions import DuplicateResearchError++ for starting_status in (+ ResearchStatus.IN_PROGRESS,+ ResearchStatus.COMPLETED,+ ResearchStatus.FAILED,+ ResearchStatus.SUSPENDED,+ ):+ processor = _make_processor()+ mock_start_research.reset_mock()++ mock_session = MagicMock()+ mock_research = Mock()+ mock_research.status = starting_status+ mock_session.query.return_value.filter_by.return_value.first.return_value = mock_research++ queued = Mock()+ queued.research_id = f"r-stale-{starting_status}"+ queued.query = "q"+ queued.mode = "standard"+ queued.settings_snapshot = {}++ with pytest.raises(DuplicateResearchError):+ processor._start_research(mock_session, "alice", "pw", queued)++ # Status unchanged — we did not overwrite a terminal state.+ assert mock_research.status == starting_status+ # Spawn never attempted — no risk of a second thread.+ mock_start_research.assert_not_called()+ # No commit for a status we did not change.+ mock_session.commit.assert_not_called()++ @patch(f"{MODULE}.UserActiveResearch")+ @patch(f"{MODULE}.start_research_process")+ def test_user_active_research_commit_failure_raises_duplicate(+ self, mock_start_research, mock_user_active_research+ ):+ """If the post-spawn UserActiveResearch commit fails, the thread+ is already running. We must raise DuplicateResearchError so the+ caller's dup branch deletes the queue row without bumping the+ spawn-retry counter — otherwise a commit failure at the retry+ limit would mark a LIVE thread as terminal FAILED."""+ from local_deep_research.constants import ResearchStatus+ from local_deep_research.exceptions import DuplicateResearchError++ processor = _make_processor()++ mock_thread = Mock()+ mock_thread.ident = 42+ mock_start_research.return_value = mock_thread++ mock_session = MagicMock()+ mock_research = Mock()+ mock_research.status = ResearchStatus.QUEUED+ mock_session.query.return_value.filter_by.return_value.first.return_value = mock_research++ # Two commits: one for IN_PROGRESS (succeeds), one for+ # UserActiveResearch (fails).+ commit_results = [None, RuntimeError("UAR commit failed")]++ def _commit():+ r = commit_results.pop(0)+ if isinstance(r, Exception):+ raise r++ mock_session.commit.side_effect = _commit++ queued = Mock()+ queued.research_id = "r-uar-fail"+ queued.query = "q"+ queued.mode = "standard"+ queued.settings_snapshot = {}++ with pytest.raises(DuplicateResearchError):+ processor._start_research(mock_session, "alice", "pw", queued)++ # Spawn *was* called (that's how we get into the post-spawn commit).+ mock_start_research.assert_called_once()+ # Rollback happened after the commit failure.+ assert mock_session.rollback.called+ # Status must remain IN_PROGRESS — the thread is live, resetting+ # would contradict its own writes. This is the key invariant+ # that distinguishes this branch from the generic spawn-failure+ # branch (which DOES reset to QUEUED).+ assert mock_research.status == ResearchStatus.IN_PROGRESS+# ---------------------------------------------------------------------------# process_pending_operations_for_user — progress/error updates, rollback