~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): recover retryable claims and discard finished rows (#7042)
LearningCircuite8ffb39e90b6
diff --git a/changelog.d/6147.bugfix.md b/changelog.d/6147.bugfix.mdnew file mode 100644index 0000000000..3ca8938a28--- /dev/null+++ b/changelog.d/6147.bugfix.md@@ -0,0 +1 @@+Fixed a stranded-queue-row bug where a transient research spawn failure or a crash/reclaim left `TaskMetadata.status` at `processing`. The queue counter reconcile then under-reported `queued_tasks`, the dispatch loop deregistered the user, and a re-dispatchable queued research was silently stranded even after the next login. Stranded claims now revert to `queued` (clearing `started_at`) and the queue-status counters are force-reconciled on the same tick. Finished research queue leftovers are removed without changing their terminal history or disturbing live workers.diff --git a/src/local_deep_research/web/queue/processor_v2.py b/src/local_deep_research/web/queue/processor_v2.pyindex a4937936d1..2665298da7 100644--- a/src/local_deep_research/web/queue/processor_v2.py+++ b/src/local_deep_research/web/queue/processor_v2.py@@ -11,6 +11,7 @@ from enum import Enum, autofrom typing import Any, Dict, Optionalfrom loguru import logger+from sqlalchemy import selectfrom sqlalchemy.orm import Sessionfrom ...constants import ResearchStatus@@ -1104,8 +1105,15 @@ class QueueProcessorV2:# No slots available, but queue might not be empty.return False # Keep checking- if queue_status["queued_tasks"] == 0:- # Queue is empty.+ if queue_status["queued_tasks"] == 0 and (+ db_session.query(QueuedResearch.id)+ .filter_by(username=username)+ .first()+ is None+ ):+ # A crashed claim still has a queue row but counts+ # as processing, not queued. Let dispatch reclaim it+ # before deciding this user has no pending work.return True # Remove from checkinglogger.info(@@ -1131,7 +1139,13 @@ class QueueProcessorV2:updated_status = queue_service.get_queue_status() or {"queued_tasks": 0}- return bool(updated_status["queued_tasks"] == 0)+ return bool(+ updated_status["queued_tasks"] == 0+ and db_session.query(QueuedResearch.id)+ .filter_by(username=username)+ .first()+ is None+ )except Exception as e:# ``password`` (from the session store above) is in scope —@@ -1156,48 +1170,100 @@ class QueueProcessorV2:— the row is invisible to the normal ``is_processing=False``query and would never be retried.- Reverts only rows whose parent is not database-backed IN_PROGRESS,- preserving the worker spawn-grace window. Returns the number of- rows reclaimed.+ Reclaims the ``ResearchHistory`` status and the+ ``TaskMetadata`` claim (``processing`` -> ``queued``) alongside+ ``is_processing``, so ``reconcile_research_queue_status`` keeps+ reporting the row in ``queued_tasks`` (#6147). Removes leftovers+ whose parent is already terminal, including previously released+ claims, so they cannot block later queued work. Preserves claims+ whose worker is still live. Returns the number of rows recovered."""from ..routes.globals import is_research_active+ terminal_statuses = (+ ResearchStatus.COMPLETED,+ ResearchStatus.SUSPENDED,+ ResearchStatus.FAILED,+ ResearchStatus.ERROR,+ )+ terminal_research_ids = select(ResearchHistory.id).where(+ ResearchHistory.status.in_(terminal_statuses)+ )stranded = (db_session.query(QueuedResearch)- .filter_by(username=username, is_processing=True)+ .filter_by(username=username)+ .filter(+ QueuedResearch.is_processing.is_(True)+ | QueuedResearch.research_id.in_(terminal_research_ids)+ ).all())reclaimed = 0+ finished_ids: set[str] = set()for row in stranded:if is_research_active(row.research_id):# A legitimate in-flight claim; don't touch.continue- row.is_processing = Falseresearch = (db_session.query(ResearchHistory).filter_by(id=row.research_id).first())+ if research is not None and research.status in terminal_statuses:+ finished_ids.add(row.research_id)+ continue+ row.is_processing = Falsestatus_changed = (research is not Noneand research.status == ResearchStatus.IN_PROGRESS)if status_changed:research.status = ResearchStatus.QUEUED+ metadata = (+ db_session.query(TaskMetadata)+ .filter_by(task_id=row.research_id, task_type="research")+ .first()+ )+ metadata_changed = (+ metadata is not None and metadata.status == "processing"+ )+ if metadata_changed:+ # A stranded claim has no live worker, so a 'processing'+ # TaskMetadata row is stale by definition. Reverting it+ # keeps queued_tasks accurate so the dispatch loop does+ # not deregister the user before retrying this row+ # (#6147).+ metadata.status = "queued"+ metadata.started_at = Nonereclaimed += 1logger.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 "")+ + (+ " and TaskMetadata.status=queued"+ if metadata_changed+ else ""+ ))- if reclaimed:+ if finished_ids:+ cleanup_queued_research_state(+ db_session, finished_ids, include_claimed=True+ )+ if reclaimed or finished_ids:+ reconcile_research_queue_status(db_session, force=True)if not self._commit_with_safe_rollback(db_session,f"reclaim of stranded rows for user {username}",):return 0- return reclaimed+ # Discard retry bookkeeping only after the database cleanup is+ # durable. A rollback must leave the whole claim recoverable.+ with self._spawn_retry_counts_lock:+ for research_id in finished_ids:+ self._spawn_retry_counts.pop(research_id, None)+ return reclaimed + len(finished_ids)def _sweep_missing_parent_queue_rows(self, db_session: Session, username: str@@ -1467,15 +1533,27 @@ class QueueProcessorV2:if attempts < SPAWN_RETRY_LIMIT:# Transient failure — allow the next loop tick to# retry. _start_research rolls back its own- # IN_PROGRESS write on spawn failure, so the only- # fix-up needed here is resetting is_processing.+ # IN_PROGRESS write on spawn failure, so the fix-ups+ # needed here are resetting is_processing and+ # reverting the TaskMetadata claim from+ # update_task_status("processing") above. Without+ # the revert, reconcile_research_queue_status+ # under-reports queued_tasks and+ # _process_user_queue deregisters the user before+ # this row is retried (#6147).logger.warning(f"Spawn failed for research {research_id} "f"(attempt {attempts}/{SPAWN_RETRY_LIMIT}), ""leaving queued for retry")+ # Mirror the SystemAtCapacityError branch: revert+ # the queued->processing claim so the slot returns+ # to queued_tasks instead of leaking into+ # active_tasks on every failed attempt.+ queue_service.update_task_status(research_id, "queued")if fresh_queued:fresh_queued.is_processing = False+ reconcile_research_queue_status(db_session, force=True)self._commit_with_safe_rollback(db_session,f"is_processing reset for research {research_id}",diff --git a/tests/connected/test_queue_claim_reclaim.py b/tests/connected/test_queue_claim_reclaim.pyindex ccce6c81cb..51f55178ec 100644--- a/tests/connected/test_queue_claim_reclaim.py+++ b/tests/connected/test_queue_claim_reclaim.py@@ -1,6 +1,7 @@from __future__ import annotationsimport threading+from datetime import UTC, datetimefrom uuid import uuid4import pytest@@ -9,7 +10,9 @@ from sqlalchemy import func, selectfrom local_deep_research.constants import ResearchStatusfrom local_deep_research.database.models import (QueuedResearch,+ QueueStatus,ResearchHistory,+ TaskMetadata,UserActiveResearch,)from local_deep_research.database.queue_service import UserQueueService@@ -170,3 +173,430 @@ def test_reclaim_only_resets_rows_without_a_live_research_thread(assert live_claimed_rows == 1assert live_history_status == ResearchStatus.IN_PROGRESSassert active_rows == 2+++def test_transient_spawn_failure_keeps_task_metadata_queued(+ connected_user: ConnectedUserFixture,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """#6147: a transient spawn failure must revert the TaskMetadata+ claim, otherwise reconcile_research_queue_status under-reports+ queued_tasks and the dispatch loop deregisters the user before the+ row is retried."""+ case = connected_user+ _register_connected_user(case)+ processor = QueueProcessorV2()+ research_id = str(uuid4())+ spawn_attempted = threading.Event()++ with get_user_db_session(case.username, case.password) as db_session:+ _seed_queued_research(+ db_session,+ case.username,+ QueueResearchSeed(research_id=research_id, position=1),+ )++ def fail_first_spawn(*_args, **_kwargs) -> None:+ spawn_attempted.set()+ raise RuntimeError("transient spawn failure")++ monkeypatch.setattr(+ "local_deep_research.web.queue.processor_v2.start_research_process",+ fail_first_spawn,+ )++ with get_user_db_session(case.username, case.password) as db_session:+ processor._start_queued_researches(+ db_session,+ UserQueueService(db_session),+ case.username,+ case.password,+ 1,+ )++ assert spawn_attempted.is_set()+ with get_user_db_session(case.username, case.password) as db_session:+ assert _queue_state(db_session, research_id) == (+ ResearchStatus.QUEUED,+ 1,+ 0,+ "queued",+ 0,+ 0,+ 1,+ )+++def test_reclaim_resets_stranded_task_metadata_to_queued(+ connected_user: ConnectedUserFixture,+) -> None:+ """#6147: crash-reclaim must reset a stranded 'processing'+ TaskMetadata row back to 'queued' so the re-dispatchable row keeps+ counting toward queued_tasks."""+ case = connected_user+ _register_connected_user(case)+ processor = QueueProcessorV2()+ stranded_id = str(uuid4())++ with get_user_db_session(case.username, case.password) as db_session:+ _seed_queued_research(+ db_session,+ case.username,+ QueueResearchSeed(+ research_id=stranded_id,+ position=1,+ status=ResearchStatus.IN_PROGRESS,+ is_processing=True,+ ),+ )+ # Model the pre-crash claimed state: TaskMetadata flipped to+ # 'processing' and the queue-status counters leaked into+ # active_tasks.+ metadata = (+ db_session.query(TaskMetadata)+ .filter_by(task_id=stranded_id, task_type="research")+ .one()+ )+ metadata.status = "processing"+ metadata.started_at = datetime.now(UTC)+ queue_status = db_session.query(QueueStatus).one()+ queue_status.active_tasks = 1+ queue_status.queued_tasks = 0+ db_session.commit()++ with get_user_db_session(case.username, case.password) as db_session:+ reclaimed = processor._reclaim_stranded_queue_rows(+ db_session,+ case.username,+ )++ assert reclaimed == 1+ with get_user_db_session(case.username, case.password) as db_session:+ assert _queue_state(db_session, stranded_id) == (+ ResearchStatus.QUEUED,+ 1,+ 0,+ "queued",+ 0,+ 0,+ 1,+ )+ started_at = db_session.execute(+ select(TaskMetadata.started_at).where(+ TaskMetadata.task_id == stranded_id+ )+ ).scalar_one()+ assert started_at is None++[email protected]("recovery_commit_fails", [False, True])+def test_polling_recovers_claimed_row_when_queued_counter_is_zero(+ connected_user: ConnectedUserFixture,+ monkeypatch: pytest.MonkeyPatch,+ recovery_commit_fails: bool,+) -> None:+ """A crash or failed recovery commit must not deregister pending work."""+ case = connected_user+ _register_connected_user(case)+ processor = QueueProcessorV2()+ research_id = str(uuid4())+ spawn_attempted = threading.Event()++ monkeypatch.setattr(+ "local_deep_research.web.queue.processor_v2.session_password_store.get_session_password",+ lambda *_args: case.password,+ )+ assert processor._process_user_queue(case.username, "poll-session") is True++ with get_user_db_session(case.username, case.password) as db_session:+ _seed_queued_research(+ db_session,+ case.username,+ QueueResearchSeed(+ research_id=research_id,+ position=1,+ status=ResearchStatus.IN_PROGRESS,+ is_processing=True,+ ),+ )+ metadata = (+ db_session.query(TaskMetadata).filter_by(task_id=research_id).one()+ )+ metadata.status = "processing"+ metadata.started_at = datetime.now(UTC)+ queue_status = db_session.query(QueueStatus).one()+ queue_status.active_tasks = 1+ queue_status.queued_tasks = 0+ db_session.commit()++ def reject_at_capacity(*_args, **_kwargs) -> None:+ spawn_attempted.set()+ raise SystemAtCapacityError("connected queue capacity boundary")++ monkeypatch.setattr(+ "local_deep_research.web.queue.processor_v2.start_research_process",+ reject_at_capacity,+ )+ if recovery_commit_fails:+ commit = processor._commit_with_safe_rollback++ def fail_recovery_commit(db_session, operation):+ if operation.startswith("reclaim of stranded rows"):+ db_session.rollback()+ return False+ return commit(db_session, operation)++ monkeypatch.setattr(+ processor, "_commit_with_safe_rollback", fail_recovery_commit+ )+ assert (+ processor._process_user_queue(case.username, "poll-session")+ is False+ )+ assert not spawn_attempted.is_set()+ monkeypatch.setattr(processor, "_commit_with_safe_rollback", commit)++ assert processor._process_user_queue(case.username, "poll-session") is False+ assert spawn_attempted.is_set()+ with get_user_db_session(case.username, case.password) as db_session:+ assert _queue_state(db_session, research_id) == (+ ResearchStatus.QUEUED,+ 1,+ 0,+ "queued",+ 0,+ 0,+ 1,+ )+++ "status",+ [+ ResearchStatus.COMPLETED,+ ResearchStatus.SUSPENDED,+ ResearchStatus.FAILED,+ ResearchStatus.ERROR,+ ],+)[email protected]("is_processing", [False, True])+def test_polling_discards_finished_queue_rows(+ connected_user: ConnectedUserFixture,+ monkeypatch: pytest.MonkeyPatch,+ status: ResearchStatus,+ is_processing: bool,+) -> None:+ """A finished parent cannot be re-dispatched or counted as queued work."""+ from unittest.mock import Mock++ case = connected_user+ _register_connected_user(case)+ processor = QueueProcessorV2()+ research_id = str(uuid4())+ processor._spawn_retry_counts[research_id] = 2+ spawn = Mock()+ processor.notify_research_failed = Mock()+ monkeypatch.setattr(+ "local_deep_research.web.queue.processor_v2.start_research_process",+ spawn,+ )+ monkeypatch.setattr(+ "local_deep_research.web.queue.processor_v2.session_password_store.get_session_password",+ lambda *_args: case.password,+ )+ with get_user_db_session(case.username, case.password) as db_session:+ _seed_queued_research(+ db_session,+ case.username,+ QueueResearchSeed(+ research_id=research_id,+ position=1,+ status=status,+ is_processing=is_processing,+ ),+ )+ UserQueueService(db_session).update_task_status(+ research_id, "processing"+ )++ assert processor._process_user_queue(case.username, "poll-session") is True+ assert processor._process_user_queue(case.username, "poll-session") is True+ with get_user_db_session(case.username, case.password) as db_session:+ assert _queue_state(db_session, research_id) == (+ status,+ 0,+ 0,+ None,+ 0,+ 0,+ 0,+ )+ assert research_id not in processor._spawn_retry_counts+ spawn.assert_not_called()+ processor.notify_research_failed.assert_not_called()+++def test_finished_queue_cleanup_keeps_live_worker_claim(+ connected_user: ConnectedUserFixture,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The worker may set a terminal status before its final bookkeeping."""+ case = connected_user+ _register_connected_user(case)+ processor = QueueProcessorV2()+ research_id = str(uuid4())+ monkeypatch.setattr(+ "local_deep_research.web.queue.processor_v2.session_password_store.get_session_password",+ lambda *_args: case.password,+ )+ with get_user_db_session(case.username, case.password) as db_session:+ _seed_queued_research(+ db_session,+ case.username,+ QueueResearchSeed(+ research_id=research_id,+ position=1,+ status=ResearchStatus.COMPLETED,+ is_processing=True,+ ),+ )+ UserQueueService(db_session).update_task_status(+ research_id, "processing"+ )+ set_active_research(research_id, {"thread": threading.current_thread()})+ try:+ assert (+ processor._process_user_queue(case.username, "poll-session")+ is False+ )+ with get_user_db_session(case.username, case.password) as db_session:+ assert _queue_state(db_session, research_id) == (+ ResearchStatus.COMPLETED,+ 1,+ 1,+ "processing",+ 0,+ 1,+ 0,+ )+ finally:+ remove_active_research(research_id)+ assert processor._process_user_queue(case.username, "poll-session") is True+++def test_finished_queue_cleanup_rolls_back_before_retry(+ connected_user: ConnectedUserFixture,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ case = connected_user+ _register_connected_user(case)+ processor = QueueProcessorV2()+ research_id = str(uuid4())+ processor._spawn_retry_counts[research_id] = 2+ monkeypatch.setattr(+ "local_deep_research.web.queue.processor_v2.session_password_store.get_session_password",+ lambda *_args: case.password,+ )+ with get_user_db_session(case.username, case.password) as db_session:+ _seed_queued_research(+ db_session,+ case.username,+ QueueResearchSeed(+ research_id=research_id,+ position=1,+ status=ResearchStatus.SUSPENDED,+ is_processing=True,+ ),+ )+ UserQueueService(db_session).update_task_status(+ research_id, "processing"+ )+ commit = processor._commit_with_safe_rollback++ def fail_recovery_commit(db_session, operation):+ if operation.startswith("reclaim of stranded rows"):+ db_session.rollback()+ return False+ return commit(db_session, operation)++ monkeypatch.setattr(+ processor, "_commit_with_safe_rollback", fail_recovery_commit+ )+ assert processor._process_user_queue(case.username, "poll-session") is False+ with get_user_db_session(case.username, case.password) as db_session:+ assert _queue_state(db_session, research_id) == (+ ResearchStatus.SUSPENDED,+ 1,+ 1,+ "processing",+ 0,+ 1,+ 0,+ )+ assert processor._spawn_retry_counts[research_id] == 2+ monkeypatch.setattr(processor, "_commit_with_safe_rollback", commit)+ assert processor._process_user_queue(case.username, "poll-session") is True+ assert research_id not in processor._spawn_retry_counts++[email protected]("is_processing", [False, True])+def test_finished_queue_row_does_not_starve_waiting_research(+ connected_user: ConnectedUserFixture,+ monkeypatch: pytest.MonkeyPatch,+ is_processing: bool,+) -> None:+ case = connected_user+ _register_connected_user(case)+ processor = QueueProcessorV2()+ finished_id, waiting_id = str(uuid4()), str(uuid4())+ spawned = []+ with get_user_db_session(case.username, case.password) as db_session:+ for seed in (+ QueueResearchSeed(+ research_id=finished_id,+ position=1,+ status=ResearchStatus.COMPLETED,+ is_processing=is_processing,+ ),+ QueueResearchSeed(research_id=waiting_id, position=2),+ ):+ _seed_queued_research(db_session, case.username, seed)+ UserQueueService(db_session).update_task_status(+ finished_id, "completed"+ )++ def spawn(research_id, *_args, **_kwargs):+ spawned.append(research_id)+ return threading.current_thread()++ monkeypatch.setattr(+ "local_deep_research.web.queue.processor_v2.start_research_process",+ spawn,+ )+ for _ in range(2):+ with get_user_db_session(case.username, case.password) as db_session:+ processor._start_queued_researches(+ db_session,+ UserQueueService(db_session),+ case.username,+ case.password,+ 1,+ )+ assert spawned == [waiting_id]+ with get_user_db_session(case.username, case.password) as db_session:+ assert (+ db_session.query(ResearchHistory)+ .filter_by(id=finished_id)+ .one()+ .status+ == ResearchStatus.COMPLETED+ )+ assert _queue_state(db_session, waiting_id) == (+ ResearchStatus.IN_PROGRESS,+ 0,+ 0,+ "processing",+ 1,+ 1,+ 0,+ )diff --git a/tests/web/queue/test_processor_v2_concurrency.py b/tests/web/queue/test_processor_v2_concurrency.pyindex d04522a739..b0b8fdc704 100644--- a/tests/web/queue/test_processor_v2_concurrency.py+++ b/tests/web/queue/test_processor_v2_concurrency.py@@ -228,6 +228,7 @@ class TestStartQueuedResearchesErrorRecovery:def _make_query(model):q = Mock()q.filter_by.return_value = q+ q.filter.return_value = qq.order_by.return_value = qq.limit.return_value = qif model is QueuedResearch:@@ -290,6 +291,7 @@ class TestStartQueuedResearchesErrorRecovery:def _make_query(model):q = Mock()q.filter_by.return_value = q+ q.filter.return_value = qq.order_by.return_value = qq.limit.return_value = qif model is QueuedResearch:@@ -338,6 +340,7 @@ class TestStartQueuedResearchesErrorRecovery:mock_session = Mock()mock_query = Mock()mock_query.filter_by.return_value = mock_query+ mock_query.filter.return_value = mock_querymock_query.order_by.return_value = mock_querymock_query.limit.return_value = mock_querymock_query.all.return_value = [queued]@@ -364,6 +367,7 @@ class TestStartQueuedResearchesErrorRecovery:mock_session = Mock()mock_query = Mock()mock_query.filter_by.return_value = mock_query+ mock_query.filter.return_value = mock_querymock_query.order_by.return_value = mock_querymock_query.limit.return_value = mock_querymock_query.all.return_value = [queued]@@ -383,6 +387,7 @@ class TestStartQueuedResearchesErrorRecovery:mock_session = Mock()mock_query = Mock()mock_query.filter_by.return_value = mock_query+ mock_query.filter.return_value = mock_querymock_query.order_by.return_value = mock_querymock_query.limit.return_value = mock_querymock_query.all.return_value = []@@ -444,6 +449,7 @@ class TestStartQueuedResearchesErrorRecovery:mock_session = Mock()mock_query = Mock()mock_query.filter_by.return_value = mock_query+ mock_query.filter.return_value = mock_querymock_query.order_by.return_value = mock_querymock_query.limit.return_value = mock_querymock_query.all.return_value = [queued]@@ -494,6 +500,7 @@ class TestStartQueuedResearchesErrorRecovery:def _make_query(model):q = Mock()q.filter_by.return_value = q+ q.filter.return_value = qq.order_by.return_value = qq.limit.return_value = qif model is QueuedResearch:@@ -551,6 +558,7 @@ class TestStartQueuedResearchesErrorRecovery:def _make_query(model):q = Mock()q.filter_by.return_value = q+ q.filter.return_value = qq.order_by.return_value = qq.limit.return_value = qif model is QueuedResearch:@@ -623,6 +631,7 @@ class TestReclaimStrandedQueueRows:def _make_query(model):q = Mock()q.filter_by.return_value = q+ q.filter.return_value = qq.order_by.return_value = qq.limit.return_value = qif model is QueuedResearch:@@ -709,8 +718,8 @@ class TestReclaimStrandedQueueRows: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."""+ (thread finished cleanly before the crash), discard its queue state+ without overwriting the terminal status."""from local_deep_research.constants import ResearchStatusstranded = Mock()@@ -724,16 +733,23 @@ class TestReclaimStrandedQueueRows:[stranded], {"res-done": research_row})- with patch(- "local_deep_research.web.routes.globals.is_research_active",- return_value=False,+ with (+ patch(+ "local_deep_research.web.routes.globals.is_research_active",+ return_value=False,+ ),+ patch(+ "local_deep_research.web.queue.processor_v2.cleanup_queued_research_state"+ ) as cleanup,):reclaimed = processor._reclaim_stranded_queue_rows(mock_session, "alice")assert reclaimed == 1- assert stranded.is_processing is False+ cleanup.assert_called_once_with(+ mock_session, {"res-done"}, include_claimed=True+ )# Terminal status untouched.assert research_row.status == ResearchStatus.COMPLETEDdiff --git a/tests/web/queue/test_processor_v2_real.py b/tests/web/queue/test_processor_v2_real.pyindex 298e282c4b..c951ff405e 100644--- a/tests/web/queue/test_processor_v2_real.py+++ b/tests/web/queue/test_processor_v2_real.py@@ -788,6 +788,7 @@ class TestProcessUserQueue:mock_session.__enter__ = Mock(return_value=mock_session)mock_session.__exit__ = Mock(return_value=False)mock_session.query.return_value.filter_by.return_value.count.return_value = 0+ mock_session.query.return_value.filter_by.return_value.first.return_value = Nonemock_get_session.return_value = mock_sessionmock_settings = Mock()diff --git a/tests/web/queue/test_queued_research_reconciliation.py b/tests/web/queue/test_queued_research_reconciliation.pyindex dcf7e53331..7197b8e744 100644--- a/tests/web/queue/test_queued_research_reconciliation.py+++ b/tests/web/queue/test_queued_research_reconciliation.py@@ -166,7 +166,14 @@ def test_sweep_commit_failure_stops_dispatch_before_reclaim_or_claim(processor.notify_research_failed.assert_not_called()-def test_process_user_queue_sweeps_before_stale_status_capacity_gates() -> None:+ ("remaining_queue_row", "expected_empty"),+ [(None, True), ((1,), False)],+ ids=["drained", "persisted-row"],+)+def test_process_user_queue_sweeps_before_stale_status_capacity_gates(+ remaining_queue_row: tuple[int] | None, expected_empty: bool+) -> None:from local_deep_research.web.queue.processor_v2 import QueueProcessorV2# Given: stale full-and-empty counters that reconciliation refreshes.@@ -177,6 +184,7 @@ def test_process_user_queue_sweeps_before_stale_status_capacity_gates() -> None:mock_session.__enter__ = Mock(return_value=mock_session)mock_session.__exit__ = Mock(return_value=False)mock_session.query.return_value.filter_by.return_value.count.return_value = 0+ mock_session.query.return_value.filter_by.return_value.first.return_value = remaining_queue_rowqueue_service = Mock()def sweep(_db_session: Session, _username: str) -> Mock:@@ -216,8 +224,10 @@ def test_process_user_queue_sweeps_before_stale_status_capacity_gates() -> None:result = processor._process_user_queue("alice", "session")# Then: refreshed counters admit the queued research despite stale gates.- assert result is Trueassert call_order[:2] == ["sweep", "status"]processor._start_queued_researches.assert_called_once_with(mock_session, queue_service, "alice", "pw", 1)+ # A zero counter after dispatch permits deregistration only when no+ # persisted queue row remains for the next polling attempt.+ assert result is expected_empty